diff --git a/dev/inc/size-budgets.json b/dev/inc/size-budgets.json
index c8ac246269..e6fcab16c1 100644
--- a/dev/inc/size-budgets.json
+++ b/dev/inc/size-budgets.json
@@ -1,69 +1,71 @@
{
- "animate": 27800,
+ "animate": 28450,
"mini-animate": 3250,
- "animate-sequence": 27800,
+ "animate-sequence": 28450,
"scroll": 3850,
- "scroll+animate": 30450,
+ "scroll+animate": 31050,
"inView": 500,
"resize": 700,
"hover+press": 2450,
- "drag": 27350,
- "pinch": 9400,
- "motionValue": 1900,
- "styleEffect": 4500,
+ "drag": 27100,
+ "pinch": 9450,
+ "motionValue": 1950,
+ "styleEffect": 4550,
"animateView": 6400,
"stagger": 850,
"frame": 750,
- "mix": 2100,
- "vanilla-all": 69500,
- "motion-div": 34350,
- "motion-div (all chunks)": 51850,
- "motion-create": 34350,
- "motion-create (all chunks)": 51900,
- "m-div": 5600,
- "m-div(via motion/react)": 5750,
- "m+LazyMotion+domAnimation": 32550,
- "m+LazyMotion+domMax": 48800,
- "m+LazyMotion+domDrag": 37300,
- "m+LazyMotion+domLayout": 44900,
- "LazyMotion-only": 650,
- "domAnimation-only": 29950,
- "domMax-only": 46000,
- "AnimatePresence": 3150,
+ "mix": 2150,
+ "vanilla-all": 70850,
+ "motion-div": 33900,
+ "motion-div (all chunks)": 52000,
+ "motion-create": 33900,
+ "motion-create (all chunks)": 52000,
+ "motion-div(sync)": 48950,
+ "m-div": 5650,
+ "m-div(via motion/react)": 5800,
+ "m+LazyMotion+domAnimation": 32700,
+ "m+LazyMotion+domMax": 49150,
+ "m+LazyMotion+domDrag": 37400,
+ "m+LazyMotion+domLayout": 45100,
+ "LazyMotion-only": 700,
+ "domAnimation-only": 29700,
+ "domMax-only": 46100,
+ "AnimatePresence": 3950,
"MotionConfig": 400,
"LayoutGroup": 1200,
- "Reorder": 43500,
- "Reorder (all chunks)": 56050,
- "Reorder(m)+LazyMotion": 14200,
+ "Reorder": 38450,
+ "Reorder (all chunks)": 56550,
+ "Reorder(m)+LazyMotion": 14400,
"useMotionValue": 2100,
"useTransform": 4800,
- "useMotionTemplate": 2250,
+ "useMotionTemplate": 2300,
"useSpring": 5050,
- "useScroll": 6050,
+ "useScroll": 6100,
"useInView": 650,
- "useAnimate": 28100,
+ "useAnimate": 28750,
"useAnimate(mini)": 3350,
"useMotionValueEvent": 150,
"useReducedMotion": 300,
"useAnimationFrame": 900,
- "useVelocity": 2150,
- "useAnimationControls": 19900,
- "react-all": 86150,
- "motion-div+AnimatePresence": 36250,
- "motion-div+AnimatePresence (all chunks)": 53800,
- "motion-div+useAnimate": 40050,
- "motion-div+useAnimate (all chunks)": 57500,
- "motion-div+animate": 39950,
- "motion-div+animate (all chunks)": 57400,
- "motion-div+useInView": 34500,
- "motion-div+useInView (all chunks)": 52050,
- "motion-div+useScroll": 37700,
- "motion-div+useScroll (all chunks)": 55200,
- "motion-div+useTransform+useMotionTemplate": 34900,
- "motion-div+useTransform+useMotionTemplate (all chunks)": 52400,
- "motion-div+useScroll+useTransform+useSpring": 39100,
- "motion-div+useScroll+useTransform+useSpring (all chunks)": 56600,
- "motion-div+Reorder": 43550,
- "motion-div+Reorder (all chunks)": 56100,
- "domMax+useScroll": 49350
+ "useVelocity": 2200,
+ "useAnimationControls": 19600,
+ "react-all": 88100,
+ "react-all (all chunks)": 88250,
+ "motion-div+AnimatePresence": 36100,
+ "motion-div+AnimatePresence (all chunks)": 54200,
+ "motion-div+useAnimate": 40600,
+ "motion-div+useAnimate (all chunks)": 58700,
+ "motion-div+animate": 40500,
+ "motion-div+animate (all chunks)": 58550,
+ "motion-div+useInView": 34050,
+ "motion-div+useInView (all chunks)": 52150,
+ "motion-div+useScroll": 37300,
+ "motion-div+useScroll (all chunks)": 55350,
+ "motion-div+useTransform+useMotionTemplate": 34450,
+ "motion-div+useTransform+useMotionTemplate (all chunks)": 52550,
+ "motion-div+useScroll+useTransform+useSpring": 38700,
+ "motion-div+useScroll+useTransform+useSpring (all chunks)": 56800,
+ "motion-div+Reorder": 38500,
+ "motion-div+Reorder (all chunks)": 56600,
+ "domMax+useScroll": 49550
}
diff --git a/dev/inc/size-scenarios.mjs b/dev/inc/size-scenarios.mjs
index 0fc558b651..a6a221c0ad 100644
--- a/dev/inc/size-scenarios.mjs
+++ b/dev/inc/size-scenarios.mjs
@@ -66,6 +66,8 @@ export const scenarios = {
// React components
"motion-div": `import { motion } from "motion/react"; export const D = motion.div`,
"motion-create": `import { motion } from "motion/react"; export const D = motion.create("div")`,
+ // For builds that write one file: compare the esbuild column with motion-div's
+ "motion-div(sync)": `import { motion } from "motion/react-sync"; export const D = motion.div`,
"m-div": `export { div } from "motion/react-m"`,
"m-div(via motion/react)": `import { m } from "motion/react"; export const D = m.div`,
"m+LazyMotion+domAnimation": `export { m, LazyMotion, domAnimation } from "motion/react"`,
@@ -95,7 +97,9 @@ export const scenarios = {
useAnimationFrame: `export { useAnimationFrame } from "motion/react"`,
useVelocity: `export { useVelocity } from "motion/react"`,
useAnimationControls: `export { useAnimationControls } from "motion/react"`,
- "react-all": `export * from "motion/react"`,
+ // Not `export *`: with a fetched chunk that imports from the first load,
+ // Rollup would emit the entry as a second file that repeats every export.
+ "react-all": `import * as all from "motion/react"; export { all }`,
// Combinations (marginal cost of mixing APIs in one app)
"motion-div+AnimatePresence": combo("AnimatePresence"),
@@ -224,6 +228,7 @@ async function warmCache() {
"motion/mini",
"motion/react",
"motion/react-m",
+ "motion/react-sync",
"motion/react-mini",
]
.map((entry) => `import "${entry}"`)
diff --git a/packages/framer-motion/package.json b/packages/framer-motion/package.json
index 5b57cfb8f2..fba914635d 100644
--- a/packages/framer-motion/package.json
+++ b/packages/framer-motion/package.json
@@ -168,7 +168,7 @@
},
{
"path": "./dist/size-rollup-animate.js",
- "maxSize": "26.95 kB"
+ "maxSize": "27.55 kB"
},
{
"path": "./dist/size-rollup-scroll.js",
@@ -180,7 +180,7 @@
},
{
"path": "./dist/size-rollup-remix.js",
- "maxSize": "52.8 kB"
+ "maxSize": "53.65 kB"
}
],
"gitHead": "78f3ff51b5508f7e8c1c283d8e80bcd26fec37d7"
diff --git a/packages/framer-motion/src/animation/animate/__tests__/delay-sleep.test.ts b/packages/framer-motion/src/animation/animate/__tests__/delay-sleep.test.ts
index e5d14c019f..a178ef1062 100644
--- a/packages/framer-motion/src/animation/animate/__tests__/delay-sleep.test.ts
+++ b/packages/framer-motion/src/animation/animate/__tests__/delay-sleep.test.ts
@@ -11,16 +11,25 @@ const frames = async (count: number) => {
/**
* A value waiting out its delay holds its first keyframe. Once it's set
* there, the frames of the delay don't set it again.
+ *
+ * The delays that tests read a value in are far longer than their frames
+ * take, as a busy machine can spend half a second on five frames.
*/
describe("values in their delay", () => {
test("aren't set again on every frame of the delay", async () => {
const x = motionValue(0)
const set = jest.spyOn(x, "set")
- animate(x, [0, 100], { delay: 0.5, duration: 0.1, ease: "linear" })
+ const animation = animate(x, [0, 100], {
+ delay: 10,
+ duration: 0.1,
+ ease: "linear",
+ })
await frames(5)
expect(set.mock.calls.length).toBeLessThanOrEqual(1)
expect(x.get()).toBe(0)
+
+ animation.stop()
})
test("still start moving when the delay ends", async () => {
@@ -40,11 +49,13 @@ describe("values in their delay", () => {
test("go back to their first keyframe after an outside write", async () => {
const x = motionValue(0)
- animate(x, [0, 100], { delay: 0.5, duration: 0.1 })
+ const animation = animate(x, [0, 100], { delay: 10, duration: 0.1 })
await frames(2)
x.set(50)
await frames(2)
expect(x.get()).toBe(0)
+
+ animation.stop()
})
})
diff --git a/packages/framer-motion/src/animation/timeline/index.ts b/packages/framer-motion/src/animation/timeline/index.ts
index a65b5f23ae..7de7884a6f 100644
--- a/packages/framer-motion/src/animation/timeline/index.ts
+++ b/packages/framer-motion/src/animation/timeline/index.ts
@@ -7,6 +7,7 @@ import {
GroupAnimationWithThen,
MotionValue,
motionValue,
+ supportPlayback,
supportTimelines,
TimelineWithFallback,
} from "motion-dom"
@@ -211,6 +212,7 @@ export class Timeline implements AnimationPlaybackControlsWithThen {
private options: TimelineOptions = {},
animations?: AnimationPlaybackControlsWithThen[]
) {
+ supportPlayback()
this.isPaused = options.autoplay === false
this.newFinished()
items.forEach((item) => this.add(item))
diff --git a/packages/framer-motion/src/components/AnimatePresence/PresenceChild.tsx b/packages/framer-motion/src/components/AnimatePresence/PresenceChild.tsx
index 0bb4f83121..67adc8a913 100644
--- a/packages/framer-motion/src/components/AnimatePresence/PresenceChild.tsx
+++ b/packages/framer-motion/src/components/AnimatePresence/PresenceChild.tsx
@@ -10,6 +10,7 @@ import type { VisualElement } from "motion-dom"
import { VariantLabels } from "../../motion/types"
import { useConstant } from "../../utils/use-constant"
import { useIsomorphicLayoutEffect } from "../../utils/use-isomorphic-effect"
+import { loadExitFeature } from "../../motion/features/animation/load-exit"
import { PopChild } from "./PopChild"
interface PresenceChildProps {
@@ -37,6 +38,13 @@ export const PresenceChild = ({
anchorY,
root
}: PresenceChildProps) => {
+ /**
+ * Motion components only bundle the feature that runs `exit` animations
+ * when they bundle all their features. The rest get it here, before
+ * any of them renders inside this component.
+ */
+ loadExitFeature()
+
const presenceChildren = useConstant(newChildrenMap)
const id = useId()
diff --git a/packages/framer-motion/src/components/AnimatePresence/__tests__/exit-without-animations.test.tsx b/packages/framer-motion/src/components/AnimatePresence/__tests__/exit-without-animations.test.tsx
new file mode 100644
index 0000000000..7044f0adb3
--- /dev/null
+++ b/packages/framer-motion/src/components/AnimatePresence/__tests__/exit-without-animations.test.tsx
@@ -0,0 +1,39 @@
+import { act } from "react"
+import { AnimatePresence, LazyMotion, m } from "../../.."
+import { render } from "../../../jest.setup"
+import { gestureAnimations } from "../../../motion/features/gestures"
+import { createDomVisualElement } from "../../../render/dom/create-visual-element"
+
+const settle = async () => {
+ for (let i = 0; i < 5; i++) {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ }
+}
+
+/**
+ * AnimatePresence brings the feature that runs `exit` animations, so a
+ * component can have it without the feature that animates.
+ */
+describe("exit of a component with no animation feature", () => {
+ test("is removed at once", async () => {
+ const features = { renderer: createDomVisualElement, ...gestureAnimations }
+
+ const Component = ({ isVisible }: { isVisible: boolean }) => (
+
+
+ {isVisible && }
+
+
+ )
+
+ const { container, rerender } = render()
+ await settle()
+
+ rerender()
+ await settle()
+
+ expect(container.querySelector("#exits")).toBeNull()
+ })
+})
diff --git a/packages/framer-motion/src/components/AnimatePresence/context.ts b/packages/framer-motion/src/components/AnimatePresence/context.ts
new file mode 100644
index 0000000000..e8c4d8d10e
--- /dev/null
+++ b/packages/framer-motion/src/components/AnimatePresence/context.ts
@@ -0,0 +1,16 @@
+import { PresenceContext as Context } from "../../context/PresenceContext"
+import { loadExitFeature } from "../../motion/features/animation/load-exit"
+
+/**
+ * PresenceContext as apps import it. A component that provides it stands
+ * in for AnimatePresence, so the feature that runs `exit` animations loads
+ * with it, as it does with AnimatePresence.
+ *
+ * Motion's own code reads the context from context/PresenceContext, which
+ * loads nothing.
+ *
+ * @public
+ */
+export const PresenceContext = /* @__PURE__ */ (() => (
+ loadExitFeature(), Context
+))()
diff --git a/packages/framer-motion/src/index.ts b/packages/framer-motion/src/index.ts
index 6e1230a9b4..fa5b47425a 100644
--- a/packages/framer-motion/src/index.ts
+++ b/packages/framer-motion/src/index.ts
@@ -121,7 +121,7 @@ export { startOptimizedAppearAnimation } from "./animation/optimized-appear/star
export { LayoutGroupContext } from "./context/LayoutGroupContext"
export { MotionConfigContext } from "./context/MotionConfigContext"
export { MotionContext } from "./context/MotionContext"
-export { PresenceContext } from "./context/PresenceContext"
+export { PresenceContext } from "./components/AnimatePresence/context"
export { SwitchLayoutGroupContext } from "./context/SwitchLayoutGroupContext"
/**
diff --git a/packages/framer-motion/src/motion/__tests__/async-exit-presence-context.test.tsx b/packages/framer-motion/src/motion/__tests__/async-exit-presence-context.test.tsx
new file mode 100644
index 0000000000..06eecc9e88
--- /dev/null
+++ b/packages/framer-motion/src/motion/__tests__/async-exit-presence-context.test.tsx
@@ -0,0 +1,58 @@
+import { act, useId, useMemo } from "react"
+import { PresenceContext } from "../../components/AnimatePresence/context"
+import { render } from "../../jest.setup"
+import { motion } from "../../render/components/motion-async/proxy"
+
+const settle = async (ms = 0) => {
+ for (let i = 0; i < 5; i++) {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, ms))
+ })
+ }
+}
+
+/**
+ * This file doesn't import AnimatePresence, as an app with its own
+ * presence component might not.
+ */
+describe("a component that provides PresenceContext itself", () => {
+ test("gets exit animations from motion components that fetch features", async () => {
+ const onExitComplete = jest.fn()
+ const register = jest.fn(() => () => {})
+
+ const Presence = ({ isPresent }: { isPresent: boolean }) => {
+ const id = useId()
+ const context = useMemo(
+ () => ({
+ id,
+ isPresent,
+ onExitComplete,
+ register,
+ }),
+ [isPresent]
+ )
+
+ return (
+
+
+
+ )
+ }
+
+ const { container, rerender } = render()
+ await settle()
+
+ expect(register).toHaveBeenCalled()
+
+ rerender()
+ await settle(40)
+
+ const element = container.querySelector("#exits") as HTMLElement
+ expect(element.style.opacity).toBe("0")
+ expect(onExitComplete).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/packages/framer-motion/src/motion/__tests__/async-features-identity.test.tsx b/packages/framer-motion/src/motion/__tests__/async-features-identity.test.tsx
new file mode 100644
index 0000000000..74bb0ab815
--- /dev/null
+++ b/packages/framer-motion/src/motion/__tests__/async-features-identity.test.tsx
@@ -0,0 +1,79 @@
+import { visualElementStore } from "motion-dom"
+import { act, useState } from "react"
+import { LazyMotion } from "../../components/LazyMotion"
+import { render } from "../../jest.setup"
+import { m } from "../../render/components/m/proxy"
+import { motion as fetching } from "../../render/components/motion-async/proxy"
+import { motion as bundled } from "../../render/components/motion/proxy"
+import { domMax } from "../../render/dom/features-max"
+
+const settle = async () => {
+ for (let i = 0; i < 5; i++) {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ }
+}
+
+const projectionOf = (container: Element, id: string) =>
+ visualElementStore.get(container.querySelector("#" + id)!)!.projection!
+
+/**
+ * Features are shared by every component on the page. Components that
+ * fetch layout code load a MeasureLayout of their own for all of them,
+ * the first time each tag is used. A mounted component given another
+ * MeasureLayout would mount it in place of the first, and a mount takes
+ * no snapshot of the layout before it changes.
+ */
+describe("a mounted layout component, when a component that fetches features is first used", () => {
+ test("an m component with domMax keeps its MeasureLayout", async () => {
+ let setDependency!: (dependency: number) => void
+ const Box = () => {
+ const [dependency, set] = useState(0)
+ setDependency = set
+ return
+ }
+ const { container } = render(
+
+
+
+ )
+ await settle()
+
+ const projection = projectionOf(container, "m")
+ const willUpdate = jest.spyOn(projection, "willUpdate")
+ const unmounted = jest.spyOn(projection, "scheduleCheckAfterUnmount")
+
+ /**
+ * As a module that loads later does, like that of a route.
+ */
+ void fetching.article
+
+ /**
+ * Only the m component renders, not its LazyMotion.
+ */
+ act(() => setDependency(1))
+
+ expect(unmounted).not.toHaveBeenCalled()
+ expect(willUpdate).toHaveBeenCalledTimes(1)
+ })
+
+ test("a component that bundles its features keeps its MeasureLayout", async () => {
+ const Bundled = bundled.section
+ const { container, rerender } = render(
+
+ )
+ await settle()
+
+ const projection = projectionOf(container, "bundled")
+ const willUpdate = jest.spyOn(projection, "willUpdate")
+ const unmounted = jest.spyOn(projection, "scheduleCheckAfterUnmount")
+
+ void fetching.aside
+
+ rerender()
+
+ expect(unmounted).not.toHaveBeenCalled()
+ expect(willUpdate).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/packages/framer-motion/src/motion/__tests__/async-features-m.test.tsx b/packages/framer-motion/src/motion/__tests__/async-features-m.test.tsx
new file mode 100644
index 0000000000..eaaa72123f
--- /dev/null
+++ b/packages/framer-motion/src/motion/__tests__/async-features-m.test.tsx
@@ -0,0 +1,63 @@
+import { visualElementStore } from "motion-dom"
+import { act } from "react"
+import { LazyMotion } from "../../components/LazyMotion"
+import { render } from "../../jest.setup"
+import { m } from "../../render/components/m/proxy"
+import { featureLoaders } from "../../render/components/motion-async/loaders"
+import { motion } from "../../render/components/motion-async/proxy"
+import { domAnimation } from "../../render/dom/features-animation"
+
+const settle = async () => {
+ for (let i = 0; i < 5; i++) {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ }
+}
+
+const projectionOf = (container: Element, id: string) =>
+ visualElementStore.get(container.querySelector("#" + id)!)!.projection
+
+/**
+ * Features are shared by every component on the page. So once a motion
+ * component has fetched the layout code, an m component with `layout`
+ * animates its layout too, as it does beside a component that bundles the
+ * code.
+ */
+describe("an m component beside a component that fetches the layout feature", () => {
+ test("is driven from React once the code arrives", async () => {
+ const { load } = featureLoaders.layout
+ let arrive!: VoidFunction
+ featureLoaders.layout.load = () =>
+ new Promise((resolve) => {
+ arrive = () => load().then(resolve)
+ })
+
+ const Component = ({ dependency = 0 }) => (
+
+
+
+
+ )
+ const { container, rerender } = render()
+ await settle()
+ expect(projectionOf(container, "m")).toBeUndefined()
+
+ arrive()
+ await settle()
+ rerender()
+
+ const projection = projectionOf(container, "m")
+ expect(projection.instance === container.querySelector("#m")).toBe(
+ true
+ )
+
+ const willUpdate = jest.spyOn(projection, "willUpdate")
+ const didUpdate = jest.spyOn(projection.root, "didUpdate")
+ rerender()
+
+ expect(willUpdate).toHaveBeenCalledTimes(1)
+ expect(didUpdate).toHaveBeenCalled()
+ expect(projection.options.onExitComplete).toBeTruthy()
+ })
+})
diff --git a/packages/framer-motion/src/motion/__tests__/async-features-shell-bundled.test.tsx b/packages/framer-motion/src/motion/__tests__/async-features-shell-bundled.test.tsx
new file mode 100644
index 0000000000..287c518677
--- /dev/null
+++ b/packages/framer-motion/src/motion/__tests__/async-features-shell-bundled.test.tsx
@@ -0,0 +1,53 @@
+import { visualElementStore } from "motion-dom"
+import { act } from "react"
+import { render } from "../../jest.setup"
+import { featureLoaders } from "../../render/components/motion-async/loaders"
+import { motion as asyncMotion } from "../../render/components/motion-async/proxy"
+import { motion } from "../../render/components/motion/proxy"
+
+const settle = async () => {
+ for (let i = 0; i < 5; i++) {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ }
+}
+
+const projectionOf = (element: Element) =>
+ visualElementStore.get(element)!.projection
+
+describe("MeasureLayout of a component whose fetch hasn't arrived", () => {
+ test("drives a node made with the feature of a component that bundles it", async () => {
+ featureLoaders.layout.load = () => new Promise(() => {})
+
+ const { container, rerender } = render(
+
+ )
+ await settle()
+ const element = container.querySelector("#waits")!
+
+ expect(projectionOf(element)).toBeUndefined()
+
+ /**
+ * A motion component that bundles its features loads them when
+ * it first renders.
+ */
+ const Bundled = motion.div
+ render()
+
+ rerender()
+
+ const projection = projectionOf(element)
+ expect(projection.instance === element).toBe(true)
+ expect(projection.options.layout).toBe(true)
+
+ const willUpdate = jest.spyOn(projection, "willUpdate")
+ const didUpdate = jest.spyOn(projection.root, "didUpdate")
+
+ rerender()
+
+ expect(willUpdate).toHaveBeenCalledTimes(1)
+ expect(didUpdate).toHaveBeenCalledTimes(1)
+ expect(projection.options.layout).toBe("position")
+ })
+})
diff --git a/packages/framer-motion/src/motion/__tests__/async-features-shell.test.tsx b/packages/framer-motion/src/motion/__tests__/async-features-shell.test.tsx
new file mode 100644
index 0000000000..f5e2361f1a
--- /dev/null
+++ b/packages/framer-motion/src/motion/__tests__/async-features-shell.test.tsx
@@ -0,0 +1,130 @@
+import { visualElementStore } from "motion-dom"
+import { act } from "react"
+import { AnimatePresence } from "../../components/AnimatePresence"
+import { render } from "../../jest.setup"
+import { featureLoaders } from "../../render/components/motion-async/loaders"
+import { motion as asyncMotion } from "../../render/components/motion-async/proxy"
+
+const settle = async () => {
+ for (let i = 0; i < 5; i++) {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ }
+}
+
+const projectionOf = (element: Element) =>
+ visualElementStore.get(element)!.projection
+
+/**
+ * A component that fetches the layout feature mounts a shell of
+ * MeasureLayout from its first render. The shell has no code of its own
+ * to drive a projection node: it runs the methods that arrive with the
+ * feature.
+ *
+ * Tests run in order and share the loaders, as an app's components do.
+ */
+describe("MeasureLayout of a component that fetches the layout feature", () => {
+ const { load } = featureLoaders.layout
+ let arrive: VoidFunction
+
+ beforeAll(() => {
+ /**
+ * Hold the component's own fetch until a test lets it arrive.
+ */
+ featureLoaders.layout.load = () =>
+ new Promise((resolve) => {
+ arrive = () => load().then(resolve)
+ })
+ })
+
+ afterAll(() => {
+ featureLoaders.layout.load = load
+ })
+
+ test("lets a component exit while the feature hasn't arrived", async () => {
+ const Component = ({ isVisible }: { isVisible: boolean }) => (
+
+ {isVisible && }
+
+ )
+ const { container, rerender } = render()
+ await settle()
+
+ expect(container.querySelector("#exits")).toBeTruthy()
+ expect(featureLoaders.layout.isLoaded).toBeFalsy()
+
+ rerender()
+ await settle()
+
+ expect(container.querySelector("#exits")).toBeNull()
+ })
+
+ test("lets a component with only drag exit", async () => {
+ const Component = ({ isVisible }: { isVisible: boolean }) => (
+
+ {isVisible && }
+
+ )
+ const { container, rerender } = render()
+ await settle()
+
+ /**
+ * Its node only measures, so there's no layout animation to wait
+ * for.
+ */
+ expect(projectionOf(container.querySelector("#drags")!)).toBeTruthy()
+
+ rerender()
+ await settle()
+
+ expect(container.querySelector("#drags")).toBeNull()
+ })
+
+ test("drives a node made after it mounted, without a render", async () => {
+ const { container, rerender } = render(
+
+ )
+ await settle()
+ const element = container.querySelector("#waits")!
+
+ expect(projectionOf(element)).toBeUndefined()
+
+ await act(async () => arrive())
+ await settle()
+
+ const projection = projectionOf(element)
+ expect(projection.instance === element).toBe(true)
+
+ /**
+ * The methods that arrived set the node up as a MeasureLayout
+ * that mounts with the feature does.
+ */
+ expect(projection.options.layout).toBe(true)
+ expect(typeof projection.options.onExitComplete).toBe("function")
+
+ const willUpdate = jest.spyOn(projection, "willUpdate")
+ const didUpdate = jest.spyOn(projection.root, "didUpdate")
+
+ rerender()
+
+ expect(willUpdate).toHaveBeenCalledTimes(1)
+ expect(didUpdate).toHaveBeenCalledTimes(1)
+ expect(projection.options.layout).toBe("position")
+ expect(projectionOf(element) === projection).toBe(true)
+ })
+
+ test("unmounts as the feature's MeasureLayout does", async () => {
+ const { container, unmount } = render(
+
+ )
+ await settle()
+
+ const projection = projectionOf(container.querySelector("#leaves")!)
+ const check = jest.spyOn(projection, "scheduleCheckAfterUnmount")
+
+ unmount()
+
+ expect(check).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/packages/framer-motion/src/motion/features/animation/exit.ts b/packages/framer-motion/src/motion/features/animation/exit.ts
index eec3af18f2..3873f51412 100644
--- a/packages/framer-motion/src/motion/features/animation/exit.ts
+++ b/packages/framer-motion/src/motion/features/animation/exit.ts
@@ -10,11 +10,24 @@ export class ExitAnimationFeature extends Feature {
*/
private exit?: Promise | true
+ /**
+ * Takes this component off its presence's list of children to wait for.
+ */
+ private stop?: VoidFunction
+
update() {
const { presenceContext, animationState } = this.node
if (!presenceContext || !animationState) return
+ /**
+ * Register here, once there's an animation state. This feature
+ * loads with AnimatePresence, so an `m` component can have it
+ * before the features that animate arrive. A presence waits for
+ * each child on its list, and this one couldn't run an exit.
+ */
+ this.stop ||= presenceContext.register?.(this.id, this.node)
+
const { isPresent, onExitComplete } = presenceContext
/**
@@ -75,15 +88,12 @@ export class ExitAnimationFeature extends Feature {
}
mount() {
- const { register } = this.node.presenceContext || {}
-
- if (register) {
- this.unmount = register(this.id, this.node)
- }
-
// Start the exit of an element that mounts already exiting
this.update()
}
- unmount() {}
+ unmount() {
+ this.stop?.()
+ this.stop = undefined
+ }
}
diff --git a/packages/framer-motion/src/motion/features/animation/load-exit.ts b/packages/framer-motion/src/motion/features/animation/load-exit.ts
new file mode 100644
index 0000000000..1abe9def08
--- /dev/null
+++ b/packages/framer-motion/src/motion/features/animation/load-exit.ts
@@ -0,0 +1,17 @@
+import { loadFeatures } from "../load-features"
+import { ExitAnimationFeature } from "./exit"
+
+let isLoaded = false
+
+/**
+ * Give every motion component the feature that runs `exit` animations.
+ *
+ * An exit only runs for a component that something keeps mounted after
+ * React would remove it. So the code that can do that calls this, and an
+ * app without that code doesn't bundle the feature.
+ */
+export const loadExitFeature = () => {
+ if (isLoaded) return
+ isLoaded = true
+ loadFeatures({ exit: { Feature: ExitAnimationFeature } })
+}
diff --git a/packages/framer-motion/src/motion/features/layout-fetched.ts b/packages/framer-motion/src/motion/features/layout-fetched.ts
new file mode 100644
index 0000000000..41da9864f4
--- /dev/null
+++ b/packages/framer-motion/src/motion/features/layout-fetched.ts
@@ -0,0 +1,15 @@
+import { HTMLProjectionNode } from "motion-dom"
+import { MeasureLayoutWithContext } from "./layout/MeasureLayout"
+import { FeaturePackages } from "./types"
+
+/**
+ * The layout feature as a component fetches it. The component has had its
+ * MeasureLayoutShell from the first render, so this brings the projection
+ * node and the methods the shell runs.
+ */
+export const layout: FeaturePackages = {
+ layout: {
+ ProjectionNode: HTMLProjectionNode,
+ Lifecycle: MeasureLayoutWithContext,
+ },
+}
diff --git a/packages/framer-motion/src/motion/features/layout.ts b/packages/framer-motion/src/motion/features/layout.ts
index 00e7da75e1..d831398b25 100644
--- a/packages/framer-motion/src/motion/features/layout.ts
+++ b/packages/framer-motion/src/motion/features/layout.ts
@@ -1,10 +1,14 @@
import { HTMLProjectionNode } from "motion-dom"
-import { MeasureLayout } from "./layout/MeasureLayout"
+import {
+ MeasureLayout,
+ MeasureLayoutWithContext,
+} from "./layout/MeasureLayout"
import { FeaturePackages } from "./types"
export const layout: FeaturePackages = {
layout: {
ProjectionNode: HTMLProjectionNode,
MeasureLayout,
+ Lifecycle: MeasureLayoutWithContext,
},
}
diff --git a/packages/framer-motion/src/motion/features/layout/MeasureLayout.tsx b/packages/framer-motion/src/motion/features/layout/MeasureLayout.tsx
index 6bb77c28c5..927c1b866f 100644
--- a/packages/framer-motion/src/motion/features/layout/MeasureLayout.tsx
+++ b/packages/framer-motion/src/motion/features/layout/MeasureLayout.tsx
@@ -23,7 +23,7 @@ interface MeasureContextProps {
safeToRemove?: VoidFunction | null
}
-type MeasureProps = MotionProps &
+export type MeasureProps = MotionProps &
MeasureContextProps & { visualElement: VisualElement }
/**
@@ -114,12 +114,16 @@ const nodeOf = ({ projection }: VisualElement) =>
projection?.isMeasureOnly ? undefined : projection
/**
- * Each mounted component's MeasureLayout, to attach it to a projection
- * node made after it mounted.
+ * Drives a component's projection node from React's commit. A class, for
+ * getSnapshotBeforeUpdate: the only point React gives to measure a layout
+ * before it changes.
+ *
+ * A component that fetches the layout feature mounts MeasureLayoutShell
+ * instead, before this code arrives. Its instances run these methods as
+ * their own once it has, so the methods use only what both classes have:
+ * `props`, `node`, `takeOver`, `attach()` and `safeToRemove()`.
*/
-export const measurers = new WeakMap()
-
-class MeasureLayoutWithContext extends Component {
+export class MeasureLayoutWithContext extends Component {
takeOver?: VoidFunction
node?: VisualElement["projection"]
@@ -129,9 +133,7 @@ class MeasureLayoutWithContext extends Component {
* in order to incorporate transforms
*/
componentDidMount() {
- measurers.set(this.props.visualElement, this)
this.attach()
- globalProjectionState.hasEverUpdated = true
}
/**
@@ -143,6 +145,8 @@ class MeasureLayoutWithContext extends Component {
this.props
const projection = nodeOf(visualElement)
+ globalProjectionState.hasEverUpdated = true
+
if (projection && projection !== this.node) {
this.node = projection
layoutGroup.group?.add(projection)
@@ -174,13 +178,7 @@ class MeasureLayoutWithContext extends Component {
this.attach()
const projection = this.node
- /**
- * Without a node there's no layout animation to hold an exit for.
- */
- if (!projection) {
- isPresent || this.safeToRemove()
- return null
- }
+ if (!projection) return null
/**
* TODO: We use this data in relegate to determine whether to
@@ -248,7 +246,6 @@ class MeasureLayoutWithContext extends Component {
const projection = this.node
hasTakenAnySnapshot = true
- measurers.delete(this.props.visualElement)
if (projection) {
projection.scheduleCheckAfterUnmount()
diff --git a/packages/framer-motion/src/motion/features/layout/MeasureLayoutShell.tsx b/packages/framer-motion/src/motion/features/layout/MeasureLayoutShell.tsx
new file mode 100644
index 0000000000..d5f3d21778
--- /dev/null
+++ b/packages/framer-motion/src/motion/features/layout/MeasureLayoutShell.tsx
@@ -0,0 +1,101 @@
+"use client"
+
+import { getFeatureDefinitions, type VisualElement } from "motion-dom"
+import { Component, useContext } from "react"
+import { usePresence } from "../../../components/AnimatePresence/use-presence"
+import { LayoutGroupContext } from "../../../context/LayoutGroupContext"
+import { SwitchLayoutGroupContext } from "../../../context/SwitchLayoutGroupContext"
+import { MotionProps } from "../../types"
+import type { MeasureProps } from "./MeasureLayout"
+
+/**
+ * Each mounted component's shell, to attach it to a projection node made
+ * after it mounted.
+ */
+export const measurers = new WeakMap()
+
+/**
+ * The methods of the layout feature's MeasureLayout. Looked up on each
+ * call, as the shell mounts before the feature arrives. The feature holds
+ * the class and not its prototype: reading a property as a module loads
+ * would stop bundlers from dropping the feature when it's unused.
+ */
+const getLifecycle = () => getFeatureDefinitions().layout?.Lifecycle?.prototype
+
+/**
+ * The React side of layout animations for a component that fetches the
+ * layout feature. React only gives a class component the chance to
+ * measure before a layout changes, and a component can't gain one without
+ * rendering again, so the class is here from the first render. What it
+ * does with a projection node arrives with the code that makes the node:
+ * each method here runs MeasureLayout's method of the same name.
+ */
+class MeasureLayoutShell extends Component {
+ takeOver?: VoidFunction
+ node?: VisualElement["projection"]
+
+ componentDidMount() {
+ measurers.set(this.props.visualElement, this)
+ this.attach()
+ this.release()
+ }
+
+ attach() {
+ getLifecycle()?.attach.call(this)
+ }
+
+ getSnapshotBeforeUpdate(prevProps: MeasureProps) {
+ return getLifecycle()?.getSnapshotBeforeUpdate.call(this, prevProps) || null
+ }
+
+ componentDidUpdate() {
+ getLifecycle()?.componentDidUpdate.call(this)
+ this.release()
+ }
+
+ /**
+ * Without a node there's no layout animation to hold an exit for. That's
+ * so before the feature arrives, and for a component with only `drag`.
+ * AnimatePresence notes which children are exiting after this commit,
+ * so tell it once the commit is over.
+ */
+ release() {
+ this.node ||
+ this.props.isPresent ||
+ queueMicrotask(() => this.safeToRemove())
+ }
+
+ /**
+ * Forgotten, so a node made later isn't set up from the props of a
+ * component that no longer has a layout to measure.
+ */
+ componentWillUnmount() {
+ measurers.delete(this.props.visualElement)
+ getLifecycle()?.componentWillUnmount.call(this)
+ }
+
+ safeToRemove() {
+ this.props.safeToRemove?.()
+ }
+
+ render() {
+ return null
+ }
+}
+
+export function MeasureLayout(
+ props: MotionProps & { visualElement: VisualElement }
+) {
+ const [isPresent, safeToRemove] = usePresence()
+ const layoutGroup = useContext(LayoutGroupContext)
+
+ return (
+
+ )
+}
diff --git a/packages/framer-motion/src/motion/features/types.ts b/packages/framer-motion/src/motion/features/types.ts
index 572c279c3e..b1e7cf7ae3 100644
--- a/packages/framer-motion/src/motion/features/types.ts
+++ b/packages/framer-motion/src/motion/features/types.ts
@@ -1,7 +1,10 @@
import type { Feature } from "motion-dom"
import { CreateVisualElement } from "../../render/types"
import { MotionProps } from "../types"
-import { MeasureLayout } from "./layout/MeasureLayout"
+import type {
+ MeasureLayout,
+ MeasureLayoutWithContext,
+} from "./layout/MeasureLayout"
interface FeatureClass {
new (props: Props): Feature
@@ -12,6 +15,13 @@ export interface HydratedFeatureDefinition {
Feature: FeatureClass
ProjectionNode?: any
MeasureLayout?: typeof MeasureLayout
+
+ /**
+ * The class whose methods drive a projection node from React's commit.
+ * The MeasureLayoutShell of a component that mounted before the layout
+ * feature arrived runs them as its own.
+ */
+ Lifecycle?: typeof MeasureLayoutWithContext
}
export interface HydratedFeatureDefinitions {
@@ -32,6 +42,7 @@ export interface FeatureDefinition {
Feature?: HydratedFeatureDefinition["Feature"]
ProjectionNode?: HydratedFeatureDefinition["ProjectionNode"]
MeasureLayout?: HydratedFeatureDefinition["MeasureLayout"]
+ Lifecycle?: HydratedFeatureDefinition["Lifecycle"]
}
export type FeatureDefinitions = {
@@ -47,6 +58,7 @@ export interface FeaturePackage {
Feature?: HydratedFeatureDefinition["Feature"]
ProjectionNode?: HydratedFeatureDefinition["ProjectionNode"]
MeasureLayout?: HydratedFeatureDefinition["MeasureLayout"]
+ Lifecycle?: HydratedFeatureDefinition["Lifecycle"]
}
export type FeaturePackages = {
diff --git a/packages/framer-motion/src/motion/features/use-async-features.ts b/packages/framer-motion/src/motion/features/use-async-features.ts
index b834346290..b9fdfce7b5 100644
--- a/packages/framer-motion/src/motion/features/use-async-features.ts
+++ b/packages/framer-motion/src/motion/features/use-async-features.ts
@@ -9,7 +9,7 @@ import { useConstant } from "../../utils/use-constant"
import { useIsomorphicLayoutEffect } from "../../utils/use-isomorphic-effect"
import { MotionProps } from "../types"
import { getInitializedFeatureDefinitions } from "./definitions"
-import { measurers } from "./layout/MeasureLayout"
+import { MeasureLayout, measurers } from "./layout/MeasureLayoutShell"
import { loadFeatures } from "./load-features"
import { FeatureLoader, FeatureLoaders } from "./types"
@@ -183,6 +183,10 @@ const fetchFeature = (loaders: FeatureLoaders, name: string) => {
*
* The fetch starts during render, not in an effect, so a server-rendered
* page asks for its features while it hydrates rather than afterwards.
+ *
+ * Returns the component that measures the layout of these components. It
+ * differs from the layout feature's own, as it mounts before the feature
+ * arrives.
*/
export function useAsyncFeatures(
props: MotionProps,
@@ -261,6 +265,8 @@ export function useAsyncFeatures(
* makes its visual element, so the node is mounted too.
*/
project(entry)
+
+ return MeasureLayout
}
/**
diff --git a/packages/framer-motion/src/motion/index.tsx b/packages/framer-motion/src/motion/index.tsx
index 96b0866544..293778d788 100644
--- a/packages/framer-motion/src/motion/index.tsx
+++ b/packages/framer-motion/src/motion/index.tsx
@@ -1,9 +1,20 @@
"use client"
-import { isMotionValue, rootProjectionNode } from "motion-dom"
+import {
+ isMotionValue,
+ rootProjectionNode,
+ type VisualElement,
+} from "motion-dom"
import { invariant, warnOnce } from "motion-utils"
import * as React from "react"
-import { forwardRef, memo, useContext, useEffect, useReducer } from "react"
+import {
+ forwardRef,
+ memo,
+ useContext,
+ useEffect,
+ useReducer,
+ useRef,
+} from "react"
import { LayoutGroupContext } from "../context/LayoutGroupContext"
import { LazyContext } from "../context/LazyContext"
import { MotionConfigContext } from "../context/MotionConfigContext"
@@ -62,6 +73,15 @@ export interface MotionComponentOptions {
type?: "html" | "svg"
}
+/**
+ * A hook of components that fetch features. It returns the component that
+ * measures their layout, which mounts before the layout feature arrives.
+ */
+export type UseFeatures = (
+ props: MotionProps,
+ context: MotionContextProps
+) => React.ComponentType
+
/**
* Create a `motion` component.
*
@@ -79,7 +99,7 @@ export function createMotionComponent<
{ forwardMotionProps = false, type }: MotionComponentOptions = {},
preloadedFeatures?: FeaturePackages,
createVisualElement?: CreateVisualElement,
- useFeatures?: (props: MotionProps, context: MotionContextProps) => void
+ useFeatures?: UseFeatures
) {
preloadedFeatures && loadFeatures(preloadedFeatures)
@@ -151,11 +171,21 @@ export function createMotionComponent<
useStrictMode(configAndProps, preloadedFeatures)
/**
- * Fetches the features these props need. It's fixed for the
- * life of the component, so this hook is always or never
- * called.
+ * Fetches the features these props need, and returns the
+ * component that measures layout until they arrive. It's
+ * fixed for the life of the component, so this hook is always
+ * or never called.
+ */
+ const FetchedMeasureLayout = useFeatures?.(configAndProps, context)
+
+ /**
+ * A component keeps the MeasureLayout it first renders.
+ * Features are shared by every component on the page, and
+ * components that fetch theirs load a MeasureLayout of their
+ * own. One given in place of another would mount, and a mount
+ * takes no snapshot of the layout before it changes.
*/
- useFeatures?.(configAndProps, context)
+ const measure = useRef(undefined)
const layoutProjection = getProjectionFunctionality(configAndProps)
@@ -182,7 +212,8 @@ export function createMotionComponent<
layoutProjection.isEnabled ||
context.visualElement?.projection?.options.layoutId
)
- MeasureLayout = layoutProjection.MeasureLayout
+ MeasureLayout = measure.current ||=
+ FetchedMeasureLayout || layoutProjection.MeasureLayout
}
/**
diff --git a/packages/framer-motion/src/render/components/create-proxy.ts b/packages/framer-motion/src/render/components/create-proxy.ts
index 536e2bac11..2355c4be96 100644
--- a/packages/framer-motion/src/render/components/create-proxy.ts
+++ b/packages/framer-motion/src/render/components/create-proxy.ts
@@ -1,7 +1,10 @@
import { warnOnce } from "motion-utils"
-import { createMotionComponent, MotionComponentOptions } from "../../motion"
+import {
+ createMotionComponent,
+ MotionComponentOptions,
+ UseFeatures,
+} from "../../motion"
import { FeaturePackages } from "../../motion/features/types"
-import { MotionContextProps } from "../../context/MotionContext"
import { MotionProps } from "../../motion/types"
import { DOMMotionComponents } from "../dom/types"
import { CreateVisualElement } from "../types"
@@ -23,7 +26,7 @@ export type MotionProxy = typeof createMotionComponent &
export function createMotionProxy(
preloadedFeatures?: FeaturePackages,
createVisualElement?: CreateVisualElement,
- useFeatures?: (props: MotionProps, context: MotionContextProps) => void
+ useFeatures?: UseFeatures
): MotionProxy {
if (typeof Proxy === "undefined") {
return createMotionComponent as MotionProxy
diff --git a/packages/framer-motion/src/render/components/motion-async/loaders.ts b/packages/framer-motion/src/render/components/motion-async/loaders.ts
index 7a5d64e097..3400abae8b 100644
--- a/packages/framer-motion/src/render/components/motion-async/loaders.ts
+++ b/packages/framer-motion/src/render/components/motion-async/loaders.ts
@@ -12,7 +12,9 @@ export const featureLoaders: FeatureLoaders = {
layout: {
keys: ["layout"],
load: () =>
- import("../../../motion/features/layout").then((m) => m.layout),
+ import("../../../motion/features/layout-fetched").then(
+ (m) => m.layout
+ ),
},
drag: {
keys: ["drag", "pan"],
diff --git a/packages/framer-motion/src/render/components/motion-async/proxy.ts b/packages/framer-motion/src/render/components/motion-async/proxy.ts
index 7343580d71..b34fe5b28e 100644
--- a/packages/framer-motion/src/render/components/motion-async/proxy.ts
+++ b/packages/framer-motion/src/render/components/motion-async/proxy.ts
@@ -1,6 +1,6 @@
-import { animations } from "../../../motion/features/animations"
+import { AnimationFeature } from "../../../motion/features/animation"
import { gestureAnimations } from "../../../motion/features/gestures"
-import { MeasureLayout } from "../../../motion/features/layout/MeasureLayout"
+import { MeasureLayout } from "../../../motion/features/layout/MeasureLayoutShell"
import {
preloadFeatures as preload,
useAsyncFeatures,
@@ -15,14 +15,23 @@ import { featureLoaders } from "./loaders"
* A motion component with animations and gestures, that fetches layout
* and drag code the first time a component's props need it.
*
- * The React side of layout animations is here from the start. It does
- * nothing until the projection code arrives, and then needs no render to
- * take part in the next layout change.
+ * The feature that runs `exit` animations isn't here. It loads with
+ * AnimatePresence, the only place an exit runs.
+ *
+ * The React side of layout animations is here from the start, as the
+ * component useAsyncFeatures returns. It does nothing until the projection
+ * code arrives, and then needs no render to take part in the next layout
+ * change.
+ *
+ * Features are shared by every component on the page, so `m` components
+ * are given it too. The code these components fetch has a projection node
+ * for them, and nothing else that would drive it.
*/
export const motion = /*@__PURE__*/ createMotionProxy(
- /*@__PURE__*/ Object.assign({}, animations, gestureAnimations, {
- layout: { MeasureLayout },
- }),
+ /*@__PURE__*/ Object.assign(
+ { animation: { Feature: AnimationFeature }, layout: { MeasureLayout } },
+ gestureAnimations
+ ),
createDomVisualElement,
(props: MotionProps, context: MotionContextProps) =>
useAsyncFeatures(props, context, featureLoaders)
diff --git a/packages/motion-dom/src/animation/JSAnimation.ts b/packages/motion-dom/src/animation/JSAnimation.ts
index 6fc69188df..3a5f217263 100644
--- a/packages/motion-dom/src/animation/JSAnimation.ts
+++ b/packages/motion-dom/src/animation/JSAnimation.ts
@@ -4,6 +4,7 @@ import { calcGeneratorVelocity } from "./generators/utils/velocity"
import { MultiValueAnimation, ValueTrack } from "./MultiValueAnimation"
import { generateTrack } from "./track"
import { supportTimelines } from "./animate/attach-timeline"
+import { supportPlayback } from "./playback"
import {
AnimationState,
TimelineWithFallback,
@@ -39,6 +40,7 @@ export class JSAnimation<
private sampled?: number
constructor(options: ValueAnimationOptions) {
+ supportPlayback()
super(options.driver)
const { autoplay, startTime, onUpdate } = options
diff --git a/packages/motion-dom/src/animation/MultiValueAnimation.ts b/packages/motion-dom/src/animation/MultiValueAnimation.ts
index bf3ec73ee7..00b57bd044 100644
--- a/packages/motion-dom/src/animation/MultiValueAnimation.ts
+++ b/packages/motion-dom/src/animation/MultiValueAnimation.ts
@@ -1,8 +1,7 @@
-import { millisecondsToSeconds, secondsToMilliseconds } from "motion-utils"
+import { secondsToMilliseconds } from "motion-utils"
import { time } from "../frameloop/sync-time"
import { animateStyle, setStyle } from "../effects/style/output"
import { sampleDelta } from "./utils/sample-delta"
-import { flushKeyframeResolvers } from "./keyframes/KeyframesResolver"
import { getFinalKeyframe } from "./keyframes/get-final"
import { inertia } from "./generators/inertia"
import { frameloopDriver } from "./drivers/frame"
@@ -28,6 +27,45 @@ import {
joinGroup,
TransformGroup,
} from "./waapi/transforms/TransformAnimation"
+import {
+ forgetLayer,
+ holdTransforms,
+ setCompositorLayer,
+} from "./waapi/transforms/groups"
+
+/**
+ * The controls of an animation that only code holding it can use:
+ * what `animate()` returns, a timeline, an animation attached to scroll.
+ * `supportPlayback()` adds them to the classes below. That's called by
+ * the code that hands out controls, so that components, which never do,
+ * don't carry them.
+ */
+export interface PlaybackControls {
+ duration: number
+ iterationDuration: number
+ time: number
+ play(): void
+ pause(): void
+ cancel(): void
+ attachTimeline(timeline: TimelineWithFallback): VoidFunction
+}
+
+export interface ValueTrack
+ extends PlaybackControls {
+ /**
+ * Follow a timeline on the shared clock, from JS.
+ */
+ observe(): void
+}
+
+export interface MultiValueAnimation extends PlaybackControls {
+ speed: number
+ complete(): void
+ /**
+ * Follow a timeline on the shared clock, from JS.
+ */
+ follow(timeline: TimelineWithFallback): void
+}
/**
* One value of a MultiValueAnimation. It's the value's animation (what the motion value
@@ -65,6 +103,12 @@ export class ValueTrack
*/
native?: Animation
+ /**
+ * What it was pooled with, so a `transform` that moved to the main
+ * thread can be pooled again.
+ */
+ pooled?: [Element, [KeyframeAnimationOptions, string[] | undefined]]
+
/**
* On WAAPI, following a native scroll timeline.
*/
@@ -171,6 +215,41 @@ export class ValueTrack
)
}
+ /**
+ * A `transform` moves from WAAPI to the main thread, while too many
+ * elements repaint.
+ */
+ demote() {
+ const { parent } = this
+ if (!this.native) return
+ release(parent, this)
+ this.generator || initTrack(this)
+ parent.state === "running" && parent.driver?.start()
+ }
+
+ /**
+ * And back, from where the clock has it. One that follows a timeline
+ * from the main thread stays there, as WAAPI would run it on a clock.
+ */
+ schedule() {
+ const { parent, pooled } = this
+ if (
+ this.native ||
+ this.isDone ||
+ this.isStopped ||
+ parent.isStopped ||
+ parent.isCancelled ||
+ parent.unfollow ||
+ !pooled
+ )
+ return
+ try {
+ const native = playPooled(this, ...pooled)
+ native.playbackRate = parent.playbackSpeed
+ syncNative(parent, native)
+ } catch {}
+ }
+
/**
* Write where the compositor has it, and its velocity, to the value.
*/
@@ -186,16 +265,6 @@ export class ValueTrack
)
}
- /**
- * Follow a timeline on the shared clock, from JS.
- */
- observe() {
- const timeline = this.scrollTimeline
- this.scrollTimeline = undefined
- this.canAccelerate = false
- timeline && this.parent.follow(timeline)
- }
-
/**
* What a group of animations holds for this value: the shared animation, while
* the value plays in it.
@@ -213,15 +282,6 @@ export class ValueTrack
: undefined
}
- get duration() {
- this.isReady || flushKeyframeResolvers()
- return millisecondsToSeconds(this.calculatedDuration)
- }
-
- get iterationDuration() {
- return this.duration + millisecondsToSeconds(this.options.delay || 0)
- }
-
get state() {
return this.isDone
? "finished"
@@ -234,30 +294,14 @@ export class ValueTrack
return this.parent.startTime
}
- get time() {
- return this.parent.time
- }
-
- set time(newTime: number) {
- this.parent.time = newTime
- }
-
get speed() {
- return this.parent.speed
+ return this.parent.playbackSpeed
}
set speed(newSpeed: number) {
this.parent.speed = newSpeed
}
- play() {
- this.parent.play()
- }
-
- pause() {
- this.parent.pause()
- }
-
/**
* Finish this value now, at its end, or played backwards, its start.
* Inertia has no target to end at, only where it is by now.
@@ -271,14 +315,6 @@ export class ValueTrack
)
finishTrack(this)
}
-
- cancel() {
- this.parent.cancel()
- }
-
- attachTimeline(timeline: TimelineWithFallback) {
- return this.parent.attachTimeline(timeline)
- }
}
/**
@@ -296,6 +332,7 @@ function finishTrack(track: ValueTrack) {
track.isDone = true
track.notifyFinished()
track.onDone()
+ track.pooled && forgetLayer(track)
track.plan.transition.onComplete?.()
group && !group.isFinishing && group.release(track)
;(track.native || group) && check(parent)
@@ -310,7 +347,7 @@ function endTrack(track: ValueTrack) {
options.keyframes,
options,
(options as any).finalKeyframe,
- track.parent.speed
+ track.parent.playbackSpeed
)
}
@@ -518,43 +555,31 @@ export class MultiValueAnimation
pool(
track: ValueTrack,
element: Element,
- [timing, easing]: [KeyframeAnimationOptions, string[] | undefined]
+ timing: [KeyframeAnimationOptions, string[] | undefined]
) {
- const { name, keyframes, times, delay } = track.options
- const frames: PropertyIndexedKeyframes = { [name!]: keyframes as any }
- if (times) frames.offset = times
- if (easing) frames.easing = easing
+ /**
+ * A `transform` makes a layer, as a group of transforms does, so
+ * it follows the same rule while too many elements repaint.
+ */
+ if (track.name === "transform" && !timing[0].pseudoElement) {
+ track.pooled = [element, timing]
+ if (holdTransforms(track)) return track.init()
+ }
- const native = animateStyle(element, frames, { ...timing, delay })
+ const native = playPooled(track, element, timing)
/**
* Its generator is only made if it's read or interrupted.
*/
- const { duration, iterations } = timing as any
+ const { duration, iterations } = timing[0] as any
track.calculatedDuration = track.resolvedDuration = duration
track.totalDuration = duration * iterations
- track.native = native
track.isReady = true
track.resolver = undefined
- watch(native, track)
this.onTrackReady(track)
syncNative(this, native)
}
- get duration() {
- this.numPending && flushKeyframeResolvers()
- return millisecondsToSeconds(this.calculatedDuration)
- }
-
- get iterationDuration() {
- this.numPending && flushKeyframeResolvers()
- let max = 0
- for (const { calculatedDuration, options } of this.tracks) {
- max = Math.max(max, calculatedDuration + (options.delay || 0))
- }
- return millisecondsToSeconds(max)
- }
-
/**
* Run the clock again, for values that move to the main thread.
*/
@@ -682,77 +707,6 @@ export class MultiValueAnimation
check(this)
}
- play() {
- if (this.isStopped) return
- if (this.state === "finished") revive(this)
- this.isCancelled = false
- run(this)
- natives(this, (native, track) => {
- watch(native, track)
- native.play()
- })
- regroup(this, false, true)
- }
-
- pause() {
- hold(this)
- natives(this, (native) => syncNative(this, native))
- regroup(this)
- }
-
- complete() {
- if (this.state !== "running") {
- this.play()
- }
-
- this.state = "finished"
- this.holdTime = null
- this.js?.start()
- natives(this, (native) => native.finish())
- }
-
- cancel() {
- this.isCancelling = this.isCancelled = true
- this.holdTime = null
- this.startTime = 0
- this.tick(0)
- teardown(this)
- fire(this, "onCancel")
- endValues(this)
- this.isCancelling = false
- natives(
- this,
- (native) => {
- watch(native)
- native.cancel()
- },
- true
- )
- leaveGroups(this)
- }
-
- get time() {
- this.isOffloaded && this.tick(time.now())
- return millisecondsToSeconds(this.currentTime)
- }
-
- set time(newTime: number) {
- setTime(this, secondsToMilliseconds(newTime), true)
- }
-
- get speed() {
- return this.playbackSpeed
- }
-
- set speed(newSpeed: number) {
- const hasChanged = this.playbackSpeed !== newSpeed && this.driver
- if (hasChanged) this.updateTime(time.now())
- this.playbackSpeed = newSpeed
- if (hasChanged) setTime(this, this.currentTime)
- natives(this, (native) => (native.playbackRate = newSpeed))
- regroup(this)
- }
-
protected stopAnimation() {
/**
* Values not yet set this frame are caught up to now.
@@ -769,22 +723,6 @@ export class MultiValueAnimation
}
leaveGroups(this)
}
-
- /**
- * Follow a timeline. The work is done by what `timelineSupport` holds,
- * which the code that makes animations to attach sets, so that
- * animations that are never attached don't carry it.
- */
- attachTimeline(timeline: TimelineWithFallback): VoidFunction {
- return timelineSupport.attach!(this, timeline)
- }
-
- /**
- * Follow a timeline on the shared clock, from JS.
- */
- follow(timeline: TimelineWithFallback) {
- this.unfollow ||= (this.driver?.stop(), timeline.observe(this))
- }
}
/**
@@ -801,7 +739,7 @@ function at(anim: MultiValueAnimation, timestamp: number) {
/**
* Call a lifecycle callback of each value still in the animation.
*/
-function fire(
+export function fire(
anim: MultiValueAnimation,
key: "onPlay" | "onStop" | "onCancel"
) {
@@ -810,10 +748,28 @@ function fire(
}
}
+/**
+ * Make the WAAPI animation of a track.
+ */
+function playPooled(
+ track: ValueTrack,
+ element: Element,
+ [timing, easing]: [KeyframeAnimationOptions, string[] | undefined]
+) {
+ const { name, keyframes, times, delay } = track.options
+ const frames: PropertyIndexedKeyframes = { [name!]: keyframes as any }
+ if (times) frames.offset = times
+ if (easing) frames.easing = easing
+
+ const native = animateStyle(element, frames, { ...timing, delay })
+ watch((track.native = native), track)
+ return native
+}
+
/**
* Start a WAAPI animation from the animation's start time and state.
*/
-function syncNative(anim: MultiValueAnimation, native: Animation) {
+export function syncNative(anim: MultiValueAnimation, native: Animation) {
if (anim.isCancelled) return native.cancel()
if (anim.startTime === null) return
if (anim.state === "paused") {
@@ -821,6 +777,12 @@ function syncNative(anim: MultiValueAnimation, native: Animation) {
native.currentTime = anim.holdTime ?? 0
} else {
native.startTime = anchor(anim, time.now())
+
+ /**
+ * At a speed of 0 it's running, but held. A start time alone
+ * would leave it at 0.
+ */
+ anim.holdTime === null || (native.currentTime = anim.holdTime)
}
}
@@ -843,7 +805,7 @@ function anchor(anim: MultiValueAnimation, now: number) {
* Apply a control to the tracks on WAAPI. Those on a scroll timeline
* follow it, so only a cancel reaches them.
*/
-function natives(
+export function natives(
anim: MultiValueAnimation,
control: (native: Animation, track: ValueTrack) => void,
all?: boolean
@@ -930,24 +892,10 @@ function check(anim: MultiValueAnimation) {
anim.isInterrupted || anim.notifyFinished()
}
-/**
- * Revive values that finished, as a group of animations does when
- * it's played or seeked again.
- */
-function revive(anim: MultiValueAnimation) {
- for (const track of anim.tracks) {
- if (track.isDone) {
- track.isDone = false
- anim.numDone--
- track.updateFinished()
- }
- }
-}
-
/**
* Start, or resume, the clock.
*/
-function run(anim: MultiValueAnimation) {
+export function run(anim: MultiValueAnimation) {
const { driver = frameloopDriver, startTime } = anim.options
if (!anim.driver) {
@@ -985,56 +933,18 @@ function run(anim: MultiValueAnimation) {
/**
* Hold the clock where it is.
*/
-function hold(anim: MultiValueAnimation) {
+export function hold(anim: MultiValueAnimation) {
anim.state = "paused"
anim.updateTime(time.now())
anim.holdTime = anim.currentTime
}
-function setTime(anim: MultiValueAnimation, ms: number, isSeek?: boolean) {
- revive(anim)
-
- /**
- * Seeking out of "finished" leaves the animation paused, so play()
- * won't renew finished. Renew it here.
- */
- if (anim.state === "finished") anim.updateFinished()
-
- anim.currentTime = ms
- const { driver, playbackSpeed } = anim
-
- if (driver) {
- if (
- anim.startTime === null ||
- anim.holdTime !== null ||
- !playbackSpeed
- ) {
- anim.holdTime = ms
- } else {
- anim.startTime = driver.now() - ms / playbackSpeed
- }
- driver.start(false)
- } else {
- anim.startTime = 0
- anim.state = "paused"
- anim.holdTime = ms
- anim.tick(ms)
- }
-
- natives(anim, (native, track) => {
- watch(native, track)
- native.currentTime = ms
- anim.holdTime === null && native.play()
- })
- isSeek && regroup(anim, true)
-}
-
/**
* The transform groups of its values follow a change to its playback,
* which a seek may need them to rebuild for. Played, values that left
* their group join it again.
*/
-function regroup(
+export function regroup(
anim: MultiValueAnimation,
isSeek?: boolean,
isPlay?: boolean
@@ -1064,15 +974,15 @@ function endValue(track: ValueTrack) {
value.animation === track && (value.animation = undefined)
}
-function endValues(anim: MultiValueAnimation) {
+export function endValues(anim: MultiValueAnimation) {
anim.tracks.forEach(endValue)
}
-function leaveGroups(anim: MultiValueAnimation) {
+export function leaveGroups(anim: MultiValueAnimation) {
for (const track of anim.tracks) track.group?.release(track)
}
-function teardown(
+export function teardown(
anim: MultiValueAnimation,
nextState: AnimationPlayState = "idle"
) {
@@ -1087,6 +997,7 @@ function teardown(
* value is where it was stopped.
*/
function leave(anim: MultiValueAnimation, track: ValueTrack) {
+ track.pooled && forgetLayer(track)
if (track.native) {
release(anim, track)
} else if (track.isAccelerated()) {
@@ -1162,6 +1073,9 @@ const commit = (track: ValueTrack, value: AnyResolvedKeyframe) => {
* references (#4034), so it's left pointing at nothing.
*/
export function watch(native: Animation, track?: ValueTrack) {
+ const watched: ValueTrack | undefined = (native as any).track
+ watched?.pooled && setCompositorLayer(watched, false)
+ track?.pooled && setCompositorLayer(track, true)
;(native as any).track = track
native.onfinish = track ? onNativeFinish : null
}
diff --git a/packages/motion-dom/src/animation/__tests__/playback.test.ts b/packages/motion-dom/src/animation/__tests__/playback.test.ts
new file mode 100644
index 0000000000..ccb958d178
--- /dev/null
+++ b/packages/motion-dom/src/animation/__tests__/playback.test.ts
@@ -0,0 +1,203 @@
+/**
+ * Animations get their playback controls from supportPlayback(), which
+ * the code that hands an animation to its caller calls first. Each of
+ * those is checked here from a fresh copy of the library, where nothing
+ * has called it yet.
+ */
+type Library = typeof import("../../index")
+
+const fresh = (
+ callback: (library: Library, hasControls: () => boolean) => void
+) => {
+ jest.isolateModules(() => {
+ const library: Library = require("../../index")
+ const { ValueTrack } = require("../MultiValueAnimation")
+ callback(library, () => "pause" in ValueTrack.prototype)
+ })
+}
+
+const createVisualElement = ({ HTMLVisualElement }: Library) => {
+ const visualElement = new HTMLVisualElement({
+ props: {},
+ presenceContext: null,
+ visualState: {
+ latestValues: {},
+ renderState: {
+ transform: {},
+ transformOrigin: {},
+ style: {},
+ vars: {},
+ },
+ },
+ } as any)
+ visualElement.mount(document.createElement("div"))
+ return visualElement
+}
+
+const expectControls = (animation: any) => {
+ animation.pause()
+ expect(animation.state).toBe("paused")
+
+ animation.time = 0.5
+ expect(animation.time).toBe(0.5)
+
+ animation.speed = 2
+ expect(animation.speed).toBe(2)
+
+ expect(animation.duration).toBe(1)
+ expect(animation.iterationDuration).toBe(1)
+
+ animation.play()
+ expect(animation.state).toBe("running")
+
+ animation.cancel()
+ expect(animation.state).toBe("idle")
+
+ animation.play()
+ animation.complete()
+ expect(animation.state).toBe("finished")
+}
+
+const transition = { duration: 1, ease: "linear" as const }
+
+describe("playback controls", () => {
+ test("an animation a component starts has none", () => {
+ fresh((library, hasControls) => {
+ const visualElement = createVisualElement(library)
+ library.animateVisualElement(visualElement, {
+ opacity: 0.5,
+ transition,
+ })
+
+ const animation = visualElement.getValue("opacity")!.animation!
+ expect(hasControls()).toBe(false)
+
+ /**
+ * What a motion value's animation is typed as having.
+ */
+ expect(animation.state).toBe("running")
+ expect(typeof animation.then).toBe("function")
+ animation.stop()
+ expect(animation.state).toBe("idle")
+ })
+ })
+
+ test("animateMotionValue() gives them to callers outside the library", () => {
+ fresh((library, hasControls) => {
+ const value = library.motionValue(0)
+ expect(hasControls()).toBe(false)
+ value.start(library.animateMotionValue("", value, 100, transition))
+
+ expect(value.isAnimating()).toBe(true)
+ expectControls(value.animation)
+ value.stop()
+ expect(value.isAnimating()).toBe(false)
+ })
+ })
+
+ /**
+ * An inspector behind __MOTION_INSPECT__ is handed each animation as
+ * it starts, and controls it.
+ */
+ test("an inspector gets them with the animation a component starts", async () => {
+ const inspected: any[] = []
+ ;(globalThis as any).__MOTION_INSPECT__ = (record: any) => {
+ /**
+ * There when the inspector is told, not after.
+ */
+ expect(typeof record.animation.pause).toBe("function")
+ inspected.push(record)
+ }
+
+ let nextFrame!: () => Promise
+ try {
+ fresh((library) => {
+ nextFrame = () =>
+ new Promise((resolve) =>
+ library.frame.postRender(() => resolve())
+ )
+ library.animateVisualElement(createVisualElement(library), {
+ opacity: 0.5,
+ transition,
+ })
+ })
+ await nextFrame()
+
+ expect(inspected).toHaveLength(1)
+ expectControls(inspected[0].animation)
+ } finally {
+ delete (globalThis as any).__MOTION_INSPECT__
+ }
+ })
+
+ test("animateSingleValue() gives them", () => {
+ fresh((library, hasControls) => {
+ expect(hasControls()).toBe(false)
+ expectControls(library.animateSingleValue(0, 100, transition))
+ })
+ })
+
+ test("animateValue() gives them", () => {
+ fresh((library, hasControls) => {
+ expect(hasControls()).toBe(false)
+ expectControls(
+ library.animateValue({
+ keyframes: [0, 100],
+ ease: "linear",
+ duration: 1000,
+ })
+ )
+ })
+ })
+
+ test("animateElement() gives them", () => {
+ fresh((library, hasControls) => {
+ expect(hasControls()).toBe(false)
+ const [animation] = library.animateElement(
+ document.createElement("div"),
+ { opacity: [0, 1] },
+ transition
+ )
+ expectControls(animation)
+ })
+ })
+
+ test("animateTarget() gives them to callers outside the library", () => {
+ fresh((library, hasControls) => {
+ const visualElement = createVisualElement(library)
+ expect(hasControls()).toBe(false)
+ const [animation] = library.animateTarget(visualElement, {
+ opacity: 0.5,
+ transition,
+ })
+ expectControls(animation)
+ })
+ })
+
+ test("an animation started before they were given has them after", () => {
+ fresh((library, hasControls) => {
+ const visualElement = createVisualElement(library)
+ library.animateVisualElement(visualElement, {
+ opacity: 0.5,
+ transition,
+ })
+ const animation = visualElement.getValue("opacity")!.animation!
+ expect(hasControls()).toBe(false)
+
+ library.supportPlayback()
+
+ expectControls(animation)
+ })
+ })
+
+ test("controls are not listed among an animation's own keys", () => {
+ fresh((library) => {
+ const animation = library.animateSingleValue(0, 100, transition)
+ const keys: string[] = []
+ for (const key in animation) keys.push(key)
+ expect(keys).not.toContain("pause")
+ expect(keys).not.toContain("time")
+ animation.stop()
+ })
+ })
+})
diff --git a/packages/motion-dom/src/animation/animate/attach-timeline.ts b/packages/motion-dom/src/animation/animate/attach-timeline.ts
index 62a5380fb2..634057314f 100644
--- a/packages/motion-dom/src/animation/animate/attach-timeline.ts
+++ b/packages/motion-dom/src/animation/animate/attach-timeline.ts
@@ -31,8 +31,15 @@ function attachTimeline(
let needsFollow = false
for (const track of animation.tracks) {
- const { native, options } = track
+ const { options } = track
if (track.isStopped) continue
+
+ /**
+ * A `transform` held on the main thread while too many elements
+ * repaint joins a native timeline on the compositor.
+ */
+ isNative && track.schedule()
+ const { native } = track
if (track.plan.base.allowFlatten) {
native
? native.effect?.updateTiming({ easing: "linear" })
diff --git a/packages/motion-dom/src/animation/animate/effects.ts b/packages/motion-dom/src/animation/animate/effects.ts
index c2115fb87c..7fa87d91dd 100644
--- a/packages/motion-dom/src/animation/animate/effects.ts
+++ b/packages/motion-dom/src/animation/animate/effects.ts
@@ -7,6 +7,7 @@ import { transformProps } from "../../render/utils/keys-transform"
import { markRepaint } from "../waapi/transforms/groups"
import { acceleratedValues } from "../waapi/utils/accelerated-values"
import { MotionValue } from "../../value"
+import { supportPlayback } from "../playback"
import { MultiValueRef, startValueAnimation } from "./multi-value"
export type { MultiValueRef }
import { AnimationElement } from "../keyframes/types"
@@ -79,6 +80,7 @@ export function animateValues(
*/
animationRef?: MultiValueRef
): AnimationPlaybackControlsWithThen[] {
+ supportPlayback()
const animations: AnimationPlaybackControlsWithThen[] = []
const { velocity, path } = transition
const ref: MultiValueRef = animationRef || {}
@@ -99,7 +101,8 @@ export function animateValues(
*/
let composes = false
- if (element?.current instanceof HTMLElement) {
+ const isHTML = element?.current instanceof HTMLElement
+ if (isHTML) {
for (const key in keyframes) composes ||= transformProps.has(key)
}
@@ -149,10 +152,10 @@ export function animateValues(
/**
* A style animating on the main thread repaints the element. It's
- * counted before its transforms first build, so if too many
- * elements repaint, they start on the main thread.
+ * counted before any transforms first build, so if too many
+ * elements repaint, transforms start on the main thread.
*/
- composes &&
+ isHTML &&
!(
transformProps.has(key) ||
acceleratedValues.has(key) ||
diff --git a/packages/motion-dom/src/animation/animate/multi-value.ts b/packages/motion-dom/src/animation/animate/multi-value.ts
index 694758936b..a7acb6dc06 100644
--- a/packages/motion-dom/src/animation/animate/multi-value.ts
+++ b/packages/motion-dom/src/animation/animate/multi-value.ts
@@ -27,6 +27,8 @@ import { keyframes as keyframesType } from "../generators/keyframes"
import { spring } from "../generators/spring"
import { createGeneratorEasing } from "../generators/utils/create-generator-easing"
import { canGroupValue } from "../waapi/transforms/TransformAnimation"
+import { isInspected } from "../utils/notify-inspector"
+import { supportPlayback } from "../playback"
/**
* What every value of one key in a call animates with, worked out once
@@ -434,6 +436,17 @@ export const startValueAnimation =
* its group, which plays them in one WAAPI animation.
*/
const isTransform = canGroupValue(name, value, composes)
+
+ /**
+ * An inspector controls the animations it is told of, including
+ * those of components, which hand out no controls otherwise. It
+ * runs on development builds, so that production builds of
+ * components stay without the code.
+ */
+ process.env.NODE_ENV !== "production" &&
+ isInspected() &&
+ supportPlayback()
+
const parent = (ref.animation ||= new MultiValueAnimation(base.driver))
const parentOptions = parent.options
if (base.autoplay === false) parentOptions.autoplay = false
diff --git a/packages/motion-dom/src/animation/animate/single-value.ts b/packages/motion-dom/src/animation/animate/single-value.ts
index 5a84fd50ef..81c01eb111 100644
--- a/packages/motion-dom/src/animation/animate/single-value.ts
+++ b/packages/motion-dom/src/animation/animate/single-value.ts
@@ -10,12 +10,14 @@ import {
MotionValue,
} from "../../value"
import { isMotionValue } from "../../value/utils/is-motion-value"
+import { supportPlayback } from "../playback"
export function animateSingleValue(
value: MotionValue | V,
keyframes: V | UnresolvedValueKeyframe[],
options?: ValueAnimationTransition
): AnimationPlaybackControlsWithThen {
+ supportPlayback()
const motionValue = isMotionValue(value) ? value : createMotionValue(value)
motionValue.run(animateMotionValue("", motionValue, keyframes, options))
diff --git a/packages/motion-dom/src/animation/interfaces/with-playback.ts b/packages/motion-dom/src/animation/interfaces/with-playback.ts
new file mode 100644
index 0000000000..95744252ce
--- /dev/null
+++ b/packages/motion-dom/src/animation/interfaces/with-playback.ts
@@ -0,0 +1,16 @@
+import { supportPlayback } from "../playback"
+import { animateMotionValue } from "./motion-value"
+import { animateTarget } from "./visual-element-target"
+
+/**
+ * `animateTarget()` and `animateMotionValue()` for callers outside the
+ * library, which get the animations and so their controls. Components
+ * use them as they are.
+ */
+export const animateTargetWithPlayback: typeof animateTarget = (...args) => (
+ supportPlayback(), animateTarget(...args)
+)
+
+export const animateMotionValueWithPlayback: typeof animateMotionValue = (
+ ...args
+) => (supportPlayback(), animateMotionValue(...args))
diff --git a/packages/motion-dom/src/animation/playback.ts b/packages/motion-dom/src/animation/playback.ts
new file mode 100644
index 0000000000..76403f4b01
--- /dev/null
+++ b/packages/motion-dom/src/animation/playback.ts
@@ -0,0 +1,243 @@
+import { millisecondsToSeconds, secondsToMilliseconds } from "motion-utils"
+import { time } from "../frameloop/sync-time"
+import { flushKeyframeResolvers } from "./keyframes/KeyframesResolver"
+import {
+ endValues,
+ fire,
+ hold,
+ leaveGroups,
+ MultiValueAnimation,
+ natives,
+ regroup,
+ run,
+ syncNative,
+ teardown,
+ timelineSupport,
+ ValueTrack,
+ watch,
+} from "./MultiValueAnimation"
+import type { TimelineWithFallback } from "./types"
+import { retime } from "./waapi/transforms/retime"
+import { groupSupport } from "./waapi/transforms/TransformAnimation"
+
+/**
+ * Revive values that finished, as a group of animations does when
+ * it's played or seeked again.
+ */
+function revive(anim: MultiValueAnimation) {
+ for (const track of anim.tracks) {
+ if (track.isDone) {
+ track.isDone = false
+ anim.numDone--
+ track.updateFinished()
+ }
+ }
+}
+
+function setTime(anim: MultiValueAnimation, ms: number, isSeek?: boolean) {
+ revive(anim)
+
+ /**
+ * Seeking out of "finished" leaves the animation paused, so play()
+ * won't renew finished. Renew it here.
+ */
+ if (anim.state === "finished") anim.updateFinished()
+
+ anim.currentTime = ms
+ const { driver, playbackSpeed } = anim
+
+ if (driver) {
+ if (
+ anim.startTime === null ||
+ anim.holdTime !== null ||
+ !playbackSpeed
+ ) {
+ anim.holdTime = ms
+ } else {
+ anim.startTime = driver.now() - ms / playbackSpeed
+ }
+ driver.start(false)
+ } else {
+ anim.startTime = 0
+ anim.state = "paused"
+ anim.holdTime = ms
+ anim.tick(ms)
+ }
+
+ natives(anim, (native, track) => {
+ watch(native, track)
+ native.currentTime = ms
+ anim.holdTime === null && native.play()
+ })
+ isSeek && regroup(anim, true)
+}
+
+/**
+ * The controls of a shared animation.
+ */
+const animationPlayback: ThisType = {
+ get duration() {
+ this.numPending && flushKeyframeResolvers()
+ return millisecondsToSeconds(this.calculatedDuration)
+ },
+
+ get iterationDuration() {
+ this.numPending && flushKeyframeResolvers()
+ let max = 0
+ for (const { calculatedDuration, options } of this.tracks) {
+ max = Math.max(max, calculatedDuration + (options.delay || 0))
+ }
+ return millisecondsToSeconds(max)
+ },
+
+ play() {
+ if (this.isStopped) return
+ if (this.state === "finished") revive(this)
+ this.isCancelled = false
+ run(this)
+ natives(this, (native, track) => {
+ watch(native, track)
+ native.play()
+ })
+ regroup(this, false, true)
+ },
+
+ pause() {
+ hold(this)
+ natives(this, (native) => syncNative(this, native))
+ regroup(this)
+ },
+
+ complete() {
+ if (this.state !== "running") {
+ this.play()
+ }
+
+ this.state = "finished"
+ this.holdTime = null
+ this.js?.start()
+ natives(this, (native) => native.finish())
+ },
+
+ cancel() {
+ this.isCancelling = this.isCancelled = true
+ this.holdTime = null
+ this.startTime = 0
+ this.tick(0)
+ teardown(this)
+ fire(this, "onCancel")
+ endValues(this)
+ this.isCancelling = false
+ natives(
+ this,
+ (native) => {
+ watch(native)
+ native.cancel()
+ },
+ true
+ )
+ leaveGroups(this)
+ },
+
+ get time() {
+ this.isOffloaded && this.tick(time.now())
+ return millisecondsToSeconds(this.currentTime)
+ },
+
+ set time(newTime: number) {
+ setTime(this, secondsToMilliseconds(newTime), true)
+ },
+
+ get speed() {
+ return this.playbackSpeed
+ },
+
+ set speed(newSpeed: number) {
+ const hasChanged = this.playbackSpeed !== newSpeed && this.driver
+ if (hasChanged) this.updateTime(time.now())
+ this.playbackSpeed = newSpeed
+ if (hasChanged) setTime(this, this.currentTime)
+ natives(this, (native) => (native.playbackRate = newSpeed))
+ regroup(this)
+ },
+
+ /**
+ * Follow a timeline. The work is done by what `timelineSupport` holds,
+ * which the code that makes animations to attach sets, so that
+ * animations that are never attached don't carry it.
+ */
+ attachTimeline(timeline: TimelineWithFallback): VoidFunction {
+ return timelineSupport.attach!(this, timeline)
+ },
+
+ follow(timeline: TimelineWithFallback) {
+ this.unfollow ||= (this.driver?.stop(), timeline.observe(this))
+ },
+}
+
+/**
+ * The controls of one value. It has no clock of its own: a control of
+ * one value controls the shared animation.
+ */
+const trackPlayback: ThisType = {
+ observe() {
+ const timeline = this.scrollTimeline
+ this.scrollTimeline = undefined
+ this.canAccelerate = false
+ timeline && this.parent.follow(timeline)
+ },
+
+ get duration() {
+ this.isReady || flushKeyframeResolvers()
+ return millisecondsToSeconds(this.calculatedDuration)
+ },
+
+ get iterationDuration() {
+ return this.duration + millisecondsToSeconds(this.options.delay || 0)
+ },
+
+ get time() {
+ return this.parent.time
+ },
+
+ set time(newTime: number) {
+ this.parent.time = newTime
+ },
+
+ play() {
+ this.parent.play()
+ },
+
+ pause() {
+ this.parent.pause()
+ },
+
+ cancel() {
+ this.parent.cancel()
+ },
+
+ attachTimeline(timeline: TimelineWithFallback) {
+ return this.parent.attachTimeline(timeline)
+ },
+}
+
+const install = (target: object, controls: object) => {
+ const descriptors = Object.getOwnPropertyDescriptors(controls)
+ for (const key in descriptors) descriptors[key].enumerable = false
+ Object.defineProperties(target, descriptors)
+}
+
+let isSupported: boolean | undefined
+
+/**
+ * Give shared animations their playback controls. Called by the code
+ * that hands an animation's controls to its caller, before it does, so
+ * that the animations of bundles with no such code don't carry them.
+ */
+export const supportPlayback = () => {
+ if (isSupported) return
+ isSupported = true
+ install(MultiValueAnimation.prototype, animationPlayback)
+ install(ValueTrack.prototype, trackPlayback)
+ groupSupport.retime = retime
+}
diff --git a/packages/motion-dom/src/animation/utils/notify-inspector.ts b/packages/motion-dom/src/animation/utils/notify-inspector.ts
index 0469204772..0a312adb5b 100644
--- a/packages/motion-dom/src/animation/utils/notify-inspector.ts
+++ b/packages/motion-dom/src/animation/utils/notify-inspector.ts
@@ -41,6 +41,12 @@ function baseRecord(
}
}
+/**
+ * Whether an inspector is listening.
+ */
+export const isInspected = () =>
+ Boolean((globalThis as InspectGlobal).__MOTION_INSPECT__)
+
/**
* Notify an optional inspector without adding a public Motion API.
*
diff --git a/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts b/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts
index eca91e1129..0e64b259b7 100644
--- a/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts
+++ b/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts
@@ -37,9 +37,9 @@ import { acceleratedValues } from "../utils/accelerated-values"
import { generateLinearEasing } from "../utils/linear"
import { supportsLinearEasing } from "../../../utils/supports/linear-easing"
import {
- addCompositorLayer,
- isRepainting,
- markRepaint,
+ forgetLayer,
+ holdTransforms,
+ setCompositorLayer,
TransformGroupHooks,
transformGroups,
} from "./groups"
@@ -72,7 +72,7 @@ interface TransformOwner extends Owner {
projection?: { isProjecting(): boolean }
}
-type TransformMember = ValueTrack
+export type TransformMember = ValueTrack
export interface TransformGroup extends TransformGroupHooks {
tracks: Set
@@ -112,7 +112,27 @@ export interface TransformGroup extends TransformGroupHooks {
* Where each animation was when the WAAPI animation was built: its time,
* speed and whether it was held.
*/
-type BuiltState = [number, number, boolean]
+export type BuiltState = [number, number, boolean]
+
+/**
+ * Does to a group's WAAPI animation what was done to its animations:
+ * a pause, a seek, a change of speed. Only an animation with controls
+ * can be, so `supportPlayback()` sets it, and a group rebuilds its WAAPI
+ * animation where it's not set.
+ */
+export const groupSupport: {
+ retime?: (
+ tracks: Set,
+ built: Map,
+ native: Animation | undefined,
+ buildAt: number | undefined,
+ nativeStart: number,
+ nativeLength: number,
+ sleep: (delay?: number) => void,
+ now: number,
+ isSeek: boolean
+ ) => boolean
+} = {}
/**
* How an animation runs as WAAPI keyframes: [start, duration, iterations,
@@ -210,7 +230,7 @@ const hasEnded = ({ state }: TransformMember) =>
* Whether a track is held (paused or speed 0) and not on a native scroll
* timeline.
*/
-const isHeld = (track: TransformMember) =>
+export const isHeld = (track: TransformMember) =>
!track.scrollTimeline && (track.parent.holdTime !== null || !track.speed)
/**
@@ -488,9 +508,9 @@ function createGroup(owner: TransformOwner): TransformGroup {
* Each group waiting to build has a timer of its own. Waking several
* at once, or from one queue of them all, costs more per frame.
*/
- const sleep = (delay: number) => {
+ const sleep = (delay?: number) => {
clearTimeout(wakeTimer)
- wakeTimer = setTimeout(wake, delay)
+ delay === undefined || (wakeTimer = setTimeout(wake, delay))
}
/**
* How long after it was last built to build it, while waiting.
@@ -551,7 +571,8 @@ function createGroup(owner: TransformOwner): TransformGroup {
native.onfinish = native.oncancel = null
native.cancel()
native = scrollAnimation = undefined
- addCompositorLayer(-1)
+ group.isScrolling = false
+ setCompositorLayer(group, false)
}
}
@@ -607,7 +628,7 @@ function createGroup(owner: TransformOwner): TransformGroup {
* Something else cancelled it, so carry on on the main thread.
*/
animation.oncancel = () => native === animation && demote()
- native || addCompositorLayer(1)
+ native || setCompositorLayer(group, true)
return (native = animation)
}
@@ -954,112 +975,13 @@ function createGroup(owner: TransformOwner): TransformGroup {
animation.timeline = timeline.timeline as AnimationTimeline
timeline.onAttach ? timeline.onAttach(animation) : animation.play()
scrollAnimation = animation
- }
-
- /**
- * If every animation has been paused, played, seeked or sped up
- * together since the WAAPI animation was built, do the same to it.
- * Returns false if it needs rebuilding instead.
- */
- const retime = (now: number, isSeek: boolean) => {
- let elapsed: number | undefined
- let rate = 0
- let last: TransformMember | undefined
-
- for (const track of tracks) {
- last = track
- const state = built.get(track)
- if (!state) return false
-
- const [builtTime, builtSpeed, wasHeld] = state
- const trackTime = track.at(now)
- const trackHeld = isHeld(track)
-
- /**
- * With nothing on the compositor, a held animation is set
- * where it's held, so it can be seeked as often as needed.
- */
- if (wasHeld) {
- if (trackHeld && (trackTime === builtTime || !native)) continue
- return false
- }
-
- const trackElapsed = (trackTime - builtTime) / builtSpeed
- const trackRate = trackHeld ? 0 : track.speed / builtSpeed
-
- if (elapsed === undefined) {
- elapsed = trackElapsed
- rate = trackRate
- } else if (
- Math.abs(trackElapsed - elapsed) > 1 ||
- trackRate !== rate
- ) {
- return false
- }
- }
-
- /**
- * Waiting to build, the values hold where they start, so only
- * when to build changes. Held, there's nothing to build yet.
- */
- if (buildAt !== undefined) {
- if (elapsed === undefined || (isSeek && rate)) return false
- clearTimeout(wakeTimer)
- if (rate < 0) {
- /**
- * Played backwards from before it moves, it never does,
- * so it only finishes, once back at its start.
- */
- sleep(last!.at(now) / -last!.speed + 16)
- } else if (rate) {
- const delay = (buildAt - elapsed) / rate
- if (delay < 1) return false
- sleep(delay)
- }
- return true
- }
-
- if (elapsed === undefined || !native) return true
+ group.isScrolling = true
/**
- * Seeking to before it starts, or past its end, rebuilds. A seek
- * every frame then moves the group to the main thread.
+ * If it was held before it joined its timeline, the end of that
+ * hold has nothing to return.
*/
- const local = elapsed - nativeStart
- if (
- (local < 0 && (isSeek || nativeStart <= 0)) ||
- local >= nativeLength
- ) {
- return false
- }
-
- if (rate) {
- if (
- native.updatePlaybackRate &&
- native.playState === "running" &&
- Math.abs(Number(native.currentTime) - local) < 20
- ) {
- /**
- * Only the speed changed. Setting playbackRate and
- * startTime restarts a running compositor animation, which
- * can render the underlying value for a frame.
- */
- native.playbackRate !== rate && native.updatePlaybackRate(rate)
- } else {
- native.playbackRate !== rate && (native.playbackRate = rate)
- native.startTime = now - local / rate
- }
- } else {
- /**
- * Hold it without pause(), whose pending pause setting
- * currentTime would end at once, leaving WebKit holding its
- * ready time (see create()).
- */
- native.startTime = null
- native.currentTime = local
- }
-
- return true
+ forgetLayer(group)
}
/**
@@ -1070,6 +992,7 @@ function createGroup(owner: TransformOwner): TransformGroup {
if (tracks.size) return false
isEnded = true
+ forgetLayer(group)
/**
* The element may have a newer group if this one was detached
* (see handOffElementState).
@@ -1125,12 +1048,6 @@ function createGroup(owner: TransformOwner): TransformGroup {
if (end()) return
- /**
- * One of too many elements repainting every frame, it stays on the
- * main thread until it stops.
- */
- if (isRepainting(element)) return demote(true)
-
let timeline: TimelineWithFallback | undefined | false = false
for (const track of tracks) {
const { scrollTimeline } = track
@@ -1143,6 +1060,12 @@ function createGroup(owner: TransformOwner): TransformGroup {
timeline = scrollTimeline
}
+ /**
+ * While too many elements repaint every frame, it stays on the
+ * main thread, unless it's on a scroll timeline.
+ */
+ if (!timeline && holdTransforms(group)) return demote(true)
+
/**
* Everything that kept the group on the main thread has finished,
* so move the remaining animations back to the compositor.
@@ -1158,7 +1081,20 @@ function createGroup(owner: TransformOwner): TransformGroup {
if (timeline) return buildScroll(timeline)
- if (shouldBuild || !retime(now, churned)) {
+ if (
+ shouldBuild ||
+ !groupSupport.retime?.(
+ tracks,
+ built,
+ native,
+ buildAt,
+ nativeStart,
+ nativeLength,
+ sleep,
+ now,
+ churned
+ )
+ ) {
if (churned) {
if (now - lastChurn < churnWindow) return demote()
lastChurn = now
@@ -1278,8 +1214,6 @@ function createGroup(owner: TransformOwner): TransformGroup {
}
}
},
-
- repaint: (value) => markRepaint(element, value),
}
transformGroups.set(element, group)
diff --git a/packages/motion-dom/src/animation/waapi/transforms/__tests__/TransformAnimation.test.ts b/packages/motion-dom/src/animation/waapi/transforms/__tests__/TransformAnimation.test.ts
index b934e76d80..d713e430a5 100644
--- a/packages/motion-dom/src/animation/waapi/transforms/__tests__/TransformAnimation.test.ts
+++ b/packages/motion-dom/src/animation/waapi/transforms/__tests__/TransformAnimation.test.ts
@@ -1,7 +1,8 @@
-import { animateElement } from "../../../animate/element"
+import { animateElement as animate } from "../../../animate/element"
import { ValueTrack } from "../../../MultiValueAnimation"
+import * as groups from "../groups"
import { repaintLimit } from "../groups"
-import { frame } from "../../../../frameloop"
+import { cancelFrame, frame } from "../../../../frameloop"
import { time } from "../../../../frameloop/sync-time"
import { styleEffect } from "../../../../effects/style"
import { motionValue } from "../../../../value"
@@ -60,7 +61,10 @@ const createAnimation = (
clearTimeout(timer)
const { duration, iterations = 1 } = options
const { playbackRate } = animation
- if (value === null || iterations === Infinity) return
+ /**
+ * At a rate of 0 it never ends.
+ */
+ if (value === null || iterations === Infinity || !playbackRate) return
/**
* Played backwards, it finishes when it gets back to 0.
*/
@@ -163,7 +167,21 @@ beforeEach(() => {
animations = []
})
+/**
+ * Compositor layers are counted across the page, and an animation that a
+ * test leaves running holds one until it finishes, which can be during a
+ * later test. So each test's animations are stopped before the next.
+ */
+const unstopped: Array<{ stop: VoidFunction }> = []
+const animateElement: typeof animate = (...args) => {
+ const started = animate(...args)
+ unstopped.push(...started)
+ return started
+}
+
afterEach(() => {
+ unstopped.forEach((animation) => animation.stop())
+ unstopped.length = 0
jest.restoreAllMocks()
})
@@ -173,6 +191,20 @@ const nextFrame = () =>
const wait = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms))
+/**
+ * How far a WAAPI animation is from the animation that drives it, in
+ * milliseconds. Both are read at one moment, as a busy machine can stall
+ * between two reads, and at twice the speed that doubles.
+ */
+const drift = (waapi: MockAnimation, animation: { time: number }) => {
+ const clock = jest
+ .spyOn(performance, "now")
+ .mockReturnValue(performance.now())
+ const distance = Math.abs(waapi.currentTime! - animation.time * 1000)
+ clock.mockRestore()
+ return distance
+}
+
/**
* Wait frames until an element has a WAAPI transform animation, as a
* group builds on a timer that a busy machine can run late.
@@ -255,6 +287,25 @@ const xAt = ({ keyframes, options }: MockAnimation, ms: number) => {
}
describe("independent transform acceleration", () => {
+ /**
+ * A touch device with no layers to spare, unless a test says
+ * otherwise: only then do few repainting elements hold transforms on
+ * the main thread.
+ */
+ const media = { matches: true }
+ const { touch: touchLimit } = groups.layerLimits
+ beforeAll(() => {
+ window.matchMedia = (() => media) as any
+ groups.layerLimits.touch = 0
+ })
+ afterAll(() => {
+ groups.layerLimits.touch = touchLimit
+ })
+ afterEach(() => {
+ media.matches = true
+ groups.layerLimits.touch = 0
+ })
+
it("composes every transform on an element into one WAAPI animation", async () => {
const element = document.createElement("div")
@@ -798,9 +849,7 @@ describe("independent transform acceleration", () => {
animation.forEach((a) => (a.speed = 2))
await nextFrame()
expect(waapi.playbackRate).toBe(2)
- expect(
- Math.abs(waapi.currentTime! - animation[0].time * 1000)
- ).toBeLessThan(20)
+ expect(drift(waapi, animation[0])).toBeLessThan(20)
expect(created(element).length).toBe(count)
expect(running(element)).toEqual([waapi])
@@ -919,9 +968,7 @@ describe("independent transform acceleration", () => {
await nextFrame()
expect(waapi.updatePlaybackRate).toHaveBeenCalledWith(2)
- expect(
- Math.abs(waapi.currentTime! - animation[0].time * 1000)
- ).toBeLessThan(20)
+ expect(drift(waapi, animation[0])).toBeLessThan(20)
expect(running(element)).toEqual([waapi])
})
@@ -2023,10 +2070,44 @@ describe("independent transform acceleration", () => {
return animations
}
+ /**
+ * How late a timer runs is how the rule finds a blocked main
+ * thread, and on a machine that runs other suites at the same
+ * time it runs late whatever these tests do. So the timer is held
+ * unless a test blocks the main thread itself.
+ */
+ let probes: VoidFunction[] = []
+ let timeouts: jest.SpyInstance | undefined
+ const freeThread = () => {
+ const setTimer = globalThis.setTimeout
+ timeouts = jest
+ .spyOn(globalThis, "setTimeout")
+ .mockImplementation(((
+ callback: VoidFunction,
+ ...args: [number?]
+ ) =>
+ callback.name === "probe"
+ ? probes.push(callback)
+ : setTimer(callback, ...args)) as typeof setTimeout)
+ }
+ const measureThread = () => {
+ timeouts?.mockRestore()
+ timeouts = undefined
+ }
+
+ beforeEach(freeThread)
+
afterEach(async () => {
started.forEach((animation) => animation.stop())
started.length = 0
for (let i = 0; i < 3; i++) await nextFrame()
+ measureThread()
+
+ /**
+ * With no frames left to compare, a held timer ends itself.
+ */
+ probes.forEach((probe) => probe())
+ probes = []
})
it("stay on the compositor for a few elements", async () => {
@@ -2136,6 +2217,119 @@ describe("independent transform acceleration", () => {
}
})
+ it("elements that only move run on the main thread while many others move and repaint", async () => {
+ const painters = elements(repaintLimit)
+ const movers = elements(3)
+
+ for (const element of movers) {
+ animateBox(element, { x: [0, 100] }, { duration: 1, ease: "linear" })
+ }
+ await untilRunning(movers[0], 500)
+ for (const element of painters) {
+ animateBox(
+ element,
+ { x: [0, 100], borderRadius: ["0px", "10px"] },
+ { duration: 1, ease: "linear" }
+ )
+ }
+ await nextFrame()
+ await nextFrame()
+ const first = movers[0].style.transform
+ await wait(50)
+ await nextFrame()
+
+ /**
+ * A layer that moves over an element that repaints makes the
+ * browser give that element a layer too, so each is rastered
+ * on its own again.
+ */
+ for (const element of movers) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+ expect(readX(movers[0].style.transform)).toBeGreaterThan(
+ readX(first)
+ )
+ })
+
+ it("elements that only move run on the main thread while many others only repaint", async () => {
+ const painters = elements(repaintLimit)
+ const movers = elements(3)
+
+ for (const element of painters) {
+ animateBox(
+ element,
+ { borderRadius: ["0px", "10px"] },
+ { duration: 1, ease: "linear" }
+ )
+ }
+ for (const element of movers) {
+ animateBox(element, { x: [0, 100] }, { duration: 1, ease: "linear" })
+ }
+ await nextFrame()
+ await nextFrame()
+ await wait(50)
+ await nextFrame()
+
+ for (const element of movers) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+ expect(readX(movers[0].style.transform)).toBeGreaterThan(0)
+ })
+
+ it("elements that only move stay on the compositor while a few others repaint", async () => {
+ const painters = elements(repaintLimit - 1)
+ const movers = elements(3)
+
+ for (const element of painters) {
+ animateBox(
+ element,
+ { borderRadius: ["0px", "10px"] },
+ { duration: 1, ease: "linear" }
+ )
+ }
+ for (const element of movers) {
+ animateBox(element, { x: [0, 100] }, { duration: 1, ease: "linear" })
+ }
+ await untilRunning(movers[0], 500)
+ await wait(50)
+ await nextFrame()
+
+ for (const element of movers) {
+ expect(transforms(element)).toHaveLength(1)
+ }
+ })
+
+ it("elements that only move go back to the compositor when the others stop repainting", async () => {
+ const painters = elements(repaintLimit)
+ const movers = elements(3)
+
+ for (const element of movers) {
+ animateBox(element, { x: [0, 100] }, { duration: 2 })
+ }
+ await untilRunning(movers[0], 500)
+ for (const element of painters) {
+ animateBox(
+ element,
+ { borderRadius: ["0px", "10px"] },
+ { duration: 0.1 }
+ )
+ }
+ await wait(50)
+ await nextFrame()
+
+ for (const element of movers) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+
+ await wait(200)
+ await nextFrame()
+ await nextFrame()
+
+ for (const element of movers) {
+ expect(transforms(element)).toHaveLength(1)
+ }
+ })
+
it("move back to the compositor when the elements stop repainting", async () => {
const boxes = elements(repaintLimit)
@@ -2236,6 +2430,749 @@ describe("independent transform acceleration", () => {
}
})
+ describe("and a transform on a native scroll timeline", () => {
+ beforeAll(() => {
+ supportsFlags.scrollTimeline = true
+ })
+
+ afterAll(() => {
+ supportsFlags.scrollTimeline = undefined
+ })
+
+ const scrollTimeline = {}
+ const follow = (animations: ReturnType) => {
+ const timeline = {
+ timeline: scrollTimeline,
+ observe: jest.fn(() => () => {}),
+ }
+ animations.forEach((a) => a.attachTimeline(timeline as any))
+ return timeline
+ }
+ const onTimeline = (element: Element) =>
+ running(element).filter((a) => a.timeline === scrollTimeline)
+
+ const repaint = () => {
+ for (const element of elements(repaintLimit)) {
+ animateBox(
+ element,
+ { borderRadius: ["0px", "10px"] },
+ { duration: 0.1 }
+ )
+ }
+ }
+
+ /**
+ * The compositor moves it with the scroll, which the main
+ * thread can't do. And one moved to the main thread couldn't
+ * return to its timeline.
+ */
+ it("stays on its timeline while many other elements repaint", async () => {
+ const element = document.createElement("div")
+ const timeline = follow(
+ animateBox(
+ element,
+ { x: [0, 100] },
+ { ease: "linear", duration: 1 }
+ )
+ )
+ await nextFrame()
+ expect(onTimeline(element)).toHaveLength(1)
+
+ repaint()
+ await wait(50)
+ await nextFrame()
+
+ expect(onTimeline(element)).toHaveLength(1)
+ expect(timeline.observe).not.toHaveBeenCalled()
+
+ await wait(200)
+ await nextFrame()
+ await nextFrame()
+
+ expect(onTimeline(element)).toHaveLength(1)
+ expect(created(element)).toHaveLength(1)
+ })
+
+ it("joins its timeline while many other elements repaint", async () => {
+ repaint()
+ await nextFrame()
+ await nextFrame()
+
+ const element = document.createElement("div")
+ const timeline = follow(
+ animateBox(
+ element,
+ { x: [0, 100] },
+ { ease: "linear", duration: 1 }
+ )
+ )
+ await nextFrame()
+ await nextFrame()
+
+ expect(onTimeline(element)).toHaveLength(1)
+ expect(timeline.observe).not.toHaveBeenCalled()
+ })
+
+ /**
+ * It was held on the main thread, and joined its timeline
+ * since. The end of the hold has nothing to move back.
+ */
+ it("isn't built again when the others stop, if it was held before it joined its timeline", async () => {
+ repaint()
+ await nextFrame()
+ await nextFrame()
+
+ const element = document.createElement("div")
+ const animations = animateBox(
+ element,
+ { x: [0, 100] },
+ { ease: "linear", duration: 1 }
+ )
+ await nextFrame()
+ await nextFrame()
+ expect(running(element)).toHaveLength(0)
+
+ follow(animations)
+ await nextFrame()
+ await nextFrame()
+ expect(onTimeline(element)).toHaveLength(1)
+
+ await wait(250)
+ await nextFrame()
+ await nextFrame()
+
+ expect(onTimeline(element)).toHaveLength(1)
+ expect(created(element)).toHaveLength(1)
+ })
+
+ it("stays on its timeline when it's a transform animated directly", async () => {
+ const element = document.createElement("div")
+ const timeline = follow(
+ animateBox(
+ element,
+ { transform: ["translateX(0px)", "translateX(100px)"] },
+ { ease: "linear", duration: 1 }
+ )
+ )
+ await nextFrame()
+ expect(onTimeline(element)).toHaveLength(1)
+
+ repaint()
+ await wait(50)
+ await nextFrame()
+
+ expect(onTimeline(element)).toHaveLength(1)
+ expect(timeline.observe).not.toHaveBeenCalled()
+
+ await wait(200)
+ await nextFrame()
+ await nextFrame()
+
+ expect(onTimeline(element)).toHaveLength(1)
+ expect(created(element)).toHaveLength(1)
+ })
+
+ it("joins its timeline when it's a transform animated directly while many other elements repaint", async () => {
+ repaint()
+ await nextFrame()
+ await nextFrame()
+
+ const element = document.createElement("div")
+ follow(
+ animateBox(
+ element,
+ { transform: ["translateX(0px)", "translateX(100px)"] },
+ { ease: "linear", duration: 1 }
+ )
+ )
+ await nextFrame()
+ await nextFrame()
+ expect(onTimeline(element)).toHaveLength(1)
+
+ await wait(250)
+ await nextFrame()
+ await nextFrame()
+
+ /**
+ * Once the others stop, it isn't started again on a
+ * clock.
+ */
+ expect(onTimeline(element)).toHaveLength(1)
+ expect(running(element)).toHaveLength(1)
+ })
+ })
+
+ /**
+ * Held transforms are remembered so they can return. One that
+ * ended is forgotten, with its element, however long the others
+ * keep repainting.
+ */
+ it("forget a held transform when its animation ends", async () => {
+ const element = document.createElement("div")
+ for (const painter of elements(repaintLimit)) {
+ animateBox(
+ painter,
+ { borderRadius: ["0px", "10px"] },
+ { duration: 0.3 }
+ )
+ }
+ await nextFrame()
+ await nextFrame()
+
+ const [x] = animateBox(element, { x: [0, 100] }, { duration: 2 })
+ await nextFrame()
+ await nextFrame()
+ expect(transforms(element)).toHaveLength(0)
+
+ const group = groups.transformGroups.get(element)!
+ const schedule = jest.spyOn(group, "schedule")
+ x.stop()
+ schedule.mockClear()
+
+ await wait(400)
+ await nextFrame()
+ await nextFrame()
+
+ expect(schedule).not.toHaveBeenCalled()
+ })
+
+ describe("with transform animated directly", () => {
+ const move = { transform: ["translateX(0px)", "translateX(100px)"] }
+
+ it("forgets one held on the main thread when it's stopped", async () => {
+ const element = document.createElement("div")
+ for (const painter of elements(repaintLimit)) {
+ animateBox(
+ painter,
+ { borderRadius: ["0px", "10px"] },
+ { duration: 0.3 }
+ )
+ }
+ await nextFrame()
+ await nextFrame()
+
+ const [track] = animateBox(element, move, {
+ duration: 2,
+ ease: "linear",
+ })
+ await nextFrame()
+ await nextFrame()
+ expect(transforms(element)).toHaveLength(0)
+
+ const schedule = jest.spyOn(track as any, "schedule")
+ track.stop()
+
+ await wait(400)
+ await nextFrame()
+ await nextFrame()
+
+ expect(schedule).not.toHaveBeenCalled()
+ })
+
+ it("forgets one held on the main thread when its whole animation is stopped", async () => {
+ const element = document.createElement("div")
+ for (const painter of elements(repaintLimit)) {
+ animateBox(
+ painter,
+ { borderRadius: ["0px", "10px"] },
+ { duration: 0.3 }
+ )
+ }
+ await nextFrame()
+ await nextFrame()
+
+ const [track] = animateBox(element, move, {
+ duration: 2,
+ ease: "linear",
+ })
+ await nextFrame()
+ await nextFrame()
+ expect(transforms(element)).toHaveLength(0)
+
+ const schedule = jest.spyOn(track as any, "schedule")
+ ;(track as any).parent.stop()
+
+ await wait(400)
+ await nextFrame()
+ await nextFrame()
+
+ expect(schedule).not.toHaveBeenCalled()
+ })
+
+ it("returns to the compositor where it was held at a speed of 0", async () => {
+ const boxes = elements(repaintLimit)
+ const tracks = boxes.map((element) =>
+ animateBox(
+ element,
+ { ...move, borderRadius: ["0px", "10px"] },
+ { duration: 10, ease: "linear" }
+ )
+ )
+ for (let i = 0; i < 3; i++) await nextFrame()
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+
+ await wait(200)
+ for (const [track] of tracks) track.speed = 0
+ const heldAt = tracks[0][0].time * 1000
+ expect(heldAt).toBeGreaterThan(150)
+
+ /**
+ * Nothing repaints now, so the transforms return.
+ */
+ for (const track of tracks.flat()) {
+ ;(track as any).name === "borderRadius" && track.stop()
+ }
+ for (let i = 0; i < 4; i++) await nextFrame()
+
+ const [waapi] = transforms(boxes[0])
+ expect(waapi).toBeDefined()
+ expect(waapi.playbackRate).toBe(0)
+ expect(Math.abs(waapi.currentTime! - heldAt)).toBeLessThan(20)
+ })
+
+ it("runs on the main thread for many elements", async () => {
+ const boxes = elements(repaintLimit)
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ { ...move, borderRadius: ["0px", "10px"] },
+ { duration: 1, ease: "linear" }
+ )
+ }
+ await nextFrame()
+ await nextFrame()
+ const first = boxes[0].style.transform
+ await wait(50)
+ await nextFrame()
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+ expect(readX(boxes[0].style.transform)).toBeGreaterThan(
+ readX(first)
+ )
+ })
+
+ it("stays on the compositor for a few elements", async () => {
+ const boxes = elements(repaintLimit - 1)
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ { ...move, borderRadius: ["0px", "10px"] },
+ { duration: 1, ease: "linear" }
+ )
+ }
+ await wait(50)
+ await nextFrame()
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(1)
+ }
+ })
+
+ /**
+ * Layers of earlier tests' animations end a few frames after
+ * they're stopped.
+ */
+ const settledLayers = async () => {
+ let count = -1
+ for (let same = 0; same < 6; same++) {
+ await nextFrame()
+ if (count !== groups.compositorLayers) same = 0
+ count = groups.compositorLayers
+ }
+ return count
+ }
+
+ it("counts as a compositor layer, for the layout layer budget, while WAAPI runs it", async () => {
+ const before = await settledLayers()
+ const boxes = elements(3)
+
+ for (const element of boxes) {
+ animateBox(element, move, { duration: 0.2, ease: "linear" })
+ }
+ await nextFrame()
+ expect(groups.compositorLayers).toBe(before + 3)
+
+ started[0].stop()
+ expect(groups.compositorLayers).toBe(before + 2)
+
+ await wait(300)
+ await nextFrame()
+ expect(groups.compositorLayers).toBe(before)
+ })
+
+ it("doesn't count while it's held on the main thread", async () => {
+ const before = await settledLayers()
+ const boxes = elements(repaintLimit)
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ { ...move, borderRadius: ["0px", "10px"] },
+ { duration: 1, ease: "linear" }
+ )
+ }
+ await nextFrame()
+ await nextFrame()
+
+ /**
+ * Other tests' layers are held too, so there may be fewer.
+ */
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+ expect(groups.compositorLayers).toBeLessThanOrEqual(before)
+ })
+
+ const held = async () => {
+ const boxes = elements(repaintLimit)
+ const tracks = boxes.map((element) =>
+ animateBox(
+ element,
+ { ...move, borderRadius: ["0px", "10px"] },
+ { duration: 10, ease: "linear" }
+ )
+ )
+ await nextFrame()
+ await nextFrame()
+ await nextFrame()
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+ return { boxes, tracks }
+ }
+
+ it("stays stopped when its animation was stopped on the main thread", async () => {
+ const { boxes, tracks } = await held()
+
+ for (const [track] of tracks) (track as any).parent.stop()
+ for (let i = 0; i < 4; i++) await nextFrame()
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+ })
+
+ it("leaves no layer when its animation was cancelled on the main thread", async () => {
+ const before = await settledLayers()
+ const { boxes, tracks } = await held()
+
+ for (const [track] of tracks) (track as any).parent.cancel()
+ for (let i = 0; i < 4; i++) await nextFrame()
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+ expect(await settledLayers()).toBe(before)
+ })
+
+ it("returns to the compositor at the speed set on the main thread", async () => {
+ const { boxes, tracks } = await held()
+
+ for (const [track] of tracks) (track as any).parent.speed = 2
+ for (const track of tracks.flat()) {
+ ;(track as any).name === "borderRadius" && track.stop()
+ }
+ for (let i = 0; i < 4; i++) await nextFrame()
+
+ for (const element of boxes) {
+ const [waapi] = transforms(element)
+ expect(waapi.playbackRate).toBe(2)
+ }
+ })
+
+ it("returns to the compositor when fewer elements than the limit still repaint", async () => {
+ groups.layerLimits.touch = repaintLimit + 1
+ const [mover] = elements(1)
+ animateBox(mover, move, { duration: 10, ease: "linear" })
+ const painters = elements(repaintLimit + 2).map((element) =>
+ animateBox(
+ element,
+ { borderRadius: ["0px", "10px"] },
+ { duration: 10, ease: "linear" }
+ )
+ )
+ for (let i = 0; i < 4; i++) await nextFrame()
+ expect(transforms(mover)).toHaveLength(0)
+
+ painters[0][0].stop()
+ painters[1][0].stop()
+ for (let i = 0; i < 6; i++) await nextFrame()
+
+ expect(transforms(mover)).toHaveLength(1)
+ })
+
+ it("moves to the main thread when many elements start to repaint, and back when they stop", async () => {
+ const boxes = elements(repaintLimit)
+
+ for (const element of boxes) {
+ animateBox(element, move, { duration: 2, ease: "linear" })
+ }
+ await nextFrame()
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(1)
+ }
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ { borderRadius: ["0px", "10px"] },
+ { duration: 0.1 }
+ )
+ }
+ await wait(50)
+ await nextFrame()
+ const first = readX(boxes[0].style.transform)
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+ expect(first).toBeGreaterThan(0)
+
+ await wait(200)
+ await nextFrame()
+ await nextFrame()
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(1)
+ }
+ })
+ })
+
+ describe("while the main thread is slow", () => {
+ /**
+ * Another script blocks the main thread for longer than a
+ * frame lasts, between Motion's frames.
+ */
+ let isBlocking = false
+ let timer: ReturnType
+
+ beforeEach(() => {
+ measureThread()
+ isBlocking = true
+ timer = setInterval(() => {
+ if (!isBlocking) return
+ const end = performance.now() + 30
+ while (performance.now() < end);
+ }, 1)
+ })
+
+ afterEach(() => clearInterval(timer))
+
+ const frames = async (count: number) => {
+ for (let i = 0; i < count; i++) await nextFrame()
+ }
+
+ it("move back to the compositor, which keeps them smooth", async () => {
+ const boxes = elements(repaintLimit)
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ { x: [0, 100], borderRadius: ["0px", "10px"] },
+ { duration: 4, ease: "linear" }
+ )
+ }
+ await frames(40)
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(1)
+ }
+ })
+
+ it("move a transform animated directly back to the compositor", async () => {
+ const boxes = elements(repaintLimit)
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ {
+ transform: ["translateX(0px)", "translateX(100px)"],
+ borderRadius: ["0px", "10px"],
+ },
+ { duration: 4, ease: "linear" }
+ )
+ }
+ await frames(40)
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(1)
+ }
+ })
+
+ it("stay on the main thread when their own frames are what's slow", async () => {
+ isBlocking = false
+
+ /**
+ * Other scripts count from a quarter of the frame's own
+ * work. Frames this slow keep that above how late a
+ * timer runs on a machine that's busy with other suites.
+ */
+ const slow = () => {
+ const end = performance.now() + 80
+ while (performance.now() < end);
+ }
+ frame.update(slow, true)
+ const boxes = elements(repaintLimit)
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ { x: [0, 100], borderRadius: ["0px", "10px"] },
+ { duration: 6, ease: "linear" }
+ )
+ }
+ await frames(30)
+ cancelFrame(slow)
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+ }, 15000)
+
+ const overLimit = async (
+ isTouch: boolean,
+ count = groups.layerLimits.computer + 1
+ ) => {
+ media.matches = isTouch
+ const boxes = elements(count)
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ { x: [0, 100], borderRadius: ["0px", "10px"] },
+ { duration: 6, ease: "linear" }
+ )
+ }
+ await frames(40)
+
+ return [boxes[0], boxes[boxes.length - 1]].map(
+ (element) => transforms(element).length
+ )
+ }
+
+ it("move to the compositor when more elements than the compositor limit move without touch", async () => {
+ expect(await overLimit(false)).toEqual([1, 1])
+ }, 30000)
+
+ it("stay on the main thread when more elements than the compositor limit move on a touch device", async () => {
+ /**
+ * A phone can't draw this many layers at the display's
+ * rate, blocked main thread or not.
+ */
+ expect(await overLimit(true)).toEqual([0, 0])
+ })
+
+ it("move to the compositor on a touch device past its compositor's limit when blocked for longer than a frame", async () => {
+ expect(
+ await overLimit(true, groups.layerLimits.max + 1)
+ ).toEqual([1, 1])
+ })
+
+ it("stay on the compositor on a computer with few enough elements", async () => {
+ isBlocking = false
+ media.matches = false
+ const boxes = elements(repaintLimit)
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ { x: [0, 100], borderRadius: ["0px", "10px"] },
+ { duration: 6, ease: "linear" }
+ )
+ }
+ await frames(40)
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(1)
+ }
+ })
+
+ it("stay on the compositor on a touch device with few enough elements", async () => {
+ isBlocking = false
+ groups.layerLimits.touch = touchLimit
+ const boxes = elements(repaintLimit)
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ { x: [0, 100], borderRadius: ["0px", "10px"] },
+ { duration: 6, ease: "linear" }
+ )
+ }
+ await frames(40)
+ groups.layerLimits.touch = 0
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(1)
+ }
+ })
+
+ it("elements that only move stay on the compositor while few enough others repaint", async () => {
+ isBlocking = false
+ groups.layerLimits.touch = touchLimit
+ const painters = elements(repaintLimit)
+ const movers = elements(touchLimit + 1)
+
+ for (const element of painters) {
+ animateBox(
+ element,
+ { borderRadius: ["0px", "10px"] },
+ { duration: 6, ease: "linear" }
+ )
+ }
+ for (const element of movers) {
+ animateBox(
+ element,
+ { x: [0, 100] },
+ { duration: 6, ease: "linear" }
+ )
+ }
+ await frames(40)
+ groups.layerLimits.touch = 0
+
+ expect(transforms(movers[0])).toHaveLength(1)
+ expect(transforms(movers[movers.length - 1])).toHaveLength(1)
+ })
+
+ it("run on the main thread on a computer past the compositor limit", async () => {
+ isBlocking = false
+ expect(await overLimit(false)).toEqual([0, 0])
+ })
+
+ it("return to the main thread once it has time again", async () => {
+ const boxes = elements(repaintLimit)
+
+ for (const element of boxes) {
+ animateBox(
+ element,
+ { x: [0, 100], borderRadius: ["0px", "10px"] },
+ { duration: 6, ease: "linear" }
+ )
+ }
+ await frames(40)
+ expect(transforms(boxes[0])).toHaveLength(1)
+
+ /**
+ * Nothing blocks from here, so the timer is held again:
+ * a machine busy with other suites runs it late, which
+ * reads as other scripts.
+ */
+ isBlocking = false
+ freeThread()
+ await frames(120)
+
+ for (const element of boxes) {
+ expect(transforms(element)).toHaveLength(0)
+ }
+ })
+ })
+
it("stay on the compositor with other composited values", async () => {
const element = document.createElement("div")
diff --git a/packages/motion-dom/src/animation/waapi/transforms/__tests__/group-without-playback.test.ts b/packages/motion-dom/src/animation/waapi/transforms/__tests__/group-without-playback.test.ts
new file mode 100644
index 0000000000..24e5314cf5
--- /dev/null
+++ b/packages/motion-dom/src/animation/waapi/transforms/__tests__/group-without-playback.test.ts
@@ -0,0 +1,231 @@
+import { frame } from "../../../../frameloop"
+import { HTMLVisualElement } from "../../../../render/html/HTMLVisualElement"
+import { supportsFlags } from "../../../../utils/supports/flags"
+import { animateVisualElement } from "../../../interfaces/visual-element"
+import { ValueTrack } from "../../../MultiValueAnimation"
+import { supportPlayback } from "../../../playback"
+import { groupSupport } from "../TransformAnimation"
+
+/**
+ * A component animates with animateVisualElement(), which hands out no
+ * controls, so nothing here gives animations their playback controls
+ * until the last test does. Its transforms still run as one WAAPI
+ * animation per element.
+ *
+ * JSDOM has no WAAPI, so record the animations made with the Animation
+ * and KeyframeEffect constructors.
+ */
+interface MockAnimation {
+ element: Element
+ keyframes: { transform?: string[]; opacity?: number[] } | null
+ options: KeyframeAnimationOptions
+ startTime: number | null
+ currentTime: number | null
+ playbackRate: number
+ playState: string
+ onfinish: (() => void) | null
+ oncancel: (() => void) | null
+ cancel: jest.Mock
+}
+
+let animations: MockAnimation[] = []
+
+const createAnimation = (
+ element: Element,
+ keyframes: MockAnimation["keyframes"],
+ options: any
+) => {
+ const animation: MockAnimation = {
+ element,
+ keyframes,
+ options,
+ startTime: null,
+ currentTime: null,
+ playbackRate: 1,
+ playState: "running",
+ onfinish: null,
+ oncancel: null,
+ cancel: jest.fn(),
+ }
+ animations.push(animation)
+ return animation
+}
+
+const running = (element: Element) =>
+ animations.filter(
+ (animation) =>
+ animation.element === element &&
+ animation.keyframes &&
+ !animation.cancel.mock.calls.length
+ )
+
+const nextFrame = () =>
+ new Promise((resolve) => frame.postRender(() => resolve()))
+
+const mount = () => {
+ const element = document.createElement("div")
+ const visualElement = new HTMLVisualElement({
+ props: {},
+ presenceContext: null,
+ visualState: {
+ latestValues: {},
+ renderState: {
+ transform: {},
+ transformOrigin: {},
+ style: {},
+ vars: {},
+ },
+ },
+ } as any)
+ visualElement.mount(element)
+ return { element, visualElement }
+}
+
+beforeAll(() => {
+ supportsFlags.linearEasing = true
+
+ Object.defineProperty(Element.prototype, "animate", {
+ configurable: true,
+ writable: true,
+ value(this: Element, keyframes: any, options: any) {
+ return createAnimation(this, keyframes, options)
+ },
+ })
+
+ const global = globalThis as any
+ global.KeyframeEffect = class {
+ constructor(
+ public target: Element,
+ public keyframes: MockAnimation["keyframes"],
+ public options: any
+ ) {}
+ }
+ global.Animation = class {
+ constructor(effect: any) {
+ return createAnimation(
+ effect.target,
+ effect.keyframes,
+ effect.options
+ )
+ }
+ }
+})
+
+afterAll(() => {
+ supportsFlags.linearEasing = undefined
+ delete (Element.prototype as any).animate
+ delete (globalThis as any).KeyframeEffect
+ delete (globalThis as any).Animation
+})
+
+beforeEach(() => {
+ animations = []
+})
+
+describe("transform groups of animations without playback controls", () => {
+ it("has no playback controls until code that hands them out asks", () => {
+ expect(groupSupport.retime).toBeUndefined()
+ expect("pause" in ValueTrack.prototype).toBe(false)
+ expect("time" in ValueTrack.prototype).toBe(false)
+ })
+
+ it("composes a component's transforms into one WAAPI animation", async () => {
+ const { element, visualElement } = mount()
+
+ animateVisualElement(visualElement, {
+ x: 100,
+ scale: 2,
+ transition: { duration: 1, ease: "linear" },
+ })
+ await nextFrame()
+
+ expect(running(element)).toHaveLength(1)
+ const { transform } = running(element)[0].keyframes!
+ expect(transform![transform!.length - 1]).toBe(
+ "translateX(100px) scale(2) "
+ )
+ })
+
+ it("rebuilds the WAAPI animation when another transform joins it", async () => {
+ const { element, visualElement } = mount()
+
+ animateVisualElement(visualElement, {
+ x: 100,
+ transition: { duration: 1, ease: "linear" },
+ })
+ await nextFrame()
+
+ expect(running(element)).toHaveLength(1)
+ const [first] = running(element)
+ expect(first.keyframes!.transform!.join()).not.toContain("rotate")
+
+ animateVisualElement(visualElement, {
+ rotate: 90,
+ transition: { duration: 1, ease: "linear" },
+ })
+ await nextFrame()
+
+ /**
+ * One WAAPI animation, with both transforms, until the first of
+ * them ends. The first WAAPI animation is cancelled, not left
+ * running under it.
+ */
+ expect(first.cancel).toHaveBeenCalled()
+ expect(running(element)).toHaveLength(1)
+ const { transform } = running(element)[0].keyframes!
+ expect(transform![transform!.length - 1]).toMatch(
+ /^translateX\(100px\) rotate\([\d.]+deg\) $/
+ )
+ })
+
+ it("writes the final transform when the animation finishes", async () => {
+ const { element, visualElement } = mount()
+
+ const finished = animateVisualElement(visualElement, {
+ x: 100,
+ transition: { duration: 0.05, ease: "linear" },
+ })
+ await nextFrame()
+ expect(running(element)).toHaveLength(1)
+
+ /**
+ * WAAPI finishes the animation.
+ */
+ await new Promise((resolve) => setTimeout(resolve, 80))
+ running(element)[0]?.onfinish?.()
+ await finished
+
+ expect(running(element)).toHaveLength(0)
+ expect(element.style.transform).toBe("translateX(100px)")
+ })
+
+ it("gives animations that are already running their controls", async () => {
+ const { element, visualElement } = mount()
+
+ animateVisualElement(visualElement, {
+ x: 100,
+ transition: { duration: 1, ease: "linear" },
+ })
+ await nextFrame()
+
+ const animation = visualElement.getValue("x")!.animation as any
+ expect(animation.pause).toBeUndefined()
+
+ supportPlayback()
+
+ expect(groupSupport.retime).toBeDefined()
+ expect(running(element)).toHaveLength(1)
+ const [native] = running(element)
+ native.startTime = performance.now()
+
+ animation.pause()
+ await nextFrame()
+
+ /**
+ * The same WAAPI animation, held where it is.
+ */
+ expect(animation.state).toBe("paused")
+ expect(running(element)).toEqual([native])
+ expect(native.startTime).toBe(null)
+ })
+})
diff --git a/packages/motion-dom/src/animation/waapi/transforms/groups.ts b/packages/motion-dom/src/animation/waapi/transforms/groups.ts
index bbc1590ec7..1ae06364fa 100644
--- a/packages/motion-dom/src/animation/waapi/transforms/groups.ts
+++ b/packages/motion-dom/src/animation/waapi/transforms/groups.ts
@@ -1,4 +1,4 @@
-import { frame } from "../../../frameloop"
+import { frame, frameData } from "../../../frameloop"
import type { MotionValue } from "../../../value"
/**
@@ -29,30 +29,47 @@ export interface TransformGroupHooks {
schedule(needsBuild: boolean): void
/**
- * A style animating on the main thread repaints the element this
- * frame. A hook so a renderer can count it without the frame loop.
+ * Whether it's on a native scroll timeline. Only the compositor moves
+ * it with the scroll, so it's never held on the main thread.
*/
- repaint(value: MotionValue): void
+ isScrolling?: boolean
}
export const transformGroups = new WeakMap