From 0d5abbc4cd24047e0ba2e51cab85e453f88db99f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:20:42 +0000 Subject: [PATCH 01/17] Keep drag code out of Reorder's first load Reorder.Board looks up an element's drag controls in a map that was declared in the file of the class that makes them. A bundler keeps a module whole, so the class, PanSession and the projection geometry they use were in the first chunk of every page with Reorder. The map now has its own file. First load with Reorder: 42.96 kB to 38.49 kB gzip. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- .../drag/VisualElementDragControls.ts | 6 +---- .../src/gestures/drag/state/controls.ts | 15 ++++++++++++ .../motion-dom/src/gestures/pinch/index.ts | 2 +- packages/motion-dom/src/index.ts | 1 + .../src/__tests__/first-load-chunk.test.ts | 24 +++++++++++++++++++ 5 files changed, 42 insertions(+), 6 deletions(-) create mode 100644 packages/motion-dom/src/gestures/drag/state/controls.ts diff --git a/packages/motion-dom/src/gestures/drag/VisualElementDragControls.ts b/packages/motion-dom/src/gestures/drag/VisualElementDragControls.ts index 7497af1125..ab66d1b40a 100644 --- a/packages/motion-dom/src/gestures/drag/VisualElementDragControls.ts +++ b/packages/motion-dom/src/gestures/drag/VisualElementDragControls.ts @@ -27,6 +27,7 @@ import { addValueToWillChange } from "../../value/will-change/add-will-change" import type { PanInfo } from "../pan/types" import { PanSession } from "../pan/PanSession" import { isElementTextInput } from "../press/utils/is-text-input" +import { elementDragControls } from "./state/controls" import { setDragLock } from "./state/set-active" import type { DragPointConstraint, ResolvedConstraints } from "./types" import { @@ -61,11 +62,6 @@ function measureScroll(projection: IProjectionNode) { return key } -export const elementDragControls = new WeakMap< - VisualElement, - VisualElementDragControls ->() - export interface DragControlOptions { /** * This distance after which dragging starts and a direction is locked in. diff --git a/packages/motion-dom/src/gestures/drag/state/controls.ts b/packages/motion-dom/src/gestures/drag/state/controls.ts new file mode 100644 index 0000000000..6bb10130b9 --- /dev/null +++ b/packages/motion-dom/src/gestures/drag/state/controls.ts @@ -0,0 +1,15 @@ +import type { VisualElement } from "../../../render/VisualElement" +import type { VisualElementDragControls } from "../VisualElementDragControls" + +/** + * The drag controls of each element that has them. + * + * This has its own file so code that only looks controls up, like + * Reorder.Board, doesn't share a module with the class that makes them. + * A bundler keeps a module whole, so it would put the class in the same + * chunk. + */ +export const elementDragControls = /* @__PURE__ */ new WeakMap< + VisualElement, + VisualElementDragControls +>() diff --git a/packages/motion-dom/src/gestures/pinch/index.ts b/packages/motion-dom/src/gestures/pinch/index.ts index f82ae5ea6a..2a069997ca 100644 --- a/packages/motion-dom/src/gestures/pinch/index.ts +++ b/packages/motion-dom/src/gestures/pinch/index.ts @@ -17,7 +17,7 @@ import { import type { MotionValue } from "../../value" import { setDragLock } from "../drag/state/set-active" import { applyConstraints, defaultElastic } from "../drag/utils/constraints" -import { elementDragControls } from "../drag/VisualElementDragControls" +import { elementDragControls } from "../drag/state/controls" /** * @public diff --git a/packages/motion-dom/src/index.ts b/packages/motion-dom/src/index.ts index deaf134a40..d826948d4b 100644 --- a/packages/motion-dom/src/index.ts +++ b/packages/motion-dom/src/index.ts @@ -95,6 +95,7 @@ export { } from "./layout/LayoutAnimationBuilder" export * from "./gestures/drag" export { createDragMeasureNode } from "./gestures/drag/measure-node" +export * from "./gestures/drag/state/controls" export * from "./gestures/drag/state/is-active" export * from "./gestures/drag/state/set-active" export * from "./gestures/drag/types" diff --git a/packages/motion/src/__tests__/first-load-chunk.test.ts b/packages/motion/src/__tests__/first-load-chunk.test.ts index 24e3f78b5d..d5d802e04a 100644 --- a/packages/motion/src/__tests__/first-load-chunk.test.ts +++ b/packages/motion/src/__tests__/first-load-chunk.test.ts @@ -17,6 +17,12 @@ jest.setTimeout(60000) const lazyOnly = /create-projection-node|projection\/(geometry\/delta-|animation\/)|VisualElementDragControls|gestures\/pan\/|components\/Reorder\// +/** + * The same, for a first load that has Reorder's own files. + */ +const fetchedOnly = + /create-projection-node|projection\/(geometry\/delta-|animation\/)|VisualElementDragControls|gestures\/pan\// + async function firstLoadModules(code: string) { const bundle = await rollup({ input: "entry", @@ -68,6 +74,24 @@ describe("motion first load", () => { expect(modules.filter((id) => lazyOnly.test(id))).toEqual([]) }) + /** + * Reorder renders motion components that fetch drag and layout, so its + * own files must not share a module with the code they fetch. A map of + * drag controls kept in the file of the class that makes them once put + * the class in every first load with Reorder.Board. + */ + test("Reorder has no drag or projection modules", async () => { + const { modules, chunkCount } = await firstLoadModules( + `export { Reorder } from "motion/react"` + ) + + expect(chunkCount).toBeGreaterThan(1) + expect(modules.some((id) => /components\/Reorder\//.test(id))).toBe( + true + ) + expect(modules.filter((id) => fetchedOnly.test(id))).toEqual([]) + }) + /** * webpack keeps a whole namespace object when a module copies one of its * members into a local binding, such as `const motion = ns.motion`. With From 1e2600b3c21004297fb54337776451b167bd7c3f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:36:06 +0000 Subject: [PATCH 02/17] Keep layout measuring logic out of the first load A component that fetches the layout feature rendered all of MeasureLayout from its first render, so the code that drives a projection node sat in the first chunk. It now renders a shell with no logic of its own: each lifecycle method runs the method of the same name that arrives with the feature. Components that bundle their features are unchanged. Also fixes an exit that never finished. An async component with layout whose feature had not arrived, or with only drag, told AnimatePresence it could be removed before AnimatePresence had noted it as exiting, so the call was lost and the element stayed in the DOM. motion.div first load 34.08 -> 33.64 kB gzip. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- .../async-features-shell-bundled.test.tsx | 53 +++++++ .../__tests__/async-features-shell.test.tsx | 130 ++++++++++++++++++ .../src/motion/features/layout-fetched.ts | 15 ++ .../src/motion/features/layout.ts | 6 +- .../motion/features/layout/MeasureLayout.tsx | 29 ++-- .../features/layout/MeasureLayoutShell.tsx | 99 +++++++++++++ .../src/motion/features/types.ts | 14 +- .../src/motion/features/use-async-features.ts | 8 +- packages/framer-motion/src/motion/index.tsx | 29 +++- .../src/render/components/create-proxy.ts | 9 +- .../render/components/motion-async/loaders.ts | 4 +- .../render/components/motion-async/proxy.ts | 12 +- packages/motion-dom/src/render/types.ts | 6 + .../src/__tests__/first-load-chunk.test.ts | 23 +++- 14 files changed, 399 insertions(+), 38 deletions(-) create mode 100644 packages/framer-motion/src/motion/__tests__/async-features-shell-bundled.test.tsx create mode 100644 packages/framer-motion/src/motion/__tests__/async-features-shell.test.tsx create mode 100644 packages/framer-motion/src/motion/features/layout-fetched.ts create mode 100644 packages/framer-motion/src/motion/features/layout/MeasureLayoutShell.tsx 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/layout-fetched.ts b/packages/framer-motion/src/motion/features/layout-fetched.ts new file mode 100644 index 0000000000..40719be49f --- /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.prototype, + }, +} diff --git a/packages/framer-motion/src/motion/features/layout.ts b/packages/framer-motion/src/motion/features/layout.ts index 00e7da75e1..9938c7cc8d 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.prototype, }, } 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..97b08471ff --- /dev/null +++ b/packages/framer-motion/src/motion/features/layout/MeasureLayoutShell.tsx @@ -0,0 +1,99 @@ +"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. + */ +const getLifecycle = () => getFeatureDefinitions().layout?.lifecycle + +/** + * 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..ffccf8261e 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 methods that drive a projection node from React's commit, for + * the MeasureLayoutShell of components that mounted before the layout + * feature arrived. + */ + lifecycle?: 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..0f137dfdc9 100644 --- a/packages/framer-motion/src/motion/index.tsx +++ b/packages/framer-motion/src/motion/index.tsx @@ -1,6 +1,10 @@ "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" @@ -62,6 +66,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 +92,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 +164,12 @@ 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. */ - useFeatures?.(configAndProps, context) + const FetchedMeasureLayout = useFeatures?.(configAndProps, context) const layoutProjection = getProjectionFunctionality(configAndProps) @@ -182,7 +196,8 @@ export function createMotionComponent< layoutProjection.isEnabled || context.visualElement?.projection?.options.layoutId ) - MeasureLayout = layoutProjection.MeasureLayout + MeasureLayout = + 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..8f2a228845 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,5 @@ import { animations } from "../../../motion/features/animations" import { gestureAnimations } from "../../../motion/features/gestures" -import { MeasureLayout } from "../../../motion/features/layout/MeasureLayout" import { preloadFeatures as preload, useAsyncFeatures, @@ -15,14 +14,13 @@ 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 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. */ export const motion = /*@__PURE__*/ createMotionProxy( - /*@__PURE__*/ Object.assign({}, animations, gestureAnimations, { - layout: { MeasureLayout }, - }), + /*@__PURE__*/ Object.assign({}, animations, gestureAnimations), createDomVisualElement, (props: MotionProps, context: MotionContextProps) => useAsyncFeatures(props, context, featureLoaders) diff --git a/packages/motion-dom/src/render/types.ts b/packages/motion-dom/src/render/types.ts index a5ef12db8b..e287dd80d9 100644 --- a/packages/motion-dom/src/render/types.ts +++ b/packages/motion-dom/src/render/types.ts @@ -174,6 +174,12 @@ export interface FeatureDefinition { Feature?: FeatureClass ProjectionNode?: any MeasureLayout?: any + + /** + * The methods that drive a projection node from a framework's commit, + * for components that mounted before the layout feature arrived. + */ + lifecycle?: any } export type FeatureDefinitions = { diff --git a/packages/motion/src/__tests__/first-load-chunk.test.ts b/packages/motion/src/__tests__/first-load-chunk.test.ts index d5d802e04a..f7e2fcf582 100644 --- a/packages/motion/src/__tests__/first-load-chunk.test.ts +++ b/packages/motion/src/__tests__/first-load-chunk.test.ts @@ -52,14 +52,16 @@ async function firstLoadModules(code: string) { walk(output.find((chunk: any) => chunk.isEntry)!.fileName) const modules: string[] = [] + let firstCode = "" for (const fileName of first) { + firstCode += chunks[fileName].code for (const [id, info] of Object.entries( chunks[fileName].modules )) { info.renderedLength && modules.push(id) } } - return { modules, chunkCount: output.length } + return { modules, code: firstCode, chunkCount: output.length } } describe("motion first load", () => { @@ -74,6 +76,25 @@ describe("motion first load", () => { expect(modules.filter((id) => lazyOnly.test(id))).toEqual([]) }) + /** + * The React side of layout animations is in the first load, so a + * component takes part in a layout change without rendering again once + * the projection code arrives. What it does with a projection node can + * only run once there is one, so that arrives with the node. + */ + test("has no code that drives a projection node", async () => { + const { code } = await firstLoadModules( + `import { motion } from "motion/react"; export const D = motion.div` + ) + + expect(code).toMatch(/getSnapshotBeforeUpdate/) + expect( + code.match( + /\b(willUpdate|registerSharedNode|relegate|promote|scheduleCheckAfterUnmount)\(/g + ) + ).toBeNull() + }) + /** * Reorder renders motion components that fetch drag and layout, so its * own files must not share a module with the code they fetch. A map of From 4a6fb217c04b4578ccd745c1096edbfc5c82eb11 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:49:33 +0000 Subject: [PATCH 03/17] Load the exit feature with AnimatePresence An exit animation only runs for a component that something keeps mounted after React would remove it. Components that fetch their features no longer bundle the exit feature: PresenceChild loads it for every motion component when it first renders. The PresenceContext that apps import loads it too, for a component that provides the context in place of AnimatePresence. Components that bundle their features, and the LazyMotion feature bundles, still include it. The feature now registers with its presence once the component has an animation state, so a component with the exit feature and no animation feature doesn't hold up its presence. The layout feature holds the MeasureLayout class and not its prototype. Reading the prototype as the module loaded stopped a bundler dropping the feature from a flattened bundle that doesn't use it. motion.div first load 33.64 -> 33.45 kB gzip. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- .../AnimatePresence/PresenceChild.tsx | 8 +++ .../exit-without-animations.test.tsx | 39 +++++++++++++ .../src/components/AnimatePresence/context.ts | 16 +++++ packages/framer-motion/src/index.ts | 2 +- .../async-exit-presence-context.test.tsx | 58 +++++++++++++++++++ .../src/motion/features/animation/exit.ts | 24 +++++--- .../motion/features/animation/load-exit.ts | 17 ++++++ .../src/motion/features/layout-fetched.ts | 2 +- .../src/motion/features/layout.ts | 2 +- .../features/layout/MeasureLayoutShell.tsx | 6 +- .../src/motion/features/types.ts | 12 ++-- .../render/components/motion-async/proxy.ts | 10 +++- packages/motion-dom/src/render/types.ts | 2 +- .../src/__tests__/first-load-chunk.test.ts | 29 ++++++++++ 14 files changed, 206 insertions(+), 21 deletions(-) create mode 100644 packages/framer-motion/src/components/AnimatePresence/__tests__/exit-without-animations.test.tsx create mode 100644 packages/framer-motion/src/components/AnimatePresence/context.ts create mode 100644 packages/framer-motion/src/motion/__tests__/async-exit-presence-context.test.tsx create mode 100644 packages/framer-motion/src/motion/features/animation/load-exit.ts 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/features/animation/exit.ts b/packages/framer-motion/src/motion/features/animation/exit.ts index eec3af18f2..3548fc9437 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 index 40719be49f..41da9864f4 100644 --- a/packages/framer-motion/src/motion/features/layout-fetched.ts +++ b/packages/framer-motion/src/motion/features/layout-fetched.ts @@ -10,6 +10,6 @@ import { FeaturePackages } from "./types" export const layout: FeaturePackages = { layout: { ProjectionNode: HTMLProjectionNode, - lifecycle: MeasureLayoutWithContext.prototype, + Lifecycle: MeasureLayoutWithContext, }, } diff --git a/packages/framer-motion/src/motion/features/layout.ts b/packages/framer-motion/src/motion/features/layout.ts index 9938c7cc8d..d831398b25 100644 --- a/packages/framer-motion/src/motion/features/layout.ts +++ b/packages/framer-motion/src/motion/features/layout.ts @@ -9,6 +9,6 @@ export const layout: FeaturePackages = { layout: { ProjectionNode: HTMLProjectionNode, MeasureLayout, - lifecycle: MeasureLayoutWithContext.prototype, + Lifecycle: MeasureLayoutWithContext, }, } diff --git a/packages/framer-motion/src/motion/features/layout/MeasureLayoutShell.tsx b/packages/framer-motion/src/motion/features/layout/MeasureLayoutShell.tsx index 97b08471ff..d5f3d21778 100644 --- a/packages/framer-motion/src/motion/features/layout/MeasureLayoutShell.tsx +++ b/packages/framer-motion/src/motion/features/layout/MeasureLayoutShell.tsx @@ -16,9 +16,11 @@ 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. + * 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 +const getLifecycle = () => getFeatureDefinitions().layout?.Lifecycle?.prototype /** * The React side of layout animations for a component that fetches the diff --git a/packages/framer-motion/src/motion/features/types.ts b/packages/framer-motion/src/motion/features/types.ts index ffccf8261e..b1e7cf7ae3 100644 --- a/packages/framer-motion/src/motion/features/types.ts +++ b/packages/framer-motion/src/motion/features/types.ts @@ -17,11 +17,11 @@ export interface HydratedFeatureDefinition { MeasureLayout?: typeof MeasureLayout /** - * The methods that drive a projection node from React's commit, for - * the MeasureLayoutShell of components that mounted before the layout - * feature arrived. + * 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?: MeasureLayoutWithContext + Lifecycle?: typeof MeasureLayoutWithContext } export interface HydratedFeatureDefinitions { @@ -42,7 +42,7 @@ export interface FeatureDefinition { Feature?: HydratedFeatureDefinition["Feature"] ProjectionNode?: HydratedFeatureDefinition["ProjectionNode"] MeasureLayout?: HydratedFeatureDefinition["MeasureLayout"] - lifecycle?: HydratedFeatureDefinition["lifecycle"] + Lifecycle?: HydratedFeatureDefinition["Lifecycle"] } export type FeatureDefinitions = { @@ -58,7 +58,7 @@ export interface FeaturePackage { Feature?: HydratedFeatureDefinition["Feature"] ProjectionNode?: HydratedFeatureDefinition["ProjectionNode"] MeasureLayout?: HydratedFeatureDefinition["MeasureLayout"] - lifecycle?: HydratedFeatureDefinition["lifecycle"] + Lifecycle?: HydratedFeatureDefinition["Lifecycle"] } export type FeaturePackages = { 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 8f2a228845..b0e2f16d67 100644 --- a/packages/framer-motion/src/render/components/motion-async/proxy.ts +++ b/packages/framer-motion/src/render/components/motion-async/proxy.ts @@ -1,4 +1,4 @@ -import { animations } from "../../../motion/features/animations" +import { AnimationFeature } from "../../../motion/features/animation" import { gestureAnimations } from "../../../motion/features/gestures" import { preloadFeatures as preload, @@ -14,13 +14,19 @@ 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 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. */ export const motion = /*@__PURE__*/ createMotionProxy( - /*@__PURE__*/ Object.assign({}, animations, gestureAnimations), + /*@__PURE__*/ Object.assign( + { animation: { Feature: AnimationFeature } }, + gestureAnimations + ), createDomVisualElement, (props: MotionProps, context: MotionContextProps) => useAsyncFeatures(props, context, featureLoaders) diff --git a/packages/motion-dom/src/render/types.ts b/packages/motion-dom/src/render/types.ts index e287dd80d9..a4dced71e2 100644 --- a/packages/motion-dom/src/render/types.ts +++ b/packages/motion-dom/src/render/types.ts @@ -179,7 +179,7 @@ export interface FeatureDefinition { * The methods that drive a projection node from a framework's commit, * for components that mounted before the layout feature arrived. */ - lifecycle?: any + Lifecycle?: any } export type FeatureDefinitions = { diff --git a/packages/motion/src/__tests__/first-load-chunk.test.ts b/packages/motion/src/__tests__/first-load-chunk.test.ts index f7e2fcf582..3fa25a883c 100644 --- a/packages/motion/src/__tests__/first-load-chunk.test.ts +++ b/packages/motion/src/__tests__/first-load-chunk.test.ts @@ -95,6 +95,35 @@ describe("motion first load", () => { ).toBeNull() }) + /** + * An `exit` animation only runs for a component that something keeps + * mounted after React would remove it. So its feature arrives with + * AnimatePresence, or with PresenceContext for a component that stands + * in for AnimatePresence, not with every motion component. + */ + test("has the exit feature only with AnimatePresence or PresenceContext", async () => { + const hasExit = async (code: string) => + (await firstLoadModules(code)).modules.some((id) => + /features\/animation\/exit/.test(id) + ) + + expect( + await hasExit( + `import { motion } from "motion/react"; export const D = motion.div` + ) + ).toBe(false) + expect( + await hasExit( + `export { motion, AnimatePresence } from "motion/react"` + ) + ).toBe(true) + expect( + await hasExit( + `export { motion, PresenceContext } from "motion/react"` + ) + ).toBe(true) + }) + /** * Reorder renders motion components that fetch drag and layout, so its * own files must not share a module with the code they fetch. A map of From 45d02831bcaab14d9d287562e5d92208182fa86f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:55:20 +0000 Subject: [PATCH 04/17] Set size budgets for the combined branch The branch combines the async features beta with four open performance changes, each of which set its own budgets. Also measure the whole React API through a namespace import: with a fetched chunk that imports from the first load, Rollup emitted `export *` as a second file that repeats every export, which added 2.3 kB that no app pays. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- dev/inc/size-scenarios.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dev/inc/size-scenarios.mjs b/dev/inc/size-scenarios.mjs index 0fc558b651..f64013d0dd 100644 --- a/dev/inc/size-scenarios.mjs +++ b/dev/inc/size-scenarios.mjs @@ -95,7 +95,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"), From 6af75aff85df4c4ee40bb1881582dc85ac34b1c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:09:38 +0000 Subject: [PATCH 05/17] Point the async features spec at the fetched layout file Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- tests/react/async-features.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/react/async-features.spec.ts b/tests/react/async-features.spec.ts index 252db8a8b4..a4eab26f4a 100644 --- a/tests/react/async-features.spec.ts +++ b/tests/react/async-features.spec.ts @@ -10,7 +10,7 @@ import { expect, Page, test } from "@playwright/test" * The dev server marks the files Motion fetches itself, as a page that * imports all of Motion also loads them with the page. */ -const featureFile = /motion\/features\/(layout|drag-measure)\.mjs\?lazy/ +const featureFile = /motion\/features\/(layout-fetched|drag-measure)\.mjs\?lazy/ /** * Open a page with its feature files held until release() is called. @@ -208,7 +208,7 @@ for (const strict of ["", "&strict"]) { * The layout code arrives after the drag code, and gives the * element a node that projects. Its constraints still hold. */ - const layout = page.waitForResponse(/features\/layout\.mjs\?lazy/) + const layout = page.waitForResponse(/features\/layout-fetched\.mjs\?lazy/) await page.click("#add-layout") await layout await page.waitForTimeout(200) From f1136bea48566db4eeb14e911e84058615a7b1aa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:31:42 +0000 Subject: [PATCH 06/17] Add motion/react-sync for builds that write one file A bundler that can't fetch code later puts the layout and drag code that motion/react fetches into its one file. esbuild also wraps every module that code shares with the rest of the file in a lazy initialiser, for any import from motion/react. motion/react-sync has the same exports, with motion components that bundle their features, so there's nothing to fetch or wrap. In an esbuild bundle without splitting, motion.div is 50.96 kB gzip (55.09 from motion/react), and m with LazyMotion and domAnimation is 34.04 kB (36.33). The entry name is provisional. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- dev/inc/size-scenarios.mjs | 3 + packages/motion/.npmignore | 1 + packages/motion/package.json | 6 ++ packages/motion/react-sync/package.json | 6 ++ packages/motion/rollup.config.mjs | 13 ++++ .../src/__tests__/one-file-bundle.test.ts | 69 +++++++++++++++++++ packages/motion/src/react-sync.ts | 16 +++++ 7 files changed, 114 insertions(+) create mode 100644 packages/motion/react-sync/package.json create mode 100644 packages/motion/src/__tests__/one-file-bundle.test.ts create mode 100644 packages/motion/src/react-sync.ts diff --git a/dev/inc/size-scenarios.mjs b/dev/inc/size-scenarios.mjs index f64013d0dd..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"`, @@ -226,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/motion/.npmignore b/packages/motion/.npmignore index 9ff5051a1c..ff1f4da01b 100644 --- a/packages/motion/.npmignore +++ b/packages/motion/.npmignore @@ -7,5 +7,6 @@ !react/package.json !react-client/package.json !react-m/package.json +!react-sync/package.json !react-animate-view/package.json !remix/package.json \ No newline at end of file diff --git a/packages/motion/package.json b/packages/motion/package.json index d0f8436043..684fa66433 100644 --- a/packages/motion/package.json +++ b/packages/motion/package.json @@ -59,6 +59,12 @@ "import": "./dist/es/react-m.mjs", "default": "./dist/cjs/react-m.js" }, + "./react-sync": { + "types": "./dist/react-sync.d.ts", + "require": "./dist/cjs/react-sync.js", + "import": "./dist/es/react-sync.mjs", + "default": "./dist/cjs/react-sync.js" + }, "./react-mini": { "types": "./dist/react-mini.d.ts", "require": "./dist/cjs/react-mini.js", diff --git a/packages/motion/react-sync/package.json b/packages/motion/react-sync/package.json new file mode 100644 index 0000000000..fbc20656fa --- /dev/null +++ b/packages/motion/react-sync/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "types": "../dist/react-sync.d.ts", + "main": "../dist/cjs/react-sync.js", + "module": "../dist/es/react-sync.mjs" +} diff --git a/packages/motion/rollup.config.mjs b/packages/motion/rollup.config.mjs index 2d8fa768dd..96a15e1a2e 100644 --- a/packages/motion/rollup.config.mjs +++ b/packages/motion/rollup.config.mjs @@ -130,6 +130,7 @@ const cjsDebug = Object.assign({}, cjs, { input : "lib/debug.js" }) const cjsReactMini = Object.assign({}, cjs, { input : "lib/react-mini.js" }) const cjsClient = Object.assign({}, cjs, { input : "lib/react-client.js" }) const cjsM = Object.assign({}, cjs, { input : "lib/react-m.js" }) +const cjsSync = Object.assign({}, cjs, { input : "lib/react-sync.js" }) const cjsThree = Object.assign({}, cjs, { input : "lib/three.js" }) const cjsVgpu = Object.assign({}, cjs, { input : "lib/vgpu.js" }) const cjsRemix = Object.assign({}, cjs, { input : "lib/remix.js" }) @@ -143,6 +144,7 @@ export const es = Object.assign({}, config, { "lib/react-mini.js", "lib/react-client.js", "lib/react-m.js", + "lib/react-sync.js", "lib/debug.js", "lib/three.js", "lib/vgpu.js", @@ -218,6 +220,15 @@ const mTypes = { plugins: typePlugins, } +const syncTypes = { + input: "types/react-sync.d.ts", + output: { + format: "es", + file: "dist/react-sync.d.ts", + }, + plugins: typePlugins, +} + const reactMiniTypes = { input: "types/react-mini.d.ts", output: { @@ -274,6 +285,7 @@ export default [ cjsMini, cjsReactMini, cjsM, + cjsSync, cjsThree, cjsVgpu, cjsRemix, @@ -284,6 +296,7 @@ export default [ reactTypes, reactMiniTypes, mTypes, + syncTypes, miniTypes, clientTypes, threeTypes, diff --git a/packages/motion/src/__tests__/one-file-bundle.test.ts b/packages/motion/src/__tests__/one-file-bundle.test.ts new file mode 100644 index 0000000000..0906f0dc05 --- /dev/null +++ b/packages/motion/src/__tests__/one-file-bundle.test.ts @@ -0,0 +1,69 @@ +/** @jest-environment node */ +import { build } from "esbuild" +import { gzipSync } from "zlib" + +/** + * A bundler that writes one file can't fetch a feature later, so the code + * a `motion` component from `motion/react` would fetch goes in the file. + * esbuild also wraps every module that code shares with the rest of the + * file in a lazy initialiser, whatever the app imports from the entry. + * + * `motion/react-sync` is the same API with components that bundle their + * features, so a one-file build has nothing to fetch or wrap. + * + * Bundles the built packages through their package.json exports, so + * run `yarn build` first. + */ +jest.setTimeout(30000) + +async function oneFile(code: string, minify = true) { + const result = await build({ + stdin: { contents: code, resolveDir: __dirname, loader: "js" }, + bundle: true, + minify, + write: false, + metafile: true, + format: "esm", + platform: "browser", + external: ["react", "react-dom", "react/jsx-runtime"], + define: { "process.env.NODE_ENV": '"production"' }, + logLevel: "silent", + }) + return { + code: result.outputFiles[0].text, + exports: Object.values(result.metafile.outputs)[0].exports.sort(), + } +} + +const gzip = (code: string) => gzipSync(code).length + +describe("motion/react-sync in a one-file bundle", () => { + test.each([ + ["motion", `export const D = entry.motion.div`, 3000], + [ + "m with LazyMotion", + `export const D = [entry.m.div, entry.LazyMotion, entry.domAnimation]`, + 1500, + ], + ])("%s has no lazy module wrappers, and is smaller", async (_, use, saving) => { + const code = (entry: string) => `import * as entry from "${entry}"; ${use}` + + const wrapped = /__esm\(/ + expect((await oneFile(code("motion/react"), false)).code).toMatch(wrapped) + expect( + (await oneFile(code("motion/react-sync"), false)).code + ).not.toMatch(wrapped) + + const fetched = await oneFile(code("motion/react")) + const sync = await oneFile(code("motion/react-sync")) + expect(gzip(fetched.code) - gzip(sync.code)).toBeGreaterThan(saving) + }) + + test("has every export of motion/react", async () => { + const all = (entry: string) => oneFile(`export * from "${entry}"`) + + expect((await all("motion/react-sync")).exports).toEqual( + (await all("motion/react")).exports + ) + }) +}) diff --git a/packages/motion/src/react-sync.ts b/packages/motion/src/react-sync.ts new file mode 100644 index 0000000000..e78ede2233 --- /dev/null +++ b/packages/motion/src/react-sync.ts @@ -0,0 +1,16 @@ +/** + * `motion/react`, with `motion` components that bundle all their features + * and fetch nothing. + * + * It's for a build that can't fetch code later, like one that writes a + * single file. There, the layout and drag code `motion/react` would fetch + * goes in the file anyway, and esbuild wraps each module that code shares + * with the rest of the file in a lazy initialiser. + */ +export * from "framer-motion" + +/** + * There's nothing to fetch. Here so code written for `motion/react` runs + * with either entry. + */ +export const preloadFeatures = () => Promise.resolve([] as void[]) From 228be6dd91cc17662cc48335287b5926c44ae098 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 19:52:27 +0000 Subject: [PATCH 07/17] Keep playback controls out of bundles that hand out none A component starts animations and hands out no controls for them, so the code to pause, seek, change the speed of and attach a timeline to an animation doesn't need to be in a bundle with only components. supportPlayback() adds those controls to the shared animation classes. It's called by the code that gives an animation to its caller: animate(), animateValue(), animateSingleValue(), layout animations, timelines, and the animateTarget() and animateMotionValue() exports. The transform group's retiming of a running WAAPI animation moves with them. An inspector behind __MOTION_INSPECT__ controls the animations of components too. It gets the controls on development builds. motion.div first load: 33.45 kB to 32.57 kB gzip. animate(): +0.07 kB. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- .../src/animation/timeline/index.ts | 2 + .../motion-dom/src/animation/JSAnimation.ts | 2 + .../src/animation/MultiValueAnimation.ts | 255 ++++-------------- .../src/animation/__tests__/playback.test.ts | 203 ++++++++++++++ .../src/animation/animate/effects.ts | 2 + .../src/animation/animate/multi-value.ts | 13 + .../src/animation/animate/single-value.ts | 2 + .../src/animation/interfaces/with-playback.ts | 16 ++ packages/motion-dom/src/animation/playback.ts | 243 +++++++++++++++++ .../src/animation/utils/notify-inspector.ts | 6 + .../waapi/transforms/TransformAnimation.ts | 151 +++-------- .../__tests__/group-without-playback.test.ts | 231 ++++++++++++++++ .../src/animation/waapi/transforms/retime.ts | 122 +++++++++ packages/motion-dom/src/index.ts | 5 +- .../src/layout/LayoutAnimationBuilder.ts | 2 + 15 files changed, 932 insertions(+), 323 deletions(-) create mode 100644 packages/motion-dom/src/animation/__tests__/playback.test.ts create mode 100644 packages/motion-dom/src/animation/interfaces/with-playback.ts create mode 100644 packages/motion-dom/src/animation/playback.ts create mode 100644 packages/motion-dom/src/animation/waapi/transforms/__tests__/group-without-playback.test.ts create mode 100644 packages/motion-dom/src/animation/waapi/transforms/retime.ts 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/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..4dd76c872b 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" @@ -29,6 +28,40 @@ import { TransformGroup, } from "./waapi/transforms/TransformAnimation" +/** + * 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 * holds and stops) and keeps what it takes to sample the value at the @@ -186,16 +219,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 +236,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 +248,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 +269,6 @@ export class ValueTrack ) finishTrack(this) } - - cancel() { - this.parent.cancel() - } - - attachTimeline(timeline: TimelineWithFallback) { - return this.parent.attachTimeline(timeline) - } } /** @@ -310,7 +300,7 @@ function endTrack(track: ValueTrack) { options.keyframes, options, (options as any).finalKeyframe, - track.parent.speed + track.parent.playbackSpeed ) } @@ -541,20 +531,6 @@ export class MultiValueAnimation 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 +658,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 +674,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 +690,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" ) { @@ -813,7 +702,7 @@ function fire( /** * 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") { @@ -843,7 +732,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 +819,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 +860,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 +901,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" ) { 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/effects.ts b/packages/motion-dom/src/animation/animate/effects.ts index c2115fb87c..7f8ad944be 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 || {} 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..4d63d9f675 100644 --- a/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts +++ b/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts @@ -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. @@ -956,112 +976,6 @@ function createGroup(owner: TransformOwner): TransformGroup { 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 - - /** - * Seeking to before it starts, or past its end, rebuilds. A seek - * every frame then moves the group to the main thread. - */ - 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 - } - /** * If no animations are left, write where they got to and cancel the * WAAPI animation. Returns whether the group ended. @@ -1158,7 +1072,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 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/retime.ts b/packages/motion-dom/src/animation/waapi/transforms/retime.ts new file mode 100644 index 0000000000..508bcb479e --- /dev/null +++ b/packages/motion-dom/src/animation/waapi/transforms/retime.ts @@ -0,0 +1,122 @@ +import { BuiltState, isHeld, TransformMember } from "./TransformAnimation" + +/** + * If every animation of a transform group has been paused, played, + * seeked or sped up together since its WAAPI animation was built, do + * the same to it. Returns false if it needs rebuilding instead. + */ +export const retime = ( + tracks: Set, + built: Map, + native: Animation | undefined, + /** + * How long after it was last built to build it, while waiting. + */ + buildAt: number | undefined, + /** + * When the WAAPI animation starts, relative to when the group was + * built, and how long it runs. + */ + nativeStart: number, + nativeLength: number, + /** + * Build after a delay, or with none, only cancel the build that's + * waiting. + */ + sleep: (delay?: number) => void, + 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 + sleep() + 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 + + /** + * Seeking to before it starts, or past its end, rebuilds. A seek + * every frame then moves the group to the main thread. + */ + 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 +} diff --git a/packages/motion-dom/src/index.ts b/packages/motion-dom/src/index.ts index d826948d4b..3de5238acd 100644 --- a/packages/motion-dom/src/index.ts +++ b/packages/motion-dom/src/index.ts @@ -18,10 +18,10 @@ export { isTransitionDefined } from "./animation/utils/is-transition-defined" export * from "./animation/utils/make-animation-instant" // Animation interfaces -export { animateMotionValue } from "./animation/interfaces/motion-value" +export { animateMotionValueWithPlayback as animateMotionValue } from "./animation/interfaces/with-playback" export type { VisualElementAnimationOptions } from "./animation/interfaces/types" export { animateVisualElement } from "./animation/interfaces/visual-element" -export { animateTarget } from "./animation/interfaces/visual-element-target" +export { animateTargetWithPlayback as animateTarget } from "./animation/interfaces/with-playback" export { animateVariant } from "./animation/interfaces/visual-element-variant" // Optimized appear @@ -68,6 +68,7 @@ export * from "./animation/waapi/utils/linear" export * from "./animation/animate/effects" export { supportTimelines } from "./animation/animate/attach-timeline" +export { supportPlayback } from "./animation/playback" export * from "./animation/animate/element" export * from "./effects/attr" export * from "./effects/MotionValueState" diff --git a/packages/motion-dom/src/layout/LayoutAnimationBuilder.ts b/packages/motion-dom/src/layout/LayoutAnimationBuilder.ts index 64bc996151..e94a785048 100644 --- a/packages/motion-dom/src/layout/LayoutAnimationBuilder.ts +++ b/packages/motion-dom/src/layout/LayoutAnimationBuilder.ts @@ -1,5 +1,6 @@ import { activeScope } from "../scope/active" import { GroupAnimation } from "../animation/GroupAnimation" +import { supportPlayback } from "../animation/playback" import type { AnimationOptions, Transition } from "../animation/types" import { frameData } from "../frameloop" import { flushFrame } from "../frameloop/flush-frame" @@ -304,6 +305,7 @@ export class LayoutAnimationBuilder { private defaultOptions?: AnimationOptions ) { registerLayoutProjection() + supportPlayback() this.readyPromise = new Promise((resolve, reject) => { this.notifyReady = resolve this.rejectReady = reject From 8d18ca3bc0257b65363d0acc1a505527f402f151 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 20:31:50 +0000 Subject: [PATCH 08/17] Test the first load for playback code Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- .../src/__tests__/first-load-chunk.test.ts | 46 ++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/packages/motion/src/__tests__/first-load-chunk.test.ts b/packages/motion/src/__tests__/first-load-chunk.test.ts index 3fa25a883c..0b67f994b5 100644 --- a/packages/motion/src/__tests__/first-load-chunk.test.ts +++ b/packages/motion/src/__tests__/first-load-chunk.test.ts @@ -1,5 +1,6 @@ /** @jest-environment node */ import resolve from "@rollup/plugin-node-resolve" +import replace from "@rollup/plugin-replace" import { readFileSync } from "fs" import { join } from "path" import { rollup } from "rollup" @@ -23,7 +24,7 @@ const lazyOnly = const fetchedOnly = /create-projection-node|projection\/(geometry\/delta-|animation\/)|VisualElementDragControls|gestures\/pan\// -async function firstLoadModules(code: string) { +async function firstLoadModules(code: string, env?: string) { const bundle = await rollup({ input: "entry", external: ["react", "react-dom", "react/jsx-runtime"], @@ -35,6 +36,11 @@ async function firstLoadModules(code: string) { load: (id) => (id === "entry" ? code : null), }, resolve({ rootDir: __dirname }), + !!env && + replace({ + "process.env.NODE_ENV": JSON.stringify(env), + preventAssignment: true, + }), ], }) const { output } = await bundle.generate({ format: "es", dir: "out" }) @@ -142,6 +148,44 @@ describe("motion first load", () => { expect(modules.filter((id) => fetchedOnly.test(id))).toEqual([]) }) + /** + * A component hands out no animation controls, so the code to pause, + * seek or change the speed of an animation is only in bundles with code + * that does, such as animate(). + * + * An inspector behind __MOTION_INSPECT__ controls the animations of + * components too. It runs on development builds, which have the code + * for it. + */ + test("has playback controls only with code that hands them out", async () => { + const playback = /animation\/playback|transforms\/retime/ + const hasPlayback = async (code: string, env = "production") => + (await firstLoadModules(code, env)).modules.some((id) => + playback.test(id) + ) + + for (const code of [ + `import { motion } from "motion/react"; export const D = motion.div`, + `import * as motion from "motion/react-client"; export const D = motion.div`, + `import { motion, AnimatePresence, useMotionValue, useTransform, useAnimationControls } from "motion/react"; export const D = [motion.div, AnimatePresence, useMotionValue, useTransform, useAnimationControls]`, + `import { m, LazyMotion, domAnimation } from "motion/react"; export const D = [m.div, LazyMotion, domAnimation]`, + ]) { + expect(await hasPlayback(code)).toBe(false) + expect(await hasPlayback(code, "development")).toBe(true) + } + + for (const code of [ + `export { animate } from "motion/react"`, + `export { useAnimate } from "motion/react"`, + `export { animate } from "motion"`, + `export { animateValue } from "motion"`, + `export { animateTarget } from "motion-dom"`, + `export { animateMotionValue } from "motion-dom"`, + ]) { + expect(await hasPlayback(code)).toBe(true) + } + }) + /** * webpack keeps a whole namespace object when a module copies one of its * members into a local binding, such as `const motion = ns.motion`. With From 8cd01ba246c89350e04932cfaf9256a42e011f14 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 21:38:09 +0000 Subject: [PATCH 09/17] Set size budgets for the size commits on the alpha Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- dev/inc/size-budgets.json | 96 ++++++++++++++++++++------------------- 1 file changed, 49 insertions(+), 47 deletions(-) diff --git a/dev/inc/size-budgets.json b/dev/inc/size-budgets.json index c8ac246269..0725a4fb69 100644 --- a/dev/inc/size-budgets.json +++ b/dev/inc/size-budgets.json @@ -1,69 +1,71 @@ { - "animate": 27800, + "animate": 27500, "mini-animate": 3250, - "animate-sequence": 27800, + "animate-sequence": 27550, "scroll": 3850, - "scroll+animate": 30450, + "scroll+animate": 30150, "inView": 500, "resize": 700, "hover+press": 2450, - "drag": 27350, + "drag": 26250, "pinch": 9400, - "motionValue": 1900, + "motionValue": 1950, "styleEffect": 4500, "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": 69950, + "motion-div": 32800, + "motion-div (all chunks)": 50900, + "motion-create": 32800, + "motion-create (all chunks)": 50900, + "motion-div(sync)": 47850, + "m-div": 5350, + "m-div(via motion/react)": 5500, + "m+LazyMotion+domAnimation": 31600, + "m+LazyMotion+domMax": 48000, + "m+LazyMotion+domDrag": 36300, + "m+LazyMotion+domLayout": 44000, + "LazyMotion-only": 700, + "domAnimation-only": 28850, + "domMax-only": 45300, + "AnimatePresence": 3950, "MotionConfig": 400, "LayoutGroup": 1200, - "Reorder": 43500, - "Reorder (all chunks)": 56050, - "Reorder(m)+LazyMotion": 14200, + "Reorder": 37350, + "Reorder (all chunks)": 55500, + "Reorder(m)+LazyMotion": 14100, "useMotionValue": 2100, "useTransform": 4800, - "useMotionTemplate": 2250, + "useMotionTemplate": 2300, "useSpring": 5050, - "useScroll": 6050, + "useScroll": 6100, "useInView": 650, - "useAnimate": 28100, + "useAnimate": 27850, "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": 18800, + "react-all": 86950, + "react-all (all chunks)": 87050, + "motion-div+AnimatePresence": 34950, + "motion-div+AnimatePresence (all chunks)": 53100, + "motion-div+useAnimate": 39450, + "motion-div+useAnimate (all chunks)": 57550, + "motion-div+animate": 39350, + "motion-div+animate (all chunks)": 57450, + "motion-div+useInView": 33000, + "motion-div+useInView (all chunks)": 51100, + "motion-div+useScroll": 36150, + "motion-div+useScroll (all chunks)": 54250, + "motion-div+useTransform+useMotionTemplate": 33350, + "motion-div+useTransform+useMotionTemplate (all chunks)": 51500, + "motion-div+useScroll+useTransform+useSpring": 37600, + "motion-div+useScroll+useTransform+useSpring (all chunks)": 55700, + "motion-div+Reorder": 37400, + "motion-div+Reorder (all chunks)": 55500, + "domMax+useScroll": 48700 } From c68ea7e2131a19df8849606f273bc8e3759ebcb9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 18:07:38 +0000 Subject: [PATCH 10/17] Hold transforms on the main thread past a device's repaint limit Brings the repaint rule of #4139 onto the size commits. Up to 100 repainting elements on a touch device, and 2,000 on a computer, every transform stays on the compositor. Past that, transforms run on the main thread, and return to the compositor while other scripts block it. Replaces the rule that moved the transforms of six or more repainting elements to the main thread on every device. Sizes, gzip: motion.div first load 32.36 kB (31.68 kB with the old rule), animate 27.30 kB. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- dev/inc/size-budgets.json | 80 +-- packages/framer-motion/package.json | 4 +- .../src/animation/MultiValueAnimation.ts | 81 ++- .../src/animation/animate/effects.ts | 9 +- .../waapi/transforms/TransformAnimation.ts | 17 +- .../__tests__/TransformAnimation.test.ts | 607 +++++++++++++++++- .../src/animation/waapi/transforms/groups.ts | 259 ++++++-- .../motion-dom/src/effects/style/index.ts | 13 +- .../projection/node/create-projection-node.ts | 9 - 9 files changed, 960 insertions(+), 119 deletions(-) diff --git a/dev/inc/size-budgets.json b/dev/inc/size-budgets.json index 0725a4fb69..268e5b6c0a 100644 --- a/dev/inc/size-budgets.json +++ b/dev/inc/size-budgets.json @@ -1,13 +1,13 @@ { - "animate": 27500, + "animate": 28250, "mini-animate": 3250, - "animate-sequence": 27550, + "animate-sequence": 28300, "scroll": 3850, - "scroll+animate": 30150, + "scroll+animate": 30850, "inView": 500, "resize": 700, "hover+press": 2450, - "drag": 26250, + "drag": 26950, "pinch": 9400, "motionValue": 1950, "styleEffect": 4500, @@ -15,26 +15,26 @@ "stagger": 850, "frame": 750, "mix": 2150, - "vanilla-all": 69950, - "motion-div": 32800, - "motion-div (all chunks)": 50900, - "motion-create": 32800, - "motion-create (all chunks)": 50900, - "motion-div(sync)": 47850, - "m-div": 5350, + "vanilla-all": 70650, + "motion-div": 33500, + "motion-div (all chunks)": 51600, + "motion-create": 33500, + "motion-create (all chunks)": 51600, + "motion-div(sync)": 48550, + "m-div": 5400, "m-div(via motion/react)": 5500, - "m+LazyMotion+domAnimation": 31600, - "m+LazyMotion+domMax": 48000, - "m+LazyMotion+domDrag": 36300, - "m+LazyMotion+domLayout": 44000, + "m+LazyMotion+domAnimation": 32300, + "m+LazyMotion+domMax": 48750, + "m+LazyMotion+domDrag": 37000, + "m+LazyMotion+domLayout": 44750, "LazyMotion-only": 700, - "domAnimation-only": 28850, - "domMax-only": 45300, + "domAnimation-only": 29550, + "domMax-only": 46000, "AnimatePresence": 3950, "MotionConfig": 400, "LayoutGroup": 1200, - "Reorder": 37350, - "Reorder (all chunks)": 55500, + "Reorder": 38050, + "Reorder (all chunks)": 56150, "Reorder(m)+LazyMotion": 14100, "useMotionValue": 2100, "useTransform": 4800, @@ -42,30 +42,30 @@ "useSpring": 5050, "useScroll": 6100, "useInView": 650, - "useAnimate": 27850, + "useAnimate": 28600, "useAnimate(mini)": 3350, "useMotionValueEvent": 150, "useReducedMotion": 300, "useAnimationFrame": 900, "useVelocity": 2200, - "useAnimationControls": 18800, - "react-all": 86950, - "react-all (all chunks)": 87050, - "motion-div+AnimatePresence": 34950, - "motion-div+AnimatePresence (all chunks)": 53100, - "motion-div+useAnimate": 39450, - "motion-div+useAnimate (all chunks)": 57550, - "motion-div+animate": 39350, - "motion-div+animate (all chunks)": 57450, - "motion-div+useInView": 33000, - "motion-div+useInView (all chunks)": 51100, - "motion-div+useScroll": 36150, - "motion-div+useScroll (all chunks)": 54250, - "motion-div+useTransform+useMotionTemplate": 33350, - "motion-div+useTransform+useMotionTemplate (all chunks)": 51500, - "motion-div+useScroll+useTransform+useSpring": 37600, - "motion-div+useScroll+useTransform+useSpring (all chunks)": 55700, - "motion-div+Reorder": 37400, - "motion-div+Reorder (all chunks)": 55500, - "domMax+useScroll": 48700 + "useAnimationControls": 19500, + "react-all": 87700, + "react-all (all chunks)": 87850, + "motion-div+AnimatePresence": 35700, + "motion-div+AnimatePresence (all chunks)": 53800, + "motion-div+useAnimate": 40200, + "motion-div+useAnimate (all chunks)": 58250, + "motion-div+animate": 40050, + "motion-div+animate (all chunks)": 58100, + "motion-div+useInView": 33700, + "motion-div+useInView (all chunks)": 51800, + "motion-div+useScroll": 36850, + "motion-div+useScroll (all chunks)": 54950, + "motion-div+useTransform+useMotionTemplate": 34050, + "motion-div+useTransform+useMotionTemplate (all chunks)": 52150, + "motion-div+useScroll+useTransform+useSpring": 38300, + "motion-div+useScroll+useTransform+useSpring (all chunks)": 56400, + "motion-div+Reorder": 38100, + "motion-div+Reorder (all chunks)": 56150, + "domMax+useScroll": 49400 } diff --git a/packages/framer-motion/package.json b/packages/framer-motion/package.json index 5b57cfb8f2..a04c980eae 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.4 kB" }, { "path": "./dist/size-rollup-scroll.js", @@ -180,7 +180,7 @@ }, { "path": "./dist/size-rollup-remix.js", - "maxSize": "52.8 kB" + "maxSize": "53.45 kB" } ], "gitHead": "78f3ff51b5508f7e8c1c283d8e80bcd26fec37d7" diff --git a/packages/motion-dom/src/animation/MultiValueAnimation.ts b/packages/motion-dom/src/animation/MultiValueAnimation.ts index 4dd76c872b..8be7fec5b4 100644 --- a/packages/motion-dom/src/animation/MultiValueAnimation.ts +++ b/packages/motion-dom/src/animation/MultiValueAnimation.ts @@ -27,6 +27,7 @@ import { joinGroup, TransformGroup, } from "./waapi/transforms/TransformAnimation" +import { holdTransforms, setCompositorLayer } from "./waapi/transforms/groups" /** * The controls of an animation that only code holding it can use: @@ -98,6 +99,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. */ @@ -204,6 +211,39 @@ 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. + */ + schedule() { + const { parent, pooled } = this + if ( + this.native || + this.isDone || + this.isStopped || + parent.isStopped || + parent.isCancelled || + !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. */ @@ -508,25 +548,27 @@ 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) } @@ -699,6 +741,24 @@ export 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. */ @@ -999,6 +1059,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/animate/effects.ts b/packages/motion-dom/src/animation/animate/effects.ts index 7f8ad944be..7fa87d91dd 100644 --- a/packages/motion-dom/src/animation/animate/effects.ts +++ b/packages/motion-dom/src/animation/animate/effects.ts @@ -101,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) } @@ -151,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/waapi/transforms/TransformAnimation.ts b/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts index 4d63d9f675..9a02acacb3 100644 --- a/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts +++ b/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts @@ -37,9 +37,8 @@ import { acceleratedValues } from "../utils/accelerated-values" import { generateLinearEasing } from "../utils/linear" import { supportsLinearEasing } from "../../../utils/supports/linear-easing" import { - addCompositorLayer, - isRepainting, - markRepaint, + holdTransforms, + setCompositorLayer, TransformGroupHooks, transformGroups, } from "./groups" @@ -571,7 +570,7 @@ function createGroup(owner: TransformOwner): TransformGroup { native.onfinish = native.oncancel = null native.cancel() native = scrollAnimation = undefined - addCompositorLayer(-1) + setCompositorLayer(group, false) } } @@ -627,7 +626,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) } @@ -1040,10 +1039,10 @@ 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. + * While too many elements repaint every frame, it stays on the + * main thread. */ - if (isRepainting(element)) return demote(true) + if (holdTransforms(group)) return demote(true) let timeline: TimelineWithFallback | undefined | false = false for (const track of tracks) { @@ -1205,8 +1204,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..b769b9a88b 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 { 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" @@ -255,6 +256,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") @@ -2023,10 +2043,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 +2190,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 +2403,444 @@ describe("independent transform acceleration", () => { } }) + describe("with transform animated directly", () => { + const move = { transform: ["translateX(0px)", "translateX(100px)"] } + + 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) + + isBlocking = false + 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/groups.ts b/packages/motion-dom/src/animation/waapi/transforms/groups.ts index bbc1590ec7..8318c66a38 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" /** @@ -27,32 +27,40 @@ export interface TransformGroupHooks { * Rebuild or retime the WAAPI animation. */ 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. - */ - repaint(value: MotionValue): void } export const transformGroups = new WeakMap() /** - * How many elements have a WAAPI animation from their group, and so a - * compositor layer. Layout animations share their layer budget with these. + * Set to markRepaint when the first transform could be held, so a + * renderer can count repaints without importing the frame loop. + */ +export const repaintHook: { mark?: typeof markRepaint } = {} + +/** + * What runs a transform on the compositor: an element's group, or the + * animation of a `transform` set directly. It can move to the main thread + * and back. + */ +export type Layer = Pick + +/** + * Those running on the compositor now, and how many. Layout animations + * share their layer budget with these. */ +const accelerated = new Set() export let compositorLayers = 0 -export const addCompositorLayer = (amount: number) => - (compositorLayers += amount) +export const setCompositorLayer = (layer: Layer, isLayer: boolean) => { + isLayer ? accelerated.add(layer) : accelerated.delete(layer) + compositorLayers = accelerated.size +} /** * An element repainted every frame by a style animating on the main thread * is rastered again every frame. With a compositor layer for its * transforms, each element is rastered on its own; without, they're - * rastered together. Up to this many, the layers cost about the same and - * keep transforms smooth while the main thread is busy. From here they - * cost more, so the transforms of these elements move to the main thread - * until they stop repainting. + * rastered together. From this many, a layout animation gives one that + * repaints no layer of its own. */ export const repaintLimit = 6 @@ -64,25 +72,201 @@ type Repaints = Map let repainted: Repaints = new Map() let repainting: Repaints = new Map() -const isOver = (elements: Repaints, element: object) => - elements.size >= repaintLimit && elements.has(element) +const isMany = (elements: Repaints) => elements.size >= repaintLimit + +const isHeavy = () => isMany(repainting) || isMany(repainted) /** - * Whether an element's transforms should stay on the main thread because - * it's one of too many repainting elements. + * Whether an element is one of too many repainting elements. */ export const isRepainting = (element: object) => - isOver(repainting, element) || isOver(repainted, element) + (isMany(repainting) && repainting.has(element)) || + (isMany(repainted) && repainted.has(element)) + +/** + * The transforms held on the main thread while too many elements repaint. + */ +const held = new Set() + +/** + * Held transforms are only smoother than the compositor's while the main + * thread gets to render them. So while too many elements repaint, the + * time between frames is compared with the shortest it has been, which is + * about a frame of the display, and the time the main thread was busy + * between frames is split in three: Motion's frame, the browser rendering + * it (a message posted from a frame is read once it has rendered), and + * the rest, which is other scripts. A timer that keeps being set finds + * the total, from how late it runs. + * + * If frames are long and other scripts are part of why, transforms are + * smoother on the compositor. If only rendering is slow, they stay: the + * main thread still renders elements that repaint together faster than + * the compositor does apart. + */ +let interval = 1000 / 60 +let average = interval +let others = 0 +let work = 0 +let lastTime = 0 +let frameEnd = 0 +let workTime = 0 +let busyTime = 0 +let probeTime = 0 +let port: MessagePort | undefined + +/** + * Requested after a frame, so it's the last callback of the next: any + * that run after Motion's are other scripts, not rendering. + */ +const endFrame = () => (frameEnd = performance.now()) + +const probeDelay = 4 +const probe = () => { + const now = performance.now() + + /** + * Frames stop in a hidden tab, and timers run late there whatever + * the main thread does. + */ + if (!lastTime || now - frameEnd > 500) return (probeTime = 0) + busyTime += Math.max(now - probeTime - probeDelay - 1, 0) + probeTime = now + setTimeout(probe, probeDelay) +} + +/** + * With up to this many elements repainting, a compositor keeps transforms + * at the display's rate, and no script can block it. So only more than + * this holds transforms on the main thread. A phone's compositor draws + * fewer than a computer's, and past `max` not at the display's rate at + * all. + * + * That's every transform, not only those of the elements that repaint. A + * layer that moves over an element makes the browser give that element a + * layer too, so one that repaints is rastered on its own again. + */ +export const layerLimits = { computer: 2000, touch: 100, max: 500 } + +let touch: MediaQueryList | undefined +const isTouch = () => + typeof matchMedia !== "undefined" && + (touch ||= matchMedia("(pointer:coarse)")).matches + +const isOver = (limit: number) => + Math.max(repainting.size, repainted.size) > limit + +const isOverLimit = () => + isOver(isTouch() ? layerLimits.touch : layerLimits.computer) + +/** + * The more of them a phone's compositor has to draw, the longer other + * scripts have to block the main thread before it's the faster of the + * two: past `max` more than a frame, and past twice that it never is. + */ +const isBlocked = (by: number) => + average > interval * by && + others > + (isOver(layerLimits.max) && isTouch() + ? isOver(layerLimits.max * 2) + ? Infinity + : interval + : Math.max(interval, work) / 4) + +/** + * Whether transforms are on the compositor because the main thread is + * blocked, and how many frames it has to be free for before they return + * to it. That doubles each time they do, so work that comes and goes + * can't move them back and forth every second. + */ +let isAway = false +let wait = 0 +let calm = 0 +let calmFrames = 30 + +const release = (layer: Layer) => layer.schedule(true) + +const move = (away: boolean) => { + isAway = away + wait = 12 + calm = 0 + if (away) { + held.forEach(release) + held.clear() + } else { + accelerated.forEach(holdLayer) + } +} + +const judge = () => { + const { timestamp } = frameData + + /** + * A frame long after the last is the first since the tab was hidden. + */ + if (lastTime && timestamp - lastTime < 500) { + average += (Math.min(timestamp - lastTime, 100) - average) * 0.1 + others += (Math.max(busyTime - workTime, 0) - others) * 0.1 + work += (workTime - work) * 0.1 + interval = Math.max(4, Math.min(interval, average)) + } + lastTime = timestamp + busyTime = 0 + + /** + * Until the message is read, the frame's work is only Motion's. + */ + workTime = (frameEnd = performance.now()) - timestamp + if ( + !port && + typeof MessageChannel !== "undefined" && + typeof requestAnimationFrame !== "undefined" + ) { + const channel = new MessageChannel() + port = channel.port2 + channel.port1.onmessage = () => { + workTime += performance.now() - frameEnd + requestAnimationFrame(endFrame) + } + } + if (!probeTime) { + probeTime = frameEnd + setTimeout(probe, probeDelay) + } + port?.postMessage(0) + + if (wait && --wait) return + + if (!isAway) { + isBlocked(1.25) ? move(true) : accelerated.forEach(holdLayer) + } else if (isBlocked(1.1)) { + calm = 0 + } else if (++calm >= calmFrames) { + calmFrames *= 2 + move(false) + } +} + +/** + * Whether a transform should stay on the main thread because too many + * elements repaint. It's told when they stop. + */ +export const holdTransforms = (layer: Layer) => + !!(repaintHook.mark = markRepaint) && + isHeavy() && + !isAway && + isOverLimit() && + !!held.add(layer) + +const holdLayer = (layer: Layer) => holdTransforms(layer) && layer.demote(true) const nextFrame = () => { - const previous = repainted repainted = repainting repainting = new Map() /** * A value that's still animating repaints its element again, if not * on this frame: a colour near its target is a new value only every - * few frames. So its element still counts, rather than its transforms + * few frames. So its element still counts, rather than transforms * moving to the compositor and back between changes. */ repainted.forEach( @@ -92,17 +276,21 @@ const nextFrame = () => { ) /** - * Elements held on the main thread that no longer repaint, or are no - * longer too many, move back to the compositor. + * Transforms held on the main thread move back to the compositor when + * the elements no longer repaint, or are no longer too many. Nothing + * is measured until they are again. */ - previous.size >= repaintLimit && - previous.forEach( - (_, element) => - isRepainting(element) || - transformGroups.get(element)?.schedule(true) - ) - - repainted.size && frame.postRender(nextFrame) + if (isHeavy() && isOverLimit()) { + judge() + } else { + move(true) + isAway = false + wait = lastTime = others = work = 0 + average = interval = 1000 / 60 + calmFrames = 30 + } + + repainted.size ? frame.postRender(nextFrame) : (lastTime = 0) } /** @@ -116,11 +304,4 @@ export const markRepaint = (element: object, value?: MotionValue) => { repainting.size || frame.postRender(nextFrame) repainting.set(element, value) - - const { size } = repainting - if (size === repaintLimit) { - repainting.forEach((_, e) => transformGroups.get(e)?.demote(true)) - } else if (size > repaintLimit) { - transformGroups.get(element)?.demote(true) - } } diff --git a/packages/motion-dom/src/effects/style/index.ts b/packages/motion-dom/src/effects/style/index.ts index 497384e3ce..0679ded156 100644 --- a/packages/motion-dom/src/effects/style/index.ts +++ b/packages/motion-dom/src/effects/style/index.ts @@ -1,4 +1,7 @@ -import { transformGroups } from "../../animation/waapi/transforms/groups" +import { + repaintHook, + transformGroups, +} from "../../animation/waapi/transforms/groups" import { isCSSVar } from "../../render/dom/is-css-var" import { acceleratedValues } from "../../animation/waapi/utils/accelerated-values" import { readTransformValue } from "../../render/dom/parse-transform" @@ -194,16 +197,16 @@ const getValueRender = ( ) => { /** * A style animating on the main thread repaints the element every - * frame. If it also has compositor transforms, count it, as too many - * such elements cost more than animating their transforms on the - * main thread. A CSS variable is never composited. + * frame. Count it, as with too many such elements, transforms cost + * less on the main thread than on the compositor. A CSS variable is + * never composited. */ const isComposited = acceleratedValues.has(key) return () => { if (!isComposited) { const value = (node as MotionNode).values?.get(key) - value?.isAnimating() && transformGroups.get(element)?.repaint(value) + value?.isAnimating() && repaintHook.mark?.(element, value) } setStyle(element, key, styleValue(node, key) as string) diff --git a/packages/motion-dom/src/projection/node/create-projection-node.ts b/packages/motion-dom/src/projection/node/create-projection-node.ts index 43b9929e63..1ca5930b96 100644 --- a/packages/motion-dom/src/projection/node/create-projection-node.ts +++ b/packages/motion-dom/src/projection/node/create-projection-node.ts @@ -48,7 +48,6 @@ import { import { compositorLayers, isRepainting, - markRepaint, transformGroups, } from "../../animation/waapi/transforms/groups" import { copyAxisDeltaInto, copyAxisInto, copyBoxInto } from "../geometry/copy" @@ -2767,14 +2766,6 @@ export function createProjectionNode({ : 0 ) - /** - * Corrected values that change repaint this element, so it - * counts towards the elements that repaint (see repaintLimit). - */ - transform !== "none" && - isCorrecting(this) && - markRepaint(this.instance as object) - /** * Apply scale correction */ From ccbeeae51867ca05963cca7aa34c5786dc3955d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 18:31:28 +0000 Subject: [PATCH 11/17] Hold the probe timer once the return test stops blocking On a CI machine busy with other suites, frames ran long after the test stopped its block, and the late probe timer read as other scripts. The transforms then stayed on the compositor past the 120 frames the test waits. The timer is held from the moment the block ends, as it is for the tests that never block. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- .../waapi/transforms/__tests__/TransformAnimation.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) 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 b769b9a88b..916691e4c2 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 @@ -2832,7 +2832,13 @@ describe("independent transform acceleration", () => { 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) { From 40d03709b13fdf112d6a543aa266cbaf4dba73f1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 19:08:10 +0000 Subject: [PATCH 12/17] Steady two transform tests on a busy machine The speed tests compared a WAAPI animation with the animation that drives it in two reads of the clock. A stall between the reads counts twice at double speed, and CI had one of 25ms. Both are now read at one moment. The layer count test took the number of compositor layers before it started. Animations that earlier tests left running each held a layer until they finished, and some finished during the test. Each test's animations are now stopped before the next. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- .../__tests__/TransformAnimation.test.ts | 38 +++++++++++++++---- 1 file changed, 31 insertions(+), 7 deletions(-) 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 916691e4c2..3b0e79018f 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,4 +1,4 @@ -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" @@ -164,7 +164,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() }) @@ -174,6 +188,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. @@ -818,9 +846,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]) @@ -939,9 +965,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]) }) From eab26e2027368d0eefb06629b8300659702427ab Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 19:43:27 +0000 Subject: [PATCH 13/17] Give two delay tests a delay a busy machine can't use up Two tests of values in their delay read the value after a few frames and expect the delay of 0.5 seconds to still be running. On CircleCI the five frames of the first test took 529 ms, so the animation had started and the value was 29, not 0. A stall of 450 ms in the test gives the same failure here. The delay is now 10 seconds, and each test stops its animation once it has read the value. Test only. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- .../animate/__tests__/delay-sleep.test.ts | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) 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() }) }) From 3c547d1b4c738d0fa3d993971eba5ebed1a738dc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 20:31:47 +0000 Subject: [PATCH 14/17] Repaint rule: leave scroll timelines alone, and forget ended transforms Three faults of the rule, found in review: A transform on a native scroll timeline was held on the main thread like any other while too many elements repainted. To hold it, it's made to follow its timeline from JS, and it can't go back. Only the compositor moves it with the scroll, so it's now never held. A `transform` animated directly that was held before its timeline was attached joins the timeline on the compositor, and one that follows a timeline from JS is no longer started again on a clock when the hold ends. A held `transform` at a speed of 0 returned to the compositor at its start. It's running, so it was given a start time, and at a rate of 0 that leaves it at 0. It's now set to where it's held. A transform that ended while it was held stayed in the set of held transforms, with its element, until the page stopped repainting. It's now forgotten when its animation finishes or stops. This is 62 bytes gzip on `animate`, so its bundlesize limit goes from 27.4 to 27.45 kB, and the Remix limit from 53.45 to 53.5 kB. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- packages/framer-motion/package.json | 4 +- .../src/animation/MultiValueAnimation.ts | 18 +- .../src/animation/animate/attach-timeline.ts | 9 +- .../waapi/transforms/TransformAnimation.ts | 16 +- .../__tests__/TransformAnimation.test.ts | 242 +++++++++++++++++- .../src/animation/waapi/transforms/groups.ts | 21 +- 6 files changed, 296 insertions(+), 14 deletions(-) diff --git a/packages/framer-motion/package.json b/packages/framer-motion/package.json index a04c980eae..ccb3eb94ff 100644 --- a/packages/framer-motion/package.json +++ b/packages/framer-motion/package.json @@ -168,7 +168,7 @@ }, { "path": "./dist/size-rollup-animate.js", - "maxSize": "27.4 kB" + "maxSize": "27.45 kB" }, { "path": "./dist/size-rollup-scroll.js", @@ -180,7 +180,7 @@ }, { "path": "./dist/size-rollup-remix.js", - "maxSize": "53.45 kB" + "maxSize": "53.5 kB" } ], "gitHead": "78f3ff51b5508f7e8c1c283d8e80bcd26fec37d7" diff --git a/packages/motion-dom/src/animation/MultiValueAnimation.ts b/packages/motion-dom/src/animation/MultiValueAnimation.ts index 8be7fec5b4..b2b2307618 100644 --- a/packages/motion-dom/src/animation/MultiValueAnimation.ts +++ b/packages/motion-dom/src/animation/MultiValueAnimation.ts @@ -27,7 +27,11 @@ import { joinGroup, TransformGroup, } from "./waapi/transforms/TransformAnimation" -import { holdTransforms, setCompositorLayer } from "./waapi/transforms/groups" +import { + forgetLayer, + holdTransforms, + setCompositorLayer, +} from "./waapi/transforms/groups" /** * The controls of an animation that only code holding it can use: @@ -224,7 +228,8 @@ export class ValueTrack } /** - * And back, from where the clock has it. + * 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 @@ -234,6 +239,7 @@ export class ValueTrack this.isStopped || parent.isStopped || parent.isCancelled || + parent.unfollow || !pooled ) return @@ -326,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) @@ -348,6 +355,7 @@ function stopTrack(track: ValueTrack) { if (track.isStopped) return track.parent.state === "idle" || track.options.onStop?.() track.isStopped = true + track.pooled && forgetLayer(track) track.resolver?.cancel() endValue(track) removeTrack(track.parent, track) @@ -770,6 +778,12 @@ export 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) } } 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/waapi/transforms/TransformAnimation.ts b/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts index 9a02acacb3..21ea221dd3 100644 --- a/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts +++ b/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts @@ -37,6 +37,7 @@ import { acceleratedValues } from "../utils/accelerated-values" import { generateLinearEasing } from "../utils/linear" import { supportsLinearEasing } from "../../../utils/supports/linear-easing" import { + forgetLayer, holdTransforms, setCompositorLayer, TransformGroupHooks, @@ -570,6 +571,7 @@ function createGroup(owner: TransformOwner): TransformGroup { native.onfinish = native.oncancel = null native.cancel() native = scrollAnimation = undefined + group.isScrolling = false setCompositorLayer(group, false) } } @@ -973,6 +975,7 @@ function createGroup(owner: TransformOwner): TransformGroup { animation.timeline = timeline.timeline as AnimationTimeline timeline.onAttach ? timeline.onAttach(animation) : animation.play() scrollAnimation = animation + group.isScrolling = true } /** @@ -983,6 +986,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). @@ -1038,12 +1042,6 @@ function createGroup(owner: TransformOwner): TransformGroup { if (end()) return - /** - * While too many elements repaint every frame, it stays on the - * main thread. - */ - if (holdTransforms(group)) return demote(true) - let timeline: TimelineWithFallback | undefined | false = false for (const track of tracks) { const { scrollTimeline } = track @@ -1056,6 +1054,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. 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 3b0e79018f..609ab4cddb 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 @@ -61,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. */ @@ -2427,9 +2430,246 @@ 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("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("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) diff --git a/packages/motion-dom/src/animation/waapi/transforms/groups.ts b/packages/motion-dom/src/animation/waapi/transforms/groups.ts index 8318c66a38..1ae06364fa 100644 --- a/packages/motion-dom/src/animation/waapi/transforms/groups.ts +++ b/packages/motion-dom/src/animation/waapi/transforms/groups.ts @@ -27,6 +27,12 @@ export interface TransformGroupHooks { * Rebuild or retime the WAAPI animation. */ schedule(needsBuild: boolean): void + + /** + * 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. + */ + isScrolling?: boolean } export const transformGroups = new WeakMap() @@ -42,7 +48,10 @@ export const repaintHook: { mark?: typeof markRepaint } = {} * animation of a `transform` set directly. It can move to the main thread * and back. */ -export type Layer = Pick +export type Layer = Pick< + TransformGroupHooks, + "demote" | "schedule" | "isScrolling" +> /** * Those running on the compositor now, and how many. Layout animations @@ -257,7 +266,15 @@ export const holdTransforms = (layer: Layer) => isOverLimit() && !!held.add(layer) -const holdLayer = (layer: Layer) => holdTransforms(layer) && layer.demote(true) +const holdLayer = (layer: Layer) => + layer.isScrolling || (holdTransforms(layer) && layer.demote(true)) + +/** + * A transform that ended while it was held has nothing to return to the + * compositor. Forgotten, it doesn't keep its element for as long as the + * others repaint. + */ +export const forgetLayer = (layer: Layer) => held.delete(layer) const nextFrame = () => { repainted = repainting From 556348b3d03dc63ef5fec021554e49c41a6268a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 20:37:18 +0000 Subject: [PATCH 15/17] Give m components the layout shell beside components that fetch layout Features are shared by every component on the page. The components that fetch layout code used to load their MeasureLayout for all of them, so an `m` component with `layout` took part once the code had arrived. Since the shell replaced it, the fetched code brought a projection node for an `m` component and nothing to drive it from React: no snapshot before a layout change, no layout group, no promotion. The shell is now loaded for every component, as MeasureLayout was. The exit feature also checks that a presence context has `register` before it calls it, as it did before it moved. Both found in review. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- .../__tests__/async-features-m.test.tsx | 63 +++++++++++++++++++ .../src/motion/features/animation/exit.ts | 2 +- .../render/components/motion-async/proxy.ts | 7 ++- 3 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 packages/framer-motion/src/motion/__tests__/async-features-m.test.tsx 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/features/animation/exit.ts b/packages/framer-motion/src/motion/features/animation/exit.ts index 3548fc9437..3873f51412 100644 --- a/packages/framer-motion/src/motion/features/animation/exit.ts +++ b/packages/framer-motion/src/motion/features/animation/exit.ts @@ -26,7 +26,7 @@ export class ExitAnimationFeature extends Feature { * 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) + this.stop ||= presenceContext.register?.(this.id, this.node) const { isPresent, onExitComplete } = presenceContext 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 b0e2f16d67..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,5 +1,6 @@ import { AnimationFeature } from "../../../motion/features/animation" import { gestureAnimations } from "../../../motion/features/gestures" +import { MeasureLayout } from "../../../motion/features/layout/MeasureLayoutShell" import { preloadFeatures as preload, useAsyncFeatures, @@ -21,10 +22,14 @@ import { featureLoaders } from "./loaders" * 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( - { animation: { Feature: AnimationFeature } }, + { animation: { Feature: AnimationFeature }, layout: { MeasureLayout } }, gestureAnimations ), createDomVisualElement, From 8e2c3ec94de14d683b4ac457bbd55ce7c7baca04 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 20:47:25 +0000 Subject: [PATCH 16/17] Keep a component's MeasureLayout, and forget more held transforms From the second pass of the review. A component now keeps the MeasureLayout it first renders. Features are shared by every component on the page, and since the last commit the components that fetch layout code load the shell for all of them, where `LazyMotion` with `domMax` and the components that bundle their features load the bundled one. In an app with both, a mounted `m` or bundled component was given the other on a later render. That mounts it again, and a mount takes no snapshot, so that layout change wasn't animated. A transform group that was held before it joined a scroll timeline is forgotten when it joins, so the end of the hold doesn't build its animation again. A held `transform` is forgotten when its whole animation is stopped, not only when it is stopped alone. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- .../async-features-identity.test.tsx | 79 +++++++++++++++++++ packages/framer-motion/src/motion/index.tsx | 20 ++++- .../src/animation/MultiValueAnimation.ts | 2 +- .../waapi/transforms/TransformAnimation.ts | 6 ++ .../__tests__/TransformAnimation.test.ts | 62 +++++++++++++++ 5 files changed, 166 insertions(+), 3 deletions(-) create mode 100644 packages/framer-motion/src/motion/__tests__/async-features-identity.test.tsx 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/index.tsx b/packages/framer-motion/src/motion/index.tsx index 0f137dfdc9..293778d788 100644 --- a/packages/framer-motion/src/motion/index.tsx +++ b/packages/framer-motion/src/motion/index.tsx @@ -7,7 +7,14 @@ import { } 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" @@ -171,6 +178,15 @@ export function createMotionComponent< */ 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. + */ + const measure = useRef(undefined) + const layoutProjection = getProjectionFunctionality(configAndProps) /** @@ -196,7 +212,7 @@ export function createMotionComponent< layoutProjection.isEnabled || context.visualElement?.projection?.options.layoutId ) - MeasureLayout = + MeasureLayout = measure.current ||= FetchedMeasureLayout || layoutProjection.MeasureLayout } diff --git a/packages/motion-dom/src/animation/MultiValueAnimation.ts b/packages/motion-dom/src/animation/MultiValueAnimation.ts index b2b2307618..00b57bd044 100644 --- a/packages/motion-dom/src/animation/MultiValueAnimation.ts +++ b/packages/motion-dom/src/animation/MultiValueAnimation.ts @@ -355,7 +355,6 @@ function stopTrack(track: ValueTrack) { if (track.isStopped) return track.parent.state === "idle" || track.options.onStop?.() track.isStopped = true - track.pooled && forgetLayer(track) track.resolver?.cancel() endValue(track) removeTrack(track.parent, track) @@ -998,6 +997,7 @@ export 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()) { diff --git a/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts b/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts index 21ea221dd3..0e64b259b7 100644 --- a/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts +++ b/packages/motion-dom/src/animation/waapi/transforms/TransformAnimation.ts @@ -976,6 +976,12 @@ function createGroup(owner: TransformOwner): TransformGroup { timeline.onAttach ? timeline.onAttach(animation) : animation.play() scrollAnimation = animation group.isScrolling = true + + /** + * If it was held before it joined its timeline, the end of that + * hold has nothing to return. + */ + forgetLayer(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 609ab4cddb..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 @@ -2513,6 +2513,38 @@ describe("independent transform acceleration", () => { 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( @@ -2637,6 +2669,36 @@ describe("independent transform acceleration", () => { 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) => From a13b5230cb4dbd1933c5372a7127d3b0958b1900 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 04:40:06 +0000 Subject: [PATCH 17/17] Set size budgets after the rebase on main Main now holds #4125 and #4136, which add about 0.29 kB to a motion component and 0.11 kB to animate. The bundlesize limits for animate and Remix go to 27.55 kB and 53.65 kB for the same reason. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016xzo3aG8ZEbuWJW9bSLjET --- dev/inc/size-budgets.json | 88 ++++++++++++++--------------- packages/framer-motion/package.json | 4 +- 2 files changed, 46 insertions(+), 46 deletions(-) diff --git a/dev/inc/size-budgets.json b/dev/inc/size-budgets.json index 268e5b6c0a..e6fcab16c1 100644 --- a/dev/inc/size-budgets.json +++ b/dev/inc/size-budgets.json @@ -1,71 +1,71 @@ { - "animate": 28250, + "animate": 28450, "mini-animate": 3250, - "animate-sequence": 28300, + "animate-sequence": 28450, "scroll": 3850, - "scroll+animate": 30850, + "scroll+animate": 31050, "inView": 500, "resize": 700, "hover+press": 2450, - "drag": 26950, - "pinch": 9400, + "drag": 27100, + "pinch": 9450, "motionValue": 1950, - "styleEffect": 4500, + "styleEffect": 4550, "animateView": 6400, "stagger": 850, "frame": 750, "mix": 2150, - "vanilla-all": 70650, - "motion-div": 33500, - "motion-div (all chunks)": 51600, - "motion-create": 33500, - "motion-create (all chunks)": 51600, - "motion-div(sync)": 48550, - "m-div": 5400, - "m-div(via motion/react)": 5500, - "m+LazyMotion+domAnimation": 32300, - "m+LazyMotion+domMax": 48750, - "m+LazyMotion+domDrag": 37000, - "m+LazyMotion+domLayout": 44750, + "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": 29550, - "domMax-only": 46000, + "domAnimation-only": 29700, + "domMax-only": 46100, "AnimatePresence": 3950, "MotionConfig": 400, "LayoutGroup": 1200, - "Reorder": 38050, - "Reorder (all chunks)": 56150, - "Reorder(m)+LazyMotion": 14100, + "Reorder": 38450, + "Reorder (all chunks)": 56550, + "Reorder(m)+LazyMotion": 14400, "useMotionValue": 2100, "useTransform": 4800, "useMotionTemplate": 2300, "useSpring": 5050, "useScroll": 6100, "useInView": 650, - "useAnimate": 28600, + "useAnimate": 28750, "useAnimate(mini)": 3350, "useMotionValueEvent": 150, "useReducedMotion": 300, "useAnimationFrame": 900, "useVelocity": 2200, - "useAnimationControls": 19500, - "react-all": 87700, - "react-all (all chunks)": 87850, - "motion-div+AnimatePresence": 35700, - "motion-div+AnimatePresence (all chunks)": 53800, - "motion-div+useAnimate": 40200, - "motion-div+useAnimate (all chunks)": 58250, - "motion-div+animate": 40050, - "motion-div+animate (all chunks)": 58100, - "motion-div+useInView": 33700, - "motion-div+useInView (all chunks)": 51800, - "motion-div+useScroll": 36850, - "motion-div+useScroll (all chunks)": 54950, - "motion-div+useTransform+useMotionTemplate": 34050, - "motion-div+useTransform+useMotionTemplate (all chunks)": 52150, - "motion-div+useScroll+useTransform+useSpring": 38300, - "motion-div+useScroll+useTransform+useSpring (all chunks)": 56400, - "motion-div+Reorder": 38100, - "motion-div+Reorder (all chunks)": 56150, - "domMax+useScroll": 49400 + "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/packages/framer-motion/package.json b/packages/framer-motion/package.json index ccb3eb94ff..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": "27.45 kB" + "maxSize": "27.55 kB" }, { "path": "./dist/size-rollup-scroll.js", @@ -180,7 +180,7 @@ }, { "path": "./dist/size-rollup-remix.js", - "maxSize": "53.5 kB" + "maxSize": "53.65 kB" } ], "gitHead": "78f3ff51b5508f7e8c1c283d8e80bcd26fec37d7"