motion-dom 12.39.0 → 12.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/cjs/index.js +1656 -847
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/es/animation/JSAnimation.mjs +0 -3
  4. package/dist/es/animation/JSAnimation.mjs.map +1 -1
  5. package/dist/es/animation/interfaces/visual-element-target.mjs +5 -0
  6. package/dist/es/animation/interfaces/visual-element-target.mjs.map +1 -1
  7. package/dist/es/animation/utils/arc.mjs +188 -0
  8. package/dist/es/animation/utils/arc.mjs.map +1 -0
  9. package/dist/es/animation/waapi/start-waapi-animation.mjs +1 -12
  10. package/dist/es/animation/waapi/start-waapi-animation.mjs.map +1 -1
  11. package/dist/es/effects/style/transform.mjs +9 -0
  12. package/dist/es/effects/style/transform.mjs.map +1 -1
  13. package/dist/es/events/add-dom-event.mjs +1 -1
  14. package/dist/es/events/add-dom-event.mjs.map +1 -1
  15. package/dist/es/frameloop/batcher.mjs +1 -1
  16. package/dist/es/frameloop/batcher.mjs.map +1 -1
  17. package/dist/es/frameloop/render-step.mjs +1 -12
  18. package/dist/es/frameloop/render-step.mjs.map +1 -1
  19. package/dist/es/gestures/press/index.mjs +11 -4
  20. package/dist/es/gestures/press/index.mjs.map +1 -1
  21. package/dist/es/index.mjs +1 -1
  22. package/dist/es/layout/LayoutAnimationBuilder.mjs +299 -214
  23. package/dist/es/layout/LayoutAnimationBuilder.mjs.map +1 -1
  24. package/dist/es/projection/node/create-projection-node.mjs +30 -12
  25. package/dist/es/projection/node/create-projection-node.mjs.map +1 -1
  26. package/dist/es/projection/styles/transform.mjs +4 -1
  27. package/dist/es/projection/styles/transform.mjs.map +1 -1
  28. package/dist/es/render/html/utils/build-transform.mjs +8 -0
  29. package/dist/es/render/html/utils/build-transform.mjs.map +1 -1
  30. package/dist/es/render/utils/keys-transform.mjs +8 -1
  31. package/dist/es/render/utils/keys-transform.mjs.map +1 -1
  32. package/dist/es/stats/buffer.mjs.map +1 -1
  33. package/dist/es/stats/index.mjs +4 -93
  34. package/dist/es/stats/index.mjs.map +1 -1
  35. package/dist/es/value/types/maps/transform.mjs +6 -0
  36. package/dist/es/value/types/maps/transform.mjs.map +1 -1
  37. package/dist/es/view/index.mjs +90 -13
  38. package/dist/es/view/index.mjs.map +1 -1
  39. package/dist/es/view/queue.mjs +9 -3
  40. package/dist/es/view/queue.mjs.map +1 -1
  41. package/dist/es/view/start.mjs +484 -83
  42. package/dist/es/view/start.mjs.map +1 -1
  43. package/dist/es/view/utils/assign-names.mjs +118 -0
  44. package/dist/es/view/utils/assign-names.mjs.map +1 -0
  45. package/dist/es/view/utils/choose-layer-type.mjs +1 -3
  46. package/dist/es/view/utils/choose-layer-type.mjs.map +1 -1
  47. package/dist/es/view/utils/get-layer-info.mjs +3 -1
  48. package/dist/es/view/utils/get-layer-info.mjs.map +1 -1
  49. package/dist/es/view/utils/get-view-animations.mjs +6 -8
  50. package/dist/es/view/utils/get-view-animations.mjs.map +1 -1
  51. package/dist/index.d.ts +1269 -1132
  52. package/dist/motion-dom.dev.js +1656 -847
  53. package/dist/motion-dom.js +1 -1
  54. package/dist/size-rollup-motion-value.js.map +1 -1
  55. package/dist/size-rollup-style-effect.js +1 -1
  56. package/dist/size-rollup-style-effect.js.map +1 -1
  57. package/package.json +2 -2
  58. package/dist/es/stats/animation-count.mjs +0 -8
  59. package/dist/es/stats/animation-count.mjs.map +0 -1
package/dist/cjs/index.js CHANGED
@@ -15,12 +15,7 @@ const stepsOrder = [
15
15
  "postRender", // Compute
16
16
  ];
17
17
 
18
- const statsBuffer = {
19
- value: null,
20
- addProjectionMetrics: null,
21
- };
22
-
23
- function createRenderStep(runNextFrame, stepName) {
18
+ function createRenderStep(runNextFrame) {
24
19
  /**
25
20
  * We create and reuse two queues, one to queue jobs for the current frame
26
21
  * and one for the next. We reuse to avoid triggering GC after x frames.
@@ -42,13 +37,11 @@ function createRenderStep(runNextFrame, stepName) {
42
37
  timestamp: 0.0,
43
38
  isProcessing: false,
44
39
  };
45
- let numCalls = 0;
46
40
  function triggerCallback(callback) {
47
41
  if (toKeepAlive.has(callback)) {
48
42
  step.schedule(callback);
49
43
  runNextFrame();
50
44
  }
51
- numCalls++;
52
45
  callback(latestFrameData);
53
46
  }
54
47
  const step = {
@@ -91,13 +84,6 @@ function createRenderStep(runNextFrame, stepName) {
91
84
  nextFrame = prevFrame;
92
85
  // Execute this frame
93
86
  thisFrame.forEach(triggerCallback);
94
- /**
95
- * If we're recording stats then
96
- */
97
- if (stepName && statsBuffer.value) {
98
- statsBuffer.value.frameloop[stepName].push(numCalls);
99
- }
100
- numCalls = 0;
101
87
  // Clear the frame so no callbacks remain. This is to avoid
102
88
  // memory leaks should this render step not run for a while.
103
89
  thisFrame.clear();
@@ -122,7 +108,7 @@ function createRenderBatcher(scheduleNextBatch, allowKeepAlive) {
122
108
  };
123
109
  const flagRunNextFrame = () => (runNextFrame = true);
124
110
  const steps = stepsOrder.reduce((acc, key) => {
125
- acc[key] = createRenderStep(flagRunNextFrame, allowKeepAlive ? key : undefined);
111
+ acc[key] = createRenderStep(flagRunNextFrame);
126
112
  return acc;
127
113
  }, {});
128
114
  const { setup, read, resolveKeyframes, preUpdate, update, preRender, render, postRender, } = steps;
@@ -207,12 +193,6 @@ const time = {
207
193
  },
208
194
  };
209
195
 
210
- const activeAnimations = {
211
- layout: 0,
212
- mainThread: 0,
213
- waapi: 0,
214
- };
215
-
216
196
  const checkStringStartsWith = (token) => (key) => typeof key === "string" && key.startsWith(token);
217
197
  const isCSSVariableName =
218
198
  /*@__PURE__*/ checkStringStartsWith("--");
@@ -1414,7 +1394,6 @@ class JSAnimation extends WithPromise {
1414
1394
  this.teardown();
1415
1395
  this.options.onStop?.();
1416
1396
  };
1417
- activeAnimations.mainThread++;
1418
1397
  this.options = options;
1419
1398
  this.initAnimation();
1420
1399
  this.play();
@@ -1720,7 +1699,6 @@ class JSAnimation extends WithPromise {
1720
1699
  this.state = "idle";
1721
1700
  this.stopDriver();
1722
1701
  this.startTime = this.holdTime = null;
1723
- activeAnimations.mainThread--;
1724
1702
  }
1725
1703
  stopDriver() {
1726
1704
  if (!this.driver)
@@ -1859,8 +1837,15 @@ const transformPropOrder = [
1859
1837
  ];
1860
1838
  /**
1861
1839
  * A quick lookup for transform props.
1840
+ *
1841
+ * `pathRotation` is a transform for routing purposes (skipped from raw
1842
+ * style application, wired to the transform composite, flags transform
1843
+ * dirty) but is intentionally NOT in `transformPropOrder` — it is
1844
+ * composed onto `rotate` at the build sites, not serialized in its own
1845
+ * slot, and must stay out of the order-array consumers (parse-transform,
1846
+ * unit-conversion, keys-position).
1862
1847
  */
1863
- const transformProps = /*@__PURE__*/ (() => new Set(transformPropOrder))();
1848
+ const transformProps = /*@__PURE__*/ (() => new Set([...transformPropOrder, "pathRotation"]))();
1864
1849
 
1865
1850
  const isNumOrPxType = (v) => v === number || v === px;
1866
1851
  const transformKeys = new Set(["x", "y", "z"]);
@@ -2125,9 +2110,6 @@ function startWaapiAnimation(element, valueName, keyframes, { delay = 0, duratio
2125
2110
  */
2126
2111
  if (Array.isArray(easing))
2127
2112
  keyframeOptions.easing = easing;
2128
- if (statsBuffer.value) {
2129
- activeAnimations.waapi++;
2130
- }
2131
2113
  const options = {
2132
2114
  delay,
2133
2115
  duration,
@@ -2138,13 +2120,7 @@ function startWaapiAnimation(element, valueName, keyframes, { delay = 0, duratio
2138
2120
  };
2139
2121
  if (pseudoElement)
2140
2122
  options.pseudoElement = pseudoElement;
2141
- const animation = element.animate(keyframeOptions, options);
2142
- if (statsBuffer.value) {
2143
- animation.finished.finally(() => {
2144
- activeAnimations.waapi--;
2145
- });
2146
- }
2147
- return animation;
2123
+ return element.animate(keyframeOptions, options);
2148
2124
  }
2149
2125
 
2150
2126
  function isGenerator(type) {
@@ -2874,342 +2850,77 @@ function calcChildStagger(children, child, delayChildren, staggerChildren = 0, s
2874
2850
  }
2875
2851
 
2876
2852
  /**
2877
- * Parse Framer's special CSS variable format into a CSS token and a fallback.
2878
- *
2879
- * ```
2880
- * `var(--foo, #fff)` => [`--foo`, '#fff']
2881
- * ```
2882
- *
2883
- * @param current
2884
- */
2885
- const splitCSSVariableRegex =
2886
- // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive, as it can match a lot of words
2887
- /^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;
2888
- function parseCSSVariable(current) {
2889
- const match = splitCSSVariableRegex.exec(current);
2890
- if (!match)
2891
- return [,];
2892
- const [, token1, token2, fallback] = match;
2893
- return [`--${token1 ?? token2}`, fallback];
2894
- }
2895
- const maxDepth = 4;
2896
- function getVariableValue(current, element, depth = 1) {
2897
- motionUtils.invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`, "max-css-var-depth");
2898
- const [token, fallback] = parseCSSVariable(current);
2899
- // No CSS variable detected
2900
- if (!token)
2901
- return;
2902
- // Attempt to read this CSS variable off the element
2903
- const resolved = window.getComputedStyle(element).getPropertyValue(token);
2904
- if (resolved) {
2905
- const trimmed = resolved.trim();
2906
- return motionUtils.isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed;
2907
- }
2908
- return isCSSVariableToken(fallback)
2909
- ? getVariableValue(fallback, element, depth + 1)
2910
- : fallback;
2911
- }
2912
-
2913
- const underDampedSpring = {
2914
- type: "spring",
2915
- stiffness: 500,
2916
- damping: 25,
2917
- restSpeed: 10,
2918
- };
2919
- const criticallyDampedSpring = (target) => ({
2920
- type: "spring",
2921
- stiffness: 550,
2922
- damping: target === 0 ? 2 * Math.sqrt(550) : 30,
2923
- restSpeed: 10,
2924
- });
2925
- const keyframesTransition = {
2926
- type: "keyframes",
2927
- duration: 0.8,
2928
- };
2929
- /**
2930
- * Default easing curve is a slightly shallower version of
2931
- * the default browser easing curve.
2853
+ * Maximum time between the value of two frames, beyond which we
2854
+ * assume the velocity has since been 0.
2932
2855
  */
2933
- const ease = {
2934
- type: "keyframes",
2935
- ease: [0.25, 0.1, 0.35, 1],
2936
- duration: 0.3,
2856
+ const MAX_VELOCITY_DELTA = 30;
2857
+ const isFloat = (value) => {
2858
+ return !isNaN(parseFloat(value));
2937
2859
  };
2938
- const getDefaultTransition = (valueKey, { keyframes }) => {
2939
- if (keyframes.length > 2) {
2940
- return keyframesTransition;
2941
- }
2942
- else if (transformProps.has(valueKey)) {
2943
- return valueKey.startsWith("scale")
2944
- ? criticallyDampedSpring(keyframes[1])
2945
- : underDampedSpring;
2946
- }
2947
- return ease;
2860
+ const collectMotionValues = {
2861
+ current: undefined,
2948
2862
  };
2949
-
2950
- /**
2951
- * If `transition` has `inherit: true`, shallow-merge it with
2952
- * `parentTransition` (child keys win) and strip the `inherit` key.
2953
- * Otherwise return `transition` unchanged.
2954
- */
2955
- function resolveTransition(transition, parentTransition) {
2956
- if (transition?.inherit && parentTransition) {
2957
- const { inherit: _, ...rest } = transition;
2958
- return { ...parentTransition, ...rest };
2959
- }
2960
- return transition;
2961
- }
2962
-
2963
- function getValueTransition(transition, key) {
2964
- const valueTransition = transition?.[key] ??
2965
- transition?.["default"] ??
2966
- transition;
2967
- if (valueTransition !== transition) {
2968
- return resolveTransition(valueTransition, transition);
2969
- }
2970
- return valueTransition;
2971
- }
2972
-
2973
- const orchestrationKeys = new Set([
2974
- "when",
2975
- "delay",
2976
- "delayChildren",
2977
- "staggerChildren",
2978
- "staggerDirection",
2979
- "repeat",
2980
- "repeatType",
2981
- "repeatDelay",
2982
- "from",
2983
- "elapsed",
2984
- ]);
2985
2863
  /**
2986
- * Decide whether a transition is defined on a given Transition.
2987
- * This filters out orchestration options and returns true
2988
- * if any options are left.
2864
+ * `MotionValue` is used to track the state and velocity of motion values.
2865
+ *
2866
+ * @public
2989
2867
  */
2990
- function isTransitionDefined(transition) {
2991
- for (const key in transition) {
2992
- if (!orchestrationKeys.has(key))
2993
- return true;
2994
- }
2995
- return false;
2996
- }
2997
-
2998
- const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => {
2999
- const valueTransition = getValueTransition(transition, name) || {};
3000
- /**
3001
- * Most transition values are currently completely overwritten by value-specific
3002
- * transitions. In the future it'd be nicer to blend these transitions. But for now
3003
- * delay actually does inherit from the root transition if not value-specific.
3004
- */
3005
- const delay = valueTransition.delay || transition.delay || 0;
3006
- /**
3007
- * Elapsed isn't a public transition option but can be passed through from
3008
- * optimized appear effects in milliseconds.
3009
- */
3010
- let { elapsed = 0 } = transition;
3011
- elapsed = elapsed - motionUtils.secondsToMilliseconds(delay);
3012
- const options = {
3013
- keyframes: Array.isArray(target) ? target : [null, target],
3014
- ease: "easeOut",
3015
- velocity: value.getVelocity(),
3016
- ...valueTransition,
3017
- delay: -elapsed,
3018
- onUpdate: (v) => {
3019
- value.set(v);
3020
- valueTransition.onUpdate && valueTransition.onUpdate(v);
3021
- },
3022
- onComplete: () => {
3023
- onComplete();
3024
- valueTransition.onComplete && valueTransition.onComplete();
3025
- },
3026
- name,
3027
- motionValue: value,
3028
- element: isHandoff ? undefined : element,
3029
- };
3030
- /**
3031
- * If there's no transition defined for this value, we can generate
3032
- * unique transition settings for this value.
3033
- */
3034
- if (!isTransitionDefined(valueTransition)) {
3035
- Object.assign(options, getDefaultTransition(name, options));
3036
- }
3037
- /**
3038
- * Both WAAPI and our internal animation functions use durations
3039
- * as defined by milliseconds, while our external API defines them
3040
- * as seconds.
3041
- */
3042
- options.duration && (options.duration = motionUtils.secondsToMilliseconds(options.duration));
3043
- options.repeatDelay && (options.repeatDelay = motionUtils.secondsToMilliseconds(options.repeatDelay));
2868
+ class MotionValue {
3044
2869
  /**
3045
- * Support deprecated way to set initial value. Prefer keyframe syntax.
2870
+ * @param init - The initiating value
2871
+ * @param config - Optional configuration options
2872
+ *
2873
+ * - `transformer`: A function to transform incoming values with.
3046
2874
  */
3047
- if (options.from !== undefined) {
3048
- options.keyframes[0] = options.from;
2875
+ constructor(init, options = {}) {
2876
+ /**
2877
+ * Tracks whether this value can output a velocity. Currently this is only true
2878
+ * if the value is numerical, but we might be able to widen the scope here and support
2879
+ * other value types.
2880
+ *
2881
+ * @internal
2882
+ */
2883
+ this.canTrackVelocity = null;
2884
+ /**
2885
+ * An object containing a SubscriptionManager for each active event.
2886
+ */
2887
+ this.events = {};
2888
+ this.updateAndNotify = (v) => {
2889
+ const currentTime = time.now();
2890
+ /**
2891
+ * If we're updating the value during another frame or eventloop
2892
+ * than the previous frame, then the we set the previous frame value
2893
+ * to current.
2894
+ */
2895
+ if (this.updatedAt !== currentTime) {
2896
+ this.setPrevFrameValue();
2897
+ }
2898
+ this.prev = this.current;
2899
+ this.setCurrent(v);
2900
+ // Update update subscribers
2901
+ if (this.current !== this.prev) {
2902
+ this.events.change?.notify(this.current);
2903
+ if (this.dependents) {
2904
+ for (const dependent of this.dependents) {
2905
+ dependent.dirty();
2906
+ }
2907
+ }
2908
+ }
2909
+ };
2910
+ this.hasAnimated = false;
2911
+ this.setCurrent(init);
2912
+ this.owner = options.owner;
3049
2913
  }
3050
- let shouldSkip = false;
3051
- if (options.type === false ||
3052
- (options.duration === 0 && !options.repeatDelay)) {
3053
- makeAnimationInstant(options);
3054
- if (options.delay === 0) {
3055
- shouldSkip = true;
2914
+ setCurrent(current) {
2915
+ this.current = current;
2916
+ this.updatedAt = time.now();
2917
+ if (this.canTrackVelocity === null && current !== undefined) {
2918
+ this.canTrackVelocity = isFloat(this.current);
3056
2919
  }
3057
2920
  }
3058
- if (motionUtils.MotionGlobalConfig.instantAnimations ||
3059
- motionUtils.MotionGlobalConfig.skipAnimations ||
3060
- element?.shouldSkipAnimations ||
3061
- valueTransition.skipAnimations) {
3062
- shouldSkip = true;
3063
- makeAnimationInstant(options);
3064
- options.delay = 0;
3065
- }
3066
- /**
3067
- * If the transition type or easing has been explicitly set by the user
3068
- * then we don't want to allow flattening the animation.
3069
- */
3070
- options.allowFlatten = !valueTransition.type && !valueTransition.ease;
3071
- /**
3072
- * If we can or must skip creating the animation, and apply only
3073
- * the final keyframe, do so. We also check once keyframes are resolved but
3074
- * this early check prevents the need to create an animation at all.
3075
- */
3076
- if (shouldSkip && !isHandoff && value.get() !== undefined) {
3077
- const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition);
3078
- if (finalKeyframe !== undefined) {
3079
- frame.update(() => {
3080
- options.onUpdate(finalKeyframe);
3081
- options.onComplete();
3082
- });
3083
- return;
3084
- }
3085
- }
3086
- return valueTransition.isSync
3087
- ? new JSAnimation(options)
3088
- : new AsyncMotionValueAnimation(options);
3089
- };
3090
-
3091
- function getValueState(visualElement) {
3092
- const state = [{}, {}];
3093
- visualElement?.values.forEach((value, key) => {
3094
- state[0][key] = value.get();
3095
- state[1][key] = value.getVelocity();
3096
- });
3097
- return state;
3098
- }
3099
- function resolveVariantFromProps(props, definition, custom, visualElement) {
3100
- /**
3101
- * If the variant definition is a function, resolve.
3102
- */
3103
- if (typeof definition === "function") {
3104
- const [current, velocity] = getValueState(visualElement);
3105
- definition = definition(custom !== undefined ? custom : props.custom, current, velocity);
3106
- }
3107
- /**
3108
- * If the variant definition is a variant label, or
3109
- * the function returned a variant label, resolve.
3110
- */
3111
- if (typeof definition === "string") {
3112
- definition = props.variants && props.variants[definition];
3113
- }
3114
- /**
3115
- * At this point we've resolved both functions and variant labels,
3116
- * but the resolved variant label might itself have been a function.
3117
- * If so, resolve. This can only have returned a valid target object.
3118
- */
3119
- if (typeof definition === "function") {
3120
- const [current, velocity] = getValueState(visualElement);
3121
- definition = definition(custom !== undefined ? custom : props.custom, current, velocity);
3122
- }
3123
- return definition;
3124
- }
3125
-
3126
- function resolveVariant(visualElement, definition, custom) {
3127
- const props = visualElement.getProps();
3128
- return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, visualElement);
3129
- }
3130
-
3131
- const positionalKeys = new Set([
3132
- "width",
3133
- "height",
3134
- "top",
3135
- "left",
3136
- "right",
3137
- "bottom",
3138
- ...transformPropOrder,
3139
- ]);
3140
-
3141
- /**
3142
- * Maximum time between the value of two frames, beyond which we
3143
- * assume the velocity has since been 0.
3144
- */
3145
- const MAX_VELOCITY_DELTA = 30;
3146
- const isFloat = (value) => {
3147
- return !isNaN(parseFloat(value));
3148
- };
3149
- const collectMotionValues = {
3150
- current: undefined,
3151
- };
3152
- /**
3153
- * `MotionValue` is used to track the state and velocity of motion values.
3154
- *
3155
- * @public
3156
- */
3157
- class MotionValue {
3158
- /**
3159
- * @param init - The initiating value
3160
- * @param config - Optional configuration options
3161
- *
3162
- * - `transformer`: A function to transform incoming values with.
3163
- */
3164
- constructor(init, options = {}) {
3165
- /**
3166
- * Tracks whether this value can output a velocity. Currently this is only true
3167
- * if the value is numerical, but we might be able to widen the scope here and support
3168
- * other value types.
3169
- *
3170
- * @internal
3171
- */
3172
- this.canTrackVelocity = null;
3173
- /**
3174
- * An object containing a SubscriptionManager for each active event.
3175
- */
3176
- this.events = {};
3177
- this.updateAndNotify = (v) => {
3178
- const currentTime = time.now();
3179
- /**
3180
- * If we're updating the value during another frame or eventloop
3181
- * than the previous frame, then the we set the previous frame value
3182
- * to current.
3183
- */
3184
- if (this.updatedAt !== currentTime) {
3185
- this.setPrevFrameValue();
3186
- }
3187
- this.prev = this.current;
3188
- this.setCurrent(v);
3189
- // Update update subscribers
3190
- if (this.current !== this.prev) {
3191
- this.events.change?.notify(this.current);
3192
- if (this.dependents) {
3193
- for (const dependent of this.dependents) {
3194
- dependent.dirty();
3195
- }
3196
- }
3197
- }
3198
- };
3199
- this.hasAnimated = false;
3200
- this.setCurrent(init);
3201
- this.owner = options.owner;
3202
- }
3203
- setCurrent(current) {
3204
- this.current = current;
3205
- this.updatedAt = time.now();
3206
- if (this.canTrackVelocity === null && current !== undefined) {
3207
- this.canTrackVelocity = isFloat(this.current);
3208
- }
3209
- }
3210
- setPrevFrameValue(prevFrameValue = this.current) {
3211
- this.prevFrameValue = prevFrameValue;
3212
- this.prevUpdatedAt = this.updatedAt;
2921
+ setPrevFrameValue(prevFrameValue = this.current) {
2922
+ this.prevFrameValue = prevFrameValue;
2923
+ this.prevUpdatedAt = this.updatedAt;
3213
2924
  }
3214
2925
  /**
3215
2926
  * Adds a function that will be notified when the `MotionValue` is updated.
@@ -3384,78 +3095,524 @@ class MotionValue {
3384
3095
  parseFloat(this.prevFrameValue), delta);
3385
3096
  }
3386
3097
  /**
3387
- * Registers a new animation to control this `MotionValue`. Only one
3388
- * animation can drive a `MotionValue` at one time.
3389
- *
3390
- * ```jsx
3391
- * value.start()
3392
- * ```
3393
- *
3394
- * @param animation - A function that starts the provided animation
3098
+ * Registers a new animation to control this `MotionValue`. Only one
3099
+ * animation can drive a `MotionValue` at one time.
3100
+ *
3101
+ * ```jsx
3102
+ * value.start()
3103
+ * ```
3104
+ *
3105
+ * @param animation - A function that starts the provided animation
3106
+ */
3107
+ start(startAnimation) {
3108
+ this.stop();
3109
+ return new Promise((resolve) => {
3110
+ this.hasAnimated = true;
3111
+ this.animation = startAnimation(resolve);
3112
+ if (this.events.animationStart) {
3113
+ this.events.animationStart.notify();
3114
+ }
3115
+ }).then(() => {
3116
+ if (this.events.animationComplete) {
3117
+ this.events.animationComplete.notify();
3118
+ }
3119
+ this.clearAnimation();
3120
+ });
3121
+ }
3122
+ /**
3123
+ * Stop the currently active animation.
3124
+ *
3125
+ * @public
3126
+ */
3127
+ stop() {
3128
+ if (this.animation) {
3129
+ this.animation.stop();
3130
+ if (this.events.animationCancel) {
3131
+ this.events.animationCancel.notify();
3132
+ }
3133
+ }
3134
+ this.clearAnimation();
3135
+ }
3136
+ /**
3137
+ * Returns `true` if this value is currently animating.
3138
+ *
3139
+ * @public
3140
+ */
3141
+ isAnimating() {
3142
+ return !!this.animation;
3143
+ }
3144
+ clearAnimation() {
3145
+ delete this.animation;
3146
+ }
3147
+ /**
3148
+ * Destroy and clean up subscribers to this `MotionValue`.
3149
+ *
3150
+ * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
3151
+ * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
3152
+ * created a `MotionValue` via the `motionValue` function.
3153
+ *
3154
+ * @public
3155
+ */
3156
+ destroy() {
3157
+ this.dependents?.clear();
3158
+ this.events.destroy?.notify();
3159
+ this.clearListeners();
3160
+ this.stop();
3161
+ if (this.stopPassiveEffect) {
3162
+ this.stopPassiveEffect();
3163
+ }
3164
+ }
3165
+ }
3166
+ function motionValue(init, options) {
3167
+ return new MotionValue(init, options);
3168
+ }
3169
+
3170
+ /**
3171
+ * If `transition` has `inherit: true`, shallow-merge it with
3172
+ * `parentTransition` (child keys win) and strip the `inherit` key.
3173
+ * Otherwise return `transition` unchanged.
3174
+ */
3175
+ function resolveTransition(transition, parentTransition) {
3176
+ if (transition?.inherit && parentTransition) {
3177
+ const { inherit: _, ...rest } = transition;
3178
+ return { ...parentTransition, ...rest };
3179
+ }
3180
+ return transition;
3181
+ }
3182
+
3183
+ function getValueTransition(transition, key) {
3184
+ const valueTransition = transition?.[key] ??
3185
+ transition?.["default"] ??
3186
+ transition;
3187
+ if (valueTransition !== transition) {
3188
+ return resolveTransition(valueTransition, transition);
3189
+ }
3190
+ return valueTransition;
3191
+ }
3192
+
3193
+ const underDampedSpring = {
3194
+ type: "spring",
3195
+ stiffness: 500,
3196
+ damping: 25,
3197
+ restSpeed: 10,
3198
+ };
3199
+ const criticallyDampedSpring = (target) => ({
3200
+ type: "spring",
3201
+ stiffness: 550,
3202
+ damping: target === 0 ? 2 * Math.sqrt(550) : 30,
3203
+ restSpeed: 10,
3204
+ });
3205
+ const keyframesTransition = {
3206
+ type: "keyframes",
3207
+ duration: 0.8,
3208
+ };
3209
+ /**
3210
+ * Default easing curve is a slightly shallower version of
3211
+ * the default browser easing curve.
3212
+ */
3213
+ const ease = {
3214
+ type: "keyframes",
3215
+ ease: [0.25, 0.1, 0.35, 1],
3216
+ duration: 0.3,
3217
+ };
3218
+ const getDefaultTransition = (valueKey, { keyframes }) => {
3219
+ if (keyframes.length > 2) {
3220
+ return keyframesTransition;
3221
+ }
3222
+ else if (transformProps.has(valueKey)) {
3223
+ return valueKey.startsWith("scale")
3224
+ ? criticallyDampedSpring(keyframes[1])
3225
+ : underDampedSpring;
3226
+ }
3227
+ return ease;
3228
+ };
3229
+
3230
+ const orchestrationKeys = new Set([
3231
+ "when",
3232
+ "delay",
3233
+ "delayChildren",
3234
+ "staggerChildren",
3235
+ "staggerDirection",
3236
+ "repeat",
3237
+ "repeatType",
3238
+ "repeatDelay",
3239
+ "from",
3240
+ "elapsed",
3241
+ ]);
3242
+ /**
3243
+ * Decide whether a transition is defined on a given Transition.
3244
+ * This filters out orchestration options and returns true
3245
+ * if any options are left.
3246
+ */
3247
+ function isTransitionDefined(transition) {
3248
+ for (const key in transition) {
3249
+ if (!orchestrationKeys.has(key))
3250
+ return true;
3251
+ }
3252
+ return false;
3253
+ }
3254
+
3255
+ const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => {
3256
+ const valueTransition = getValueTransition(transition, name) || {};
3257
+ /**
3258
+ * Most transition values are currently completely overwritten by value-specific
3259
+ * transitions. In the future it'd be nicer to blend these transitions. But for now
3260
+ * delay actually does inherit from the root transition if not value-specific.
3261
+ */
3262
+ const delay = valueTransition.delay || transition.delay || 0;
3263
+ /**
3264
+ * Elapsed isn't a public transition option but can be passed through from
3265
+ * optimized appear effects in milliseconds.
3266
+ */
3267
+ let { elapsed = 0 } = transition;
3268
+ elapsed = elapsed - motionUtils.secondsToMilliseconds(delay);
3269
+ const options = {
3270
+ keyframes: Array.isArray(target) ? target : [null, target],
3271
+ ease: "easeOut",
3272
+ velocity: value.getVelocity(),
3273
+ ...valueTransition,
3274
+ delay: -elapsed,
3275
+ onUpdate: (v) => {
3276
+ value.set(v);
3277
+ valueTransition.onUpdate && valueTransition.onUpdate(v);
3278
+ },
3279
+ onComplete: () => {
3280
+ onComplete();
3281
+ valueTransition.onComplete && valueTransition.onComplete();
3282
+ },
3283
+ name,
3284
+ motionValue: value,
3285
+ element: isHandoff ? undefined : element,
3286
+ };
3287
+ /**
3288
+ * If there's no transition defined for this value, we can generate
3289
+ * unique transition settings for this value.
3290
+ */
3291
+ if (!isTransitionDefined(valueTransition)) {
3292
+ Object.assign(options, getDefaultTransition(name, options));
3293
+ }
3294
+ /**
3295
+ * Both WAAPI and our internal animation functions use durations
3296
+ * as defined by milliseconds, while our external API defines them
3297
+ * as seconds.
3298
+ */
3299
+ options.duration && (options.duration = motionUtils.secondsToMilliseconds(options.duration));
3300
+ options.repeatDelay && (options.repeatDelay = motionUtils.secondsToMilliseconds(options.repeatDelay));
3301
+ /**
3302
+ * Support deprecated way to set initial value. Prefer keyframe syntax.
3303
+ */
3304
+ if (options.from !== undefined) {
3305
+ options.keyframes[0] = options.from;
3306
+ }
3307
+ let shouldSkip = false;
3308
+ if (options.type === false ||
3309
+ (options.duration === 0 && !options.repeatDelay)) {
3310
+ makeAnimationInstant(options);
3311
+ if (options.delay === 0) {
3312
+ shouldSkip = true;
3313
+ }
3314
+ }
3315
+ if (motionUtils.MotionGlobalConfig.instantAnimations ||
3316
+ motionUtils.MotionGlobalConfig.skipAnimations ||
3317
+ element?.shouldSkipAnimations ||
3318
+ valueTransition.skipAnimations) {
3319
+ shouldSkip = true;
3320
+ makeAnimationInstant(options);
3321
+ options.delay = 0;
3322
+ }
3323
+ /**
3324
+ * If the transition type or easing has been explicitly set by the user
3325
+ * then we don't want to allow flattening the animation.
3326
+ */
3327
+ options.allowFlatten = !valueTransition.type && !valueTransition.ease;
3328
+ /**
3329
+ * If we can or must skip creating the animation, and apply only
3330
+ * the final keyframe, do so. We also check once keyframes are resolved but
3331
+ * this early check prevents the need to create an animation at all.
3395
3332
  */
3396
- start(startAnimation) {
3397
- this.stop();
3398
- return new Promise((resolve) => {
3399
- this.hasAnimated = true;
3400
- this.animation = startAnimation(resolve);
3401
- if (this.events.animationStart) {
3402
- this.events.animationStart.notify();
3333
+ if (shouldSkip && !isHandoff && value.get() !== undefined) {
3334
+ const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition);
3335
+ if (finalKeyframe !== undefined) {
3336
+ frame.update(() => {
3337
+ options.onUpdate(finalKeyframe);
3338
+ options.onComplete();
3339
+ });
3340
+ return;
3341
+ }
3342
+ }
3343
+ return valueTransition.isSync
3344
+ ? new JSAnimation(options)
3345
+ : new AsyncMotionValueAnimation(options);
3346
+ };
3347
+
3348
+ const MIN_LAYOUT_DISTANCE = 20;
3349
+ function bezierPoint(t, origin, control, target) {
3350
+ const inv = 1 - t;
3351
+ return inv * inv * origin + 2 * inv * t * control + t * t * target;
3352
+ }
3353
+ function bezierTangentAngle(t, originX, controlX, targetX, originY, controlY, targetY) {
3354
+ const dx = 2 * (1 - t) * (controlX - originX) + 2 * t * (targetX - controlX);
3355
+ const dy = 2 * (1 - t) * (controlY - originY) + 2 * t * (targetY - controlY);
3356
+ return Math.atan2(dy, dx) * (180 / Math.PI);
3357
+ }
3358
+ function computeArcControlPoint(fromX, fromY, toX, toY, strength, peak) {
3359
+ const deltaX = toX - fromX;
3360
+ const deltaY = toY - fromY;
3361
+ const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
3362
+ if (distance > 0) {
3363
+ const normalPerpX = -deltaY / distance;
3364
+ const normalPerpY = deltaX / distance;
3365
+ const desiredHeight = strength * distance;
3366
+ return {
3367
+ x: fromX + deltaX * peak + normalPerpX * desiredHeight,
3368
+ y: fromY + deltaY * peak + normalPerpY * desiredHeight,
3369
+ };
3370
+ }
3371
+ return { x: fromX, y: fromY };
3372
+ }
3373
+ /**
3374
+ * The pure sampling factory: `(from, to) => (t) => point`. Internal —
3375
+ * used by {@link arc} and the unit tests. Not part of the public surface.
3376
+ */
3377
+ function createArcPath({ strength = 0.5, peak = 0.5, direction, rotate = false, } = {}) {
3378
+ const rotationScale = rotate === true ? 1 : typeof rotate === "number" ? rotate : 0;
3379
+ // Auto-direction only: persists across calls to flip the bulge back
3380
+ // onto the same screen side when the dominant axis changes between
3381
+ // calls. Reuse the factory (module scope / useMemo) to keep this alive.
3382
+ let prevBulgeSign;
3383
+ const createInterpolator = (from, to) => {
3384
+ const dx = to.x - from.x;
3385
+ const dy = to.y - from.y;
3386
+ let signed;
3387
+ if (direction === "cw") {
3388
+ signed = -strength;
3389
+ }
3390
+ else if (direction === "ccw") {
3391
+ signed = strength;
3392
+ }
3393
+ else {
3394
+ const dom = Math.abs(dx) >= Math.abs(dy) ? dx : dy;
3395
+ signed = dom < 0 ? -strength : strength;
3396
+ }
3397
+ let control = computeArcControlPoint(from.x, from.y, to.x, to.y, signed, peak);
3398
+ if (direction === undefined) {
3399
+ const isVertical = Math.abs(dx) < Math.abs(dy);
3400
+ const midX = from.x + dx * peak;
3401
+ const midY = from.y + dy * peak;
3402
+ const bulgeSign = isVertical
3403
+ ? Math.sign(control.x - midX)
3404
+ : Math.sign(control.y - midY);
3405
+ if (prevBulgeSign !== undefined &&
3406
+ bulgeSign !== 0 &&
3407
+ bulgeSign !== prevBulgeSign) {
3408
+ signed = -signed;
3409
+ control = computeArcControlPoint(from.x, from.y, to.x, to.y, signed, peak);
3410
+ }
3411
+ else if (bulgeSign !== 0) {
3412
+ prevBulgeSign = bulgeSign;
3413
+ }
3414
+ }
3415
+ const tangent0 = rotationScale
3416
+ ? bezierTangentAngle(0, from.x, control.x, to.x, from.y, control.y, to.y)
3417
+ : 0;
3418
+ const tangent1 = rotationScale
3419
+ ? bezierTangentAngle(1, from.x, control.x, to.x, from.y, control.y, to.y)
3420
+ : 0;
3421
+ const tangentDelta = rotationScale
3422
+ ? motionUtils.wrap(-180, 180, tangent1 - tangent0)
3423
+ : 0;
3424
+ return (t) => {
3425
+ const out = {
3426
+ x: bezierPoint(t, from.x, control.x, to.x),
3427
+ y: bezierPoint(t, from.y, control.y, to.y),
3428
+ };
3429
+ if (rotationScale) {
3430
+ const raw = bezierTangentAngle(t, from.x, control.x, to.x, from.y, control.y, to.y);
3431
+ const baseline = tangent0 + tangentDelta * t;
3432
+ out.rotate = motionUtils.wrap(-180, 180, raw - baseline) * rotationScale;
3403
3433
  }
3404
- }).then(() => {
3405
- if (this.events.animationComplete) {
3406
- this.events.animationComplete.notify();
3434
+ return out;
3435
+ };
3436
+ };
3437
+ return createInterpolator;
3438
+ }
3439
+ /**
3440
+ * Creates a curved path for `transition.path`:
3441
+ *
3442
+ * ```ts
3443
+ * <motion.div animate={{ x: 200, y: 100 }} transition={{ path: arc() }} />
3444
+ * ```
3445
+ *
3446
+ * Reuse the returned value (module scope / useMemo / useRef) so its
3447
+ * continuity closure survives re-renders — a fresh `arc()` has no memory.
3448
+ */
3449
+ function arc(options = {}) {
3450
+ const sample = createArcPath(options);
3451
+ const path = {
3452
+ interpolateProjection(delta) {
3453
+ // `from` is the current translate offset (carries any in-flight
3454
+ // displacement when interrupted); `to` is the new layout origin.
3455
+ // The distance floor avoids visible wobble on tiny shifts.
3456
+ const tx = delta.x.translate;
3457
+ const ty = delta.y.translate;
3458
+ if (Math.sqrt(tx * tx + ty * ty) < MIN_LAYOUT_DISTANCE) {
3459
+ return undefined;
3407
3460
  }
3408
- this.clearAnimation();
3409
- });
3461
+ return sample({ x: tx, y: ty }, { x: 0, y: 0 });
3462
+ },
3463
+ animateVisualElement(visualElement, target, transition, delay, animations) {
3464
+ if (!("x" in target || "y" in target))
3465
+ return;
3466
+ const xValue = visualElement.getValue("x", visualElement.latestValues["x"] ?? 0);
3467
+ const yValue = visualElement.getValue("y", visualElement.latestValues["y"] ?? 0);
3468
+ const xRaw = target.x;
3469
+ const yRaw = target.y;
3470
+ const xFrom = (Array.isArray(xRaw) && xRaw[0] != null
3471
+ ? xRaw[0]
3472
+ : xValue?.get()) ?? 0;
3473
+ const yFrom = (Array.isArray(yRaw) && yRaw[0] != null
3474
+ ? yRaw[0]
3475
+ : yValue?.get()) ?? 0;
3476
+ const xTo = (Array.isArray(xRaw)
3477
+ ? xRaw[xRaw.length - 1]
3478
+ : xRaw ?? xFrom);
3479
+ const yTo = (Array.isArray(yRaw)
3480
+ ? yRaw[yRaw.length - 1]
3481
+ : yRaw ?? yFrom);
3482
+ // Interruption needs no flag: x/y already hold the displaced
3483
+ // mid-arc position, so xFrom/yFrom carry the continuity geometry.
3484
+ const interpolate = sample({ x: xFrom, y: yFrom }, { x: xTo, y: yTo });
3485
+ // Drive a dedicated `pathRotation` value (composed onto `rotate`
3486
+ // at the build sites) rather than `rotate` itself, so a
3487
+ // concurrent rotate animation composes and nothing accumulates
3488
+ // on interrupt.
3489
+ const pathRotationValue = interpolate(0).rotate !== undefined
3490
+ ? visualElement.getValue("pathRotation", 0)
3491
+ : undefined;
3492
+ const pathTransition = {
3493
+ delay,
3494
+ ...getValueTransition(transition || {}, "x"),
3495
+ };
3496
+ delete pathTransition.path;
3497
+ const progress = motionValue(0);
3498
+ progress.start(animateMotionValue("", progress, [0, 1000], {
3499
+ ...pathTransition,
3500
+ isSync: true,
3501
+ velocity: 0,
3502
+ onUpdate: (latest) => {
3503
+ const point = interpolate(latest / 1000);
3504
+ xValue?.set(point.x);
3505
+ yValue?.set(point.y);
3506
+ if (pathRotationValue && point.rotate !== undefined) {
3507
+ pathRotationValue.set(point.rotate);
3508
+ }
3509
+ },
3510
+ onComplete: () => {
3511
+ xValue?.set(xTo);
3512
+ yValue?.set(yTo);
3513
+ pathRotationValue?.set(0);
3514
+ },
3515
+ // Interrupt/cancel must clear our additive contribution
3516
+ // so it can't linger on top of the user's `rotate`.
3517
+ onStop: () => pathRotationValue?.set(0),
3518
+ onCancel: () => pathRotationValue?.set(0),
3519
+ }));
3520
+ if (progress.animation)
3521
+ animations.push(progress.animation);
3522
+ delete target.x;
3523
+ delete target.y;
3524
+ },
3525
+ };
3526
+ return path;
3527
+ }
3528
+
3529
+ /**
3530
+ * Parse Framer's special CSS variable format into a CSS token and a fallback.
3531
+ *
3532
+ * ```
3533
+ * `var(--foo, #fff)` => [`--foo`, '#fff']
3534
+ * ```
3535
+ *
3536
+ * @param current
3537
+ */
3538
+ const splitCSSVariableRegex =
3539
+ // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive, as it can match a lot of words
3540
+ /^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;
3541
+ function parseCSSVariable(current) {
3542
+ const match = splitCSSVariableRegex.exec(current);
3543
+ if (!match)
3544
+ return [,];
3545
+ const [, token1, token2, fallback] = match;
3546
+ return [`--${token1 ?? token2}`, fallback];
3547
+ }
3548
+ const maxDepth = 4;
3549
+ function getVariableValue(current, element, depth = 1) {
3550
+ motionUtils.invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`, "max-css-var-depth");
3551
+ const [token, fallback] = parseCSSVariable(current);
3552
+ // No CSS variable detected
3553
+ if (!token)
3554
+ return;
3555
+ // Attempt to read this CSS variable off the element
3556
+ const resolved = window.getComputedStyle(element).getPropertyValue(token);
3557
+ if (resolved) {
3558
+ const trimmed = resolved.trim();
3559
+ return motionUtils.isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed;
3410
3560
  }
3561
+ return isCSSVariableToken(fallback)
3562
+ ? getVariableValue(fallback, element, depth + 1)
3563
+ : fallback;
3564
+ }
3565
+
3566
+ function getValueState(visualElement) {
3567
+ const state = [{}, {}];
3568
+ visualElement?.values.forEach((value, key) => {
3569
+ state[0][key] = value.get();
3570
+ state[1][key] = value.getVelocity();
3571
+ });
3572
+ return state;
3573
+ }
3574
+ function resolveVariantFromProps(props, definition, custom, visualElement) {
3411
3575
  /**
3412
- * Stop the currently active animation.
3413
- *
3414
- * @public
3576
+ * If the variant definition is a function, resolve.
3415
3577
  */
3416
- stop() {
3417
- if (this.animation) {
3418
- this.animation.stop();
3419
- if (this.events.animationCancel) {
3420
- this.events.animationCancel.notify();
3421
- }
3422
- }
3423
- this.clearAnimation();
3578
+ if (typeof definition === "function") {
3579
+ const [current, velocity] = getValueState(visualElement);
3580
+ definition = definition(custom !== undefined ? custom : props.custom, current, velocity);
3424
3581
  }
3425
3582
  /**
3426
- * Returns `true` if this value is currently animating.
3427
- *
3428
- * @public
3583
+ * If the variant definition is a variant label, or
3584
+ * the function returned a variant label, resolve.
3429
3585
  */
3430
- isAnimating() {
3431
- return !!this.animation;
3432
- }
3433
- clearAnimation() {
3434
- delete this.animation;
3586
+ if (typeof definition === "string") {
3587
+ definition = props.variants && props.variants[definition];
3435
3588
  }
3436
3589
  /**
3437
- * Destroy and clean up subscribers to this `MotionValue`.
3438
- *
3439
- * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
3440
- * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
3441
- * created a `MotionValue` via the `motionValue` function.
3442
- *
3443
- * @public
3590
+ * At this point we've resolved both functions and variant labels,
3591
+ * but the resolved variant label might itself have been a function.
3592
+ * If so, resolve. This can only have returned a valid target object.
3444
3593
  */
3445
- destroy() {
3446
- this.dependents?.clear();
3447
- this.events.destroy?.notify();
3448
- this.clearListeners();
3449
- this.stop();
3450
- if (this.stopPassiveEffect) {
3451
- this.stopPassiveEffect();
3452
- }
3594
+ if (typeof definition === "function") {
3595
+ const [current, velocity] = getValueState(visualElement);
3596
+ definition = definition(custom !== undefined ? custom : props.custom, current, velocity);
3453
3597
  }
3598
+ return definition;
3454
3599
  }
3455
- function motionValue(init, options) {
3456
- return new MotionValue(init, options);
3600
+
3601
+ function resolveVariant(visualElement, definition, custom) {
3602
+ const props = visualElement.getProps();
3603
+ return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, visualElement);
3457
3604
  }
3458
3605
 
3606
+ const positionalKeys = new Set([
3607
+ "width",
3608
+ "height",
3609
+ "top",
3610
+ "left",
3611
+ "right",
3612
+ "bottom",
3613
+ ...transformPropOrder,
3614
+ ]);
3615
+
3459
3616
  const isKeyframesTarget = (v) => {
3460
3617
  return Array.isArray(v);
3461
3618
  };
@@ -3544,6 +3701,11 @@ function animateTarget(visualElement, targetAndTransition, { delay = 0, transiti
3544
3701
  const animationTypeState = type &&
3545
3702
  visualElement.animationState &&
3546
3703
  visualElement.animationState.getState()[type];
3704
+ const path = transition?.path;
3705
+ if (path) {
3706
+ // path mutates `target` to claim x/y; loop below skips them.
3707
+ path.animateVisualElement(visualElement, target, transition, delay, animations);
3708
+ }
3547
3709
  for (const key in target) {
3548
3710
  const value = visualElement.getValue(key, visualElement.latestValues[key] ?? null);
3549
3711
  const valueTarget = target[key];
@@ -3762,6 +3924,12 @@ const int = {
3762
3924
 
3763
3925
  const transformValueTypes = {
3764
3926
  rotate: degrees,
3927
+ /**
3928
+ * Internal channel for `transition.path` orientToPath. Composed onto
3929
+ * `rotate` at the transform-build sites so the user's `rotate` is
3930
+ * never read or overwritten. Not part of `transformPropOrder`.
3931
+ */
3932
+ pathRotation: degrees,
3765
3933
  rotateX: degrees,
3766
3934
  rotateY: degrees,
3767
3935
  rotateZ: degrees,
@@ -4313,6 +4481,15 @@ function buildTransform$1(state) {
4313
4481
  transform += `${transformName}(${value}) `;
4314
4482
  }
4315
4483
  }
4484
+ // See build-transform.ts: additive `rotate()` so user `rotate` isn't
4485
+ // clobbered. Not a `transformPropOrder` slot.
4486
+ const pathRotation = state.latest.pathRotation;
4487
+ if (pathRotation) {
4488
+ transformIsDefault = false;
4489
+ transform += `rotate(${typeof pathRotation === "number"
4490
+ ? `${pathRotation}deg`
4491
+ : pathRotation}) `;
4492
+ }
4316
4493
  return transformIsDefault ? "none" : transform.trim();
4317
4494
  }
4318
4495
 
@@ -4653,9 +4830,16 @@ function press(targetOrSelector, onPressStart, options = {}) {
4653
4830
  claimedPointerDownEvents.add(startEvent);
4654
4831
  }
4655
4832
  const onPressEnd = onPressStart(target, startEvent);
4833
+ /**
4834
+ * End listeners run in the capture phase so a descendant calling
4835
+ * stopPropagation() in its own pointerup handler can't prevent the
4836
+ * press gesture from ending. This also keeps the gesture-end
4837
+ * ordering consistent with the drag gesture. See #2794.
4838
+ */
4839
+ const endEventOptions = { ...eventOptions, capture: true };
4656
4840
  const onPointerEnd = (endEvent, success) => {
4657
- window.removeEventListener("pointerup", onPointerUp);
4658
- window.removeEventListener("pointercancel", onPointerCancel);
4841
+ window.removeEventListener("pointerup", onPointerUp, endEventOptions);
4842
+ window.removeEventListener("pointercancel", onPointerCancel, endEventOptions);
4659
4843
  if (isPressing.has(target)) {
4660
4844
  isPressing.delete(target);
4661
4845
  }
@@ -4675,8 +4859,8 @@ function press(targetOrSelector, onPressStart, options = {}) {
4675
4859
  const onPointerCancel = (cancelEvent) => {
4676
4860
  onPointerEnd(cancelEvent, false);
4677
4861
  };
4678
- window.addEventListener("pointerup", onPointerUp, eventOptions);
4679
- window.addEventListener("pointercancel", onPointerCancel, eventOptions);
4862
+ window.addEventListener("pointerup", onPointerUp, endEventOptions);
4863
+ window.addEventListener("pointercancel", onPointerCancel, endEventOptions);
4680
4864
  };
4681
4865
  targets.forEach((target) => {
4682
4866
  const pointerDownTarget = options.useGlobalTarget ? window : target;
@@ -4815,116 +4999,34 @@ function observeTimeline(update, timeline) {
4815
4999
  return () => cancelFrame(onFrame);
4816
5000
  }
4817
5001
 
4818
- function record() {
4819
- const { value } = statsBuffer;
4820
- if (value === null) {
4821
- cancelFrame(record);
4822
- return;
4823
- }
4824
- value.frameloop.rate.push(frameData.delta);
4825
- value.animations.mainThread.push(activeAnimations.mainThread);
4826
- value.animations.waapi.push(activeAnimations.waapi);
4827
- value.animations.layout.push(activeAnimations.layout);
4828
- }
4829
- function mean(values) {
4830
- return values.reduce((acc, value) => acc + value, 0) / values.length;
4831
- }
4832
- function summarise(values, calcAverage = mean) {
4833
- if (values.length === 0) {
4834
- return {
4835
- min: 0,
4836
- max: 0,
4837
- avg: 0,
4838
- };
4839
- }
4840
- return {
4841
- min: Math.min(...values),
4842
- max: Math.max(...values),
4843
- avg: calcAverage(values),
4844
- };
4845
- }
4846
- const msToFps = (ms) => Math.round(1000 / ms);
5002
+ const statsBuffer = {
5003
+ value: null,
5004
+ addProjectionMetrics: null,
5005
+ };
5006
+
4847
5007
  function clearStatsBuffer() {
4848
5008
  statsBuffer.value = null;
4849
5009
  statsBuffer.addProjectionMetrics = null;
4850
5010
  }
4851
- function reportStats() {
4852
- const { value } = statsBuffer;
4853
- if (!value) {
4854
- throw new Error("Stats are not being measured");
4855
- }
4856
- clearStatsBuffer();
4857
- cancelFrame(record);
4858
- const summary = {
4859
- frameloop: {
4860
- setup: summarise(value.frameloop.setup),
4861
- rate: summarise(value.frameloop.rate),
4862
- read: summarise(value.frameloop.read),
4863
- resolveKeyframes: summarise(value.frameloop.resolveKeyframes),
4864
- preUpdate: summarise(value.frameloop.preUpdate),
4865
- update: summarise(value.frameloop.update),
4866
- preRender: summarise(value.frameloop.preRender),
4867
- render: summarise(value.frameloop.render),
4868
- postRender: summarise(value.frameloop.postRender),
4869
- },
4870
- animations: {
4871
- mainThread: summarise(value.animations.mainThread),
4872
- waapi: summarise(value.animations.waapi),
4873
- layout: summarise(value.animations.layout),
4874
- },
4875
- layoutProjection: {
4876
- nodes: summarise(value.layoutProjection.nodes),
4877
- calculatedTargetDeltas: summarise(value.layoutProjection.calculatedTargetDeltas),
4878
- calculatedProjections: summarise(value.layoutProjection.calculatedProjections),
4879
- },
4880
- };
4881
- /**
4882
- * Convert the rate to FPS
4883
- */
4884
- const { rate } = summary.frameloop;
4885
- rate.min = msToFps(rate.min);
4886
- rate.max = msToFps(rate.max);
4887
- rate.avg = msToFps(rate.avg);
4888
- [rate.min, rate.max] = [rate.max, rate.min];
4889
- return summary;
4890
- }
4891
5011
  function recordStats() {
4892
5012
  if (statsBuffer.value) {
4893
5013
  clearStatsBuffer();
4894
5014
  throw new Error("Stats are already being measured");
4895
5015
  }
4896
- const newStatsBuffer = statsBuffer;
4897
- newStatsBuffer.value = {
4898
- frameloop: {
4899
- setup: [],
4900
- rate: [],
4901
- read: [],
4902
- resolveKeyframes: [],
4903
- preUpdate: [],
4904
- update: [],
4905
- preRender: [],
4906
- render: [],
4907
- postRender: [],
4908
- },
4909
- animations: {
4910
- mainThread: [],
4911
- waapi: [],
4912
- layout: [],
4913
- },
5016
+ const buffer = statsBuffer;
5017
+ buffer.value = {
4914
5018
  layoutProjection: {
4915
5019
  nodes: [],
4916
5020
  calculatedTargetDeltas: [],
4917
5021
  calculatedProjections: [],
4918
5022
  },
4919
5023
  };
4920
- newStatsBuffer.addProjectionMetrics = (metrics) => {
4921
- const { layoutProjection } = newStatsBuffer.value;
5024
+ buffer.addProjectionMetrics = (metrics) => {
5025
+ const { layoutProjection } = buffer.value;
4922
5026
  layoutProjection.nodes.push(metrics.nodes);
4923
5027
  layoutProjection.calculatedTargetDeltas.push(metrics.calculatedTargetDeltas);
4924
5028
  layoutProjection.calculatedProjections.push(metrics.calculatedProjections);
4925
5029
  };
4926
- frame.postRender(record, true);
4927
- return reportStats;
4928
5030
  }
4929
5031
 
4930
5032
  /**
@@ -5210,14 +5312,126 @@ const valueTypes = [...dimensionValueTypes, color, complex];
5210
5312
  */
5211
5313
  const findValueType = (v) => valueTypes.find(testValueType(v));
5212
5314
 
5315
+ let nameCount = 0;
5316
+ /**
5317
+ * Generated names live in their own namespace so we can tell a name we own
5318
+ * (and must clean up) from an author-defined one - and so a stale generated
5319
+ * name left behind by an interrupted transition is re-owned, not mistaken for
5320
+ * the author's and leaked.
5321
+ */
5322
+ const generatedName = () => `motion-view-${nameCount++}`;
5323
+ const isGeneratedName = (name) => name.startsWith("motion-view-");
5324
+ /**
5325
+ * Tag a captured element with a `view-transition-class` so authors can target
5326
+ * its generated layer from CSS (e.g. `::view-transition-group(.hero)`) without
5327
+ * the opaque generated name. Tracked in `classed` - separate from the generated
5328
+ * names in `assigned` - so cleanup removes the class without ever stripping an
5329
+ * author's own inline `view-transition-name`.
5330
+ */
5331
+ function tagClass(element, className, classed) {
5332
+ if (!className)
5333
+ return;
5334
+ element.style?.setProperty("view-transition-class", className);
5335
+ classed.push(element);
5336
+ }
5337
+ /**
5338
+ * Resolve a selector/Element to elements and ensure each one carries a
5339
+ * `view-transition-name` we can target from script.
5340
+ *
5341
+ * Author-defined names are reused as-is. Elements that are unnamed (or use
5342
+ * the browser's `auto`/`match-element`, whose generated name is not exposed
5343
+ * to script) are given a unique generated name, set inline so it's captured,
5344
+ * and tracked in `assigned` for later cleanup.
5345
+ *
5346
+ * `registry` maps each Element to its name so the same element keeps its name
5347
+ * across both captures (before and after the update), which is what allows a
5348
+ * persistent element to animate as a single `group` layer.
5349
+ */
5350
+ function assignViewTransitionNames(definition, registry, assigned, forcedNames, className, classed = []) {
5351
+ const elements = resolveElements(definition);
5352
+ /**
5353
+ * The new end of a paired morph: give each element the matching name from
5354
+ * the old end (by index) so the two share one layer and morph. If the new
5355
+ * end resolves to *more* elements than the old end named, the extras have no
5356
+ * counterpart - give them a fresh name so they animate as newcomers rather
5357
+ * than being silently left unnamed. We return the names actually assigned
5358
+ * (sized to the resolved elements), not the raw `forcedNames`, so stagger
5359
+ * totals and the layer set stay in step with what's on the page.
5360
+ */
5361
+ if (forcedNames) {
5362
+ return elements.map((element, i) => {
5363
+ const existing = registry.get(element);
5364
+ if (existing)
5365
+ return existing;
5366
+ const name = forcedNames[i] ?? generatedName();
5367
+ element.style?.setProperty("view-transition-name", name);
5368
+ assigned.push(element);
5369
+ registry.set(element, name);
5370
+ tagClass(element, className, classed);
5371
+ return name;
5372
+ });
5373
+ }
5374
+ /**
5375
+ * Read every current name up front, before assigning any. Interleaving the
5376
+ * reads with the inline `setProperty` writes below would dirty styles
5377
+ * between reads and force a style recalc per element; batching the reads
5378
+ * keeps it to one. Elements already in the registry keep their name and
5379
+ * need no read.
5380
+ */
5381
+ const currentNames = elements.map((element) => registry.has(element)
5382
+ ? undefined
5383
+ : getComputedStyle(element).getPropertyValue("view-transition-name"));
5384
+ return elements.map((element, i) => {
5385
+ const existing = registry.get(element);
5386
+ if (existing)
5387
+ return existing;
5388
+ const current = currentNames[i];
5389
+ let name;
5390
+ if (current &&
5391
+ current !== "none" &&
5392
+ current !== "auto" &&
5393
+ current !== "match-element" &&
5394
+ !isGeneratedName(current)) {
5395
+ /**
5396
+ * The author already named this layer - target it as-is and leave
5397
+ * it to them to clean up. `auto`/`match-element` are overridden
5398
+ * because their generated name is not exposed to script, and a
5399
+ * stale `motion-view-*` (e.g. left by an interrupted transition) is
5400
+ * re-owned rather than adopted as an author name and leaked.
5401
+ */
5402
+ name = current;
5403
+ }
5404
+ else {
5405
+ name = generatedName();
5406
+ element.style?.setProperty("view-transition-name", name);
5407
+ assigned.push(element);
5408
+ }
5409
+ registry.set(element, name);
5410
+ tagClass(element, className, classed);
5411
+ return name;
5412
+ });
5413
+ }
5414
+ /**
5415
+ * Remove the `view-transition-name`s we generated and the
5416
+ * `view-transition-class`es we applied. Author-defined names are never touched
5417
+ * (they're not in `assigned`). Safe to call more than once (e.g. on both a
5418
+ * finished and an interrupted transition).
5419
+ */
5420
+ function releaseViewTransitionNames(assigned, classed = []) {
5421
+ for (const element of assigned) {
5422
+ element.style?.removeProperty("view-transition-name");
5423
+ }
5424
+ for (const element of classed) {
5425
+ element.style?.removeProperty("view-transition-class");
5426
+ }
5427
+ }
5428
+
5213
5429
  function chooseLayerType(valueName) {
5214
5430
  if (valueName === "layout")
5215
5431
  return "group";
5216
5432
  if (valueName === "enter" || valueName === "new")
5217
5433
  return "new";
5218
- if (valueName === "exit" || valueName === "old")
5219
- return "old";
5220
- return "group";
5434
+ return "old";
5221
5435
  }
5222
5436
 
5223
5437
  let pendingRules = {};
@@ -5252,21 +5466,21 @@ const css = {
5252
5466
  };
5253
5467
 
5254
5468
  function getViewAnimationLayerInfo(pseudoElement) {
5255
- const match = pseudoElement.match(/::view-transition-(old|new|group|image-pair)\((.*?)\)/);
5469
+ const match = pseudoElement.match(
5470
+ // `group-children` (nested transitions) before `group` so it wins.
5471
+ /::view-transition-(old|new|group-children|group|image-pair)\((.*?)\)/);
5256
5472
  if (!match)
5257
5473
  return null;
5258
5474
  return { layer: match[2], type: match[1] };
5259
5475
  }
5260
5476
 
5261
- function filterViewAnimations(animation) {
5262
- const { effect } = animation;
5263
- if (!effect)
5264
- return false;
5265
- return (effect.target === document.documentElement &&
5266
- effect.pseudoElement?.startsWith("::view-transition"));
5267
- }
5268
5477
  function getViewAnimations() {
5269
- return document.getAnimations().filter(filterViewAnimations);
5478
+ return document.getAnimations().filter((animation) => {
5479
+ const { effect } = animation;
5480
+ return (!!effect &&
5481
+ effect.target === document.documentElement &&
5482
+ effect.pseudoElement?.startsWith("::view-transition"));
5483
+ });
5270
5484
  }
5271
5485
 
5272
5486
  function hasTarget(target, targets) {
@@ -5274,87 +5488,370 @@ function hasTarget(target, targets) {
5274
5488
  }
5275
5489
 
5276
5490
  const definitionNames = ["layout", "enter", "exit", "new", "old"];
5491
+ /**
5492
+ * The `ViewTransitionTarget` buckets driving each generated layer type, in
5493
+ * priority order - the inverse of `chooseLayerType`. The new view is driven by
5494
+ * `new`/`enter`, the old by `old`/`exit`. `group-children`/`image-pair` have no
5495
+ * bucket; they follow the default layout timing.
5496
+ */
5497
+ const typeBuckets = {
5498
+ group: ["layout"],
5499
+ new: ["new", "enter"],
5500
+ old: ["old", "exit"],
5501
+ };
5502
+ /**
5503
+ * Default "absent" origin for a single-value keyframe, by pseudo type, so e.g.
5504
+ * `enter({ scale: 1 })` grows in from 0.85 and `exit({ opacity: 0 })` fades
5505
+ * from 1. `enter` prefers the matching `exit` value over these (see below).
5506
+ */
5507
+ const ORIGIN_DEFAULTS = {
5508
+ new: { opacity: 0, scale: 0.85 },
5509
+ old: { opacity: 1, scale: 1 },
5510
+ };
5511
+ const cornerProps = [
5512
+ "borderTopLeftRadius",
5513
+ "borderTopRightRadius",
5514
+ "borderBottomRightRadius",
5515
+ "borderBottomLeftRadius",
5516
+ ];
5277
5517
  function startViewAnimation(builder) {
5278
- const { update, targets, options: defaultOptions } = builder;
5518
+ const { update, targets, resolveDefs, noCrop, pairs, classNames, options: defaultOptions, } = builder;
5279
5519
  if (!document.startViewTransition) {
5280
- return new Promise(async (resolve) => {
5520
+ // An async IIFE (not `new Promise(async …)`) so a throwing/rejecting
5521
+ // update rejects this promise rather than leaving it unsettled.
5522
+ return (async () => {
5281
5523
  await update();
5282
- resolve(new GroupAnimation([]));
5524
+ return new GroupAnimation([]);
5525
+ })();
5526
+ }
5527
+ /**
5528
+ * Resolve any selector/Element targets to layer names, assigning a
5529
+ * `view-transition-name` to each element as we go. We run this before the
5530
+ * update (so the elements are captured in the old snapshot) and again
5531
+ * after it (for the new snapshot). An element present in both keeps the
5532
+ * same name and animates as a single `group` layer.
5533
+ */
5534
+ const nameRegistry = new Map();
5535
+ const assigned = [];
5536
+ /**
5537
+ * Elements we tagged with a `view-transition-class` (via `.class()`),
5538
+ * tracked separately from `assigned` so cleanup removes the class without
5539
+ * ever stripping an author's own inline `view-transition-name`.
5540
+ */
5541
+ const classed = [];
5542
+ const layerTargets = new Map();
5543
+ const croppedNames = new Set();
5544
+ /**
5545
+ * Each layer's stagger position (index + total) within its subject, per
5546
+ * snapshot. Resolving against the snapshot the layer belongs to keeps
5547
+ * stagger correct when `update()` replaces the matched elements, and lets
5548
+ * us skip a layer that's absent from a snapshot (e.g. an exited element
5549
+ * has no `new` pseudo-element).
5550
+ */
5551
+ const layerStagger = new Map();
5552
+ /**
5553
+ * Names allocated for a paired subject in the old snapshot, replayed onto
5554
+ * its new-snapshot target so both ends share a layer and morph.
5555
+ */
5556
+ const pairNames = new Map();
5557
+ /**
5558
+ * The old (`from`) elements of each paired subject, so their names can be
5559
+ * transferred off before the new (`to`) elements inherit them.
5560
+ */
5561
+ const pairFrom = new Map();
5562
+ const resolveLayers = (phase) => {
5563
+ targets.forEach((target, definition) => {
5564
+ const className = classNames.get(definition);
5565
+ let names;
5566
+ if (definition === "root" || !resolveDefs.has(definition)) {
5567
+ names = [definition];
5568
+ }
5569
+ else if (pairs.has(definition)) {
5570
+ /**
5571
+ * Paired morph: name the old target in the old snapshot, then
5572
+ * force the same name(s) onto the new target in the new one, so
5573
+ * two different elements morph as a single layer.
5574
+ */
5575
+ if (phase === "old") {
5576
+ pairFrom.set(definition, resolveElements(definition));
5577
+ names = assignViewTransitionNames(definition, nameRegistry, assigned, undefined, className, classed);
5578
+ pairNames.set(definition, names);
5579
+ }
5580
+ else {
5581
+ /**
5582
+ * Transfer the name(s) off the `from` elements before the
5583
+ * `to` elements inherit them. A `from` that survives into
5584
+ * the new snapshot (e.g. hidden with `visibility: hidden`
5585
+ * rather than removed) would otherwise keep the name and
5586
+ * collide - "duplicate view-transition-name".
5587
+ */
5588
+ for (const el of pairFrom.get(definition) ?? []) {
5589
+ el.style?.removeProperty("view-transition-name");
5590
+ /**
5591
+ * Drop the old end from the registry too, so the new
5592
+ * end alone supplies this name's `new` crop radii - we
5593
+ * neither re-measure nor get ordered by a stale element.
5594
+ */
5595
+ nameRegistry.delete(el);
5596
+ }
5597
+ names = assignViewTransitionNames(pairs.get(definition), nameRegistry, assigned, pairNames.get(definition), className, classed);
5598
+ }
5599
+ }
5600
+ else {
5601
+ names = assignViewTransitionNames(definition, nameRegistry, assigned, undefined, className, classed);
5602
+ }
5603
+ const cropped = definition !== "root" && !noCrop.has(definition);
5604
+ names.forEach((name, index) => {
5605
+ /**
5606
+ * If two subjects resolve to the same element, merge their
5607
+ * definitions so neither subject's animations are dropped.
5608
+ */
5609
+ const existing = layerTargets.get(name);
5610
+ layerTargets.set(name, existing && existing !== target
5611
+ ? { ...existing, ...target }
5612
+ : target);
5613
+ if (cropped)
5614
+ croppedNames.add(name);
5615
+ const stagger = layerStagger.get(name) ?? {};
5616
+ stagger[phase] = [index, names.length];
5617
+ layerStagger.set(name, stagger);
5618
+ });
5283
5619
  });
5284
- }
5285
- // TODO: Go over existing targets and ensure they all have ids
5620
+ };
5621
+ /**
5622
+ * The stagger index/total for a layer, resolved against the snapshot it
5623
+ * belongs to. Returns index -1 when the layer is absent from that snapshot
5624
+ * so the caller can skip a pseudo-element that doesn't exist.
5625
+ */
5626
+ const staggerPosition = (name, type) => {
5627
+ const stagger = layerStagger.get(name);
5628
+ const position = type === "old"
5629
+ ? stagger?.old
5630
+ : type === "new"
5631
+ ? stagger?.new
5632
+ : // group / group-children / image-pair persist across both.
5633
+ stagger?.new ?? stagger?.old;
5634
+ return position ?? [-1, 1];
5635
+ };
5636
+ /**
5637
+ * Merge default + per-layer transition options for a generated layer and
5638
+ * resolve any stagger/delay function against this element's position. Used
5639
+ * by both the morph-retiming and crop corner-radius passes.
5640
+ */
5641
+ const resolveLayerTransition = (target, type, transitionName, index, total) => {
5642
+ const transition = mergeTransition(getValueTransition(defaultOptions, transitionName), getValueTransition((layerOptions(target, type) ?? {}), transitionName));
5643
+ if (typeof transition.delay === "function") {
5644
+ transition.delay = transition.delay(index, total);
5645
+ }
5646
+ return transition;
5647
+ };
5648
+ /**
5649
+ * Measured corner radii per cropped layer, so the clip can animate each
5650
+ * corner between the old and new elements. Per-corner (rather than the
5651
+ * shorthand) so mismatched/individual radii interpolate cleanly.
5652
+ */
5653
+ const cropRadii = new Map();
5654
+ const recordRadii = (style, name, phase) => {
5655
+ const corners = {};
5656
+ for (const corner of cornerProps)
5657
+ corners[corner] = style[corner];
5658
+ const entry = cropRadii.get(name) ?? {};
5659
+ entry[phase] = corners;
5660
+ cropRadii.set(name, entry);
5661
+ };
5286
5662
  /**
5287
- * If we don't have any animations defined for the root target,
5288
- * remove it from being captured.
5663
+ * Cropped layers all come from `.add()`, so their elements are in the
5664
+ * registry - read each one's corner radii directly. For a paired morph both
5665
+ * ends share a name; the new-snapshot element is registered last, so it
5666
+ * wins the `new` reading (and the old end the `old` reading).
5289
5667
  */
5290
- if (!hasTarget("root", targets)) {
5291
- css.set(":root", {
5292
- "view-transition-name": "none",
5668
+ const measureCrop = (phase) => {
5669
+ if (!croppedNames.size)
5670
+ return;
5671
+ nameRegistry.forEach((name, element) => {
5672
+ if (croppedNames.has(name)) {
5673
+ recordRadii(getComputedStyle(element), name, phase);
5674
+ }
5293
5675
  });
5294
- }
5676
+ };
5295
5677
  /**
5296
- * Set the timing curve to linear for all view transition layers.
5297
- * This gets baked into the keyframes, which can't be changed
5298
- * without breaking the generated animation.
5678
+ * Write the persistent view-transition CSS: suppress root capture when the
5679
+ * root has no animations of its own; force linear timing (baked into the
5680
+ * keyframes, so we can retime later via updateTiming); and clip +
5681
+ * object-fit: cover every cropped morph (the UA default overflows on
5682
+ * aspect-ratio change), with an animated border-radius added below.
5299
5683
  *
5300
- * This allows us to set easing via updateTiming - which can be changed.
5684
+ * `css.commit` replaces rather than appends, so we re-set the full rule set
5685
+ * each call - the second call (in the update callback) then picks up cropped
5686
+ * layers that only exist in the new snapshot.
5301
5687
  */
5302
- css.set("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)", { "animation-timing-function": "linear !important" });
5303
- css.commit(); // Write
5304
- const transition = document.startViewTransition(async () => {
5305
- await update();
5306
- // TODO: Go over new targets and ensure they all have ids
5307
- });
5308
- transition.finished.finally(() => {
5688
+ const commitViewCSS = () => {
5689
+ if (!hasTarget("root", targets)) {
5690
+ css.set(":root", { "view-transition-name": "none" });
5691
+ }
5692
+ css.set("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)", { "animation-timing-function": "linear !important" });
5693
+ croppedNames.forEach((name) => {
5694
+ css.set(`::view-transition-group(${name})`, { overflow: "clip" });
5695
+ css.set(`::view-transition-old(${name}), ::view-transition-new(${name})`, { width: "100%", height: "100%", "object-fit": "cover" });
5696
+ });
5697
+ css.commit(); // Write
5698
+ };
5699
+ const cleanup = () => {
5700
+ releaseViewTransitionNames(assigned, classed);
5309
5701
  css.remove(); // Write
5310
- });
5311
- return new Promise((resolve) => {
5312
- transition.ready.then(() => {
5702
+ };
5703
+ const callback = async () => {
5704
+ await update();
5705
+ /**
5706
+ * Re-resolve so elements created by the update are named for the new
5707
+ * snapshot, then measure the cropped layers' new border-radius.
5708
+ */
5709
+ const croppedBefore = croppedNames.size;
5710
+ resolveLayers("new");
5711
+ measureCrop("new");
5712
+ /**
5713
+ * Re-commit the crop CSS only if the new snapshot introduced cropped
5714
+ * layers, so a layer that exists only in the new snapshot is clipped
5715
+ * too - without forcing a redundant style write on the common path.
5716
+ */
5717
+ if (croppedNames.size > croppedBefore)
5718
+ commitViewCSS();
5719
+ };
5720
+ let transition;
5721
+ try {
5722
+ resolveLayers("old");
5723
+ measureCrop("old");
5724
+ commitViewCSS();
5725
+ transition = document.startViewTransition(callback);
5726
+ }
5727
+ catch (error) {
5728
+ /**
5729
+ * The prelude writes inline names before the transition exists. If it
5730
+ * throws (e.g. startViewTransition rejects in a bad UA state), release
5731
+ * them so we neither leak DOM state nor stall the queue on a promise
5732
+ * that never settles - hand back a rejection it can advance past.
5733
+ */
5734
+ cleanup();
5735
+ return Promise.reject(error);
5736
+ }
5737
+ transition.finished.finally(cleanup);
5738
+ return new Promise((resolve, reject) => {
5739
+ transition.ready
5740
+ .then(() => {
5313
5741
  const generatedViewAnimations = getViewAnimations();
5314
5742
  const animations = [];
5315
5743
  /**
5316
5744
  * Create animations for each of our explicitly-defined subjects.
5745
+ * `opacityAnimated` additionally tracks which `${name}:${type}`
5746
+ * we faded, so we can keep the UA `plus-lighter` blend only for a
5747
+ * genuine opacity crossfade (both sides fading) and drop it for a
5748
+ * slide/transform, where additive compositing would flash bright.
5317
5749
  */
5318
- targets.forEach((definition, target) => {
5319
- // TODO: If target is not "root", resolve elements
5320
- // and iterate over each
5750
+ const explicitlyAnimated = new Set();
5751
+ const opacityAnimated = new Set();
5752
+ layerTargets.forEach((target, name) => {
5753
+ const stagger = layerStagger.get(name);
5754
+ /**
5755
+ * Presence: `enter` only fires for a pure newcomer (a new
5756
+ * view with no old), `exit` only for a pure leaver. A
5757
+ * survivor (both) gets neither - it just morphs.
5758
+ */
5759
+ const enterApplies = !!stagger?.new && !stagger?.old;
5760
+ const exitApplies = !!stagger?.old && !stagger?.new;
5321
5761
  for (const key of definitionNames) {
5322
- if (!definition[key])
5762
+ if (!target[key])
5323
5763
  continue;
5324
- const { keyframes, options } = definition[key];
5764
+ if (key === "enter" && !enterApplies)
5765
+ continue;
5766
+ if (key === "exit" && !exitApplies)
5767
+ continue;
5768
+ const type = chooseLayerType(key);
5769
+ const [index, total] = staggerPosition(name, type);
5770
+ // Skip a layer absent from its snapshot.
5771
+ if (index === -1)
5772
+ continue;
5773
+ const { keyframes, options } = target[key];
5325
5774
  for (let [valueName, valueKeyframes] of Object.entries(keyframes)) {
5326
- if (!valueKeyframes)
5775
+ // Skip only missing values - `0` (e.g. opacity: 0)
5776
+ // is valid and must reach the from-value inference.
5777
+ if (valueKeyframes == null)
5327
5778
  continue;
5328
- const valueOptions = {
5329
- ...getValueTransition(defaultOptions, valueName),
5330
- ...getValueTransition(options, valueName),
5331
- };
5332
- const type = chooseLayerType(key);
5333
5779
  /**
5334
- * If this is an opacity animation, and keyframes are not an array,
5335
- * we need to convert them into an array and set an initial value.
5780
+ * The view path hands keyframes straight to WAAPI,
5781
+ * so Motion's `x`/`y` shorthands (compiled to
5782
+ * `transform` only via the value pipeline) have no
5783
+ * effect. Warn and skip - use `transform`/`translate`.
5784
+ */
5785
+ if (valueName === "x" || valueName === "y") {
5786
+ motionUtils.warnOnce(false, `animateView() animates view-transition layers with CSS properties; the "${valueName}" shorthand has no effect - use transform, e.g. { transform: "translateX(40px)" }.`);
5787
+ continue;
5788
+ }
5789
+ /**
5790
+ * enter/exit win over new/old on a shared property -
5791
+ * skip it here when the gated bucket also defines it.
5336
5792
  */
5337
- if (valueName === "opacity" &&
5338
- !Array.isArray(valueKeyframes)) {
5339
- const initialValue = type === "new" ? 0 : 1;
5340
- valueKeyframes = [initialValue, valueKeyframes];
5793
+ if (key === "new" &&
5794
+ enterApplies &&
5795
+ target.enter?.keyframes[valueName] != null) {
5796
+ continue;
5797
+ }
5798
+ if (key === "old" &&
5799
+ exitApplies &&
5800
+ target.exit?.keyframes[valueName] != null) {
5801
+ continue;
5802
+ }
5803
+ const valueOptions = mergeTransition(getValueTransition(defaultOptions, valueName), getValueTransition(options, valueName));
5804
+ /**
5805
+ * Infer an origin for a single-value keyframe. An
5806
+ * `enter` mirrors the matching `exit` value (a
5807
+ * defined exit reverses into the enter for free);
5808
+ * otherwise the per-type default (opacity 0/1, scale
5809
+ * 0.85). No default -> left as-is (animates from the
5810
+ * live value).
5811
+ *
5812
+ * `new`/`old` fire for survivors too, where only the
5813
+ * opacity crossfade default applies - a transform
5814
+ * default like scale 0.85 would pop a persisting
5815
+ * element, so gate it on the layer actually
5816
+ * entering/leaving.
5817
+ */
5818
+ if (!Array.isArray(valueKeyframes)) {
5819
+ const exitValue = key === "enter"
5820
+ ? target.exit?.keyframes[valueName]
5821
+ : undefined;
5822
+ const allowDefault = valueName === "opacity" ||
5823
+ (type === "new" ? enterApplies : exitApplies);
5824
+ const from = exitValue != null
5825
+ ? Array.isArray(exitValue)
5826
+ ? exitValue[exitValue.length - 1]
5827
+ : exitValue
5828
+ : allowDefault
5829
+ ? ORIGIN_DEFAULTS[type]?.[valueName]
5830
+ : undefined;
5831
+ if (from !== undefined) {
5832
+ valueKeyframes = [from, valueKeyframes];
5833
+ }
5341
5834
  }
5342
5835
  /**
5343
- * Resolve stagger function if provided.
5836
+ * Resolve stagger function if provided, per element
5837
+ * across this subject's resolved layers.
5344
5838
  */
5345
5839
  if (typeof valueOptions.delay === "function") {
5346
- valueOptions.delay = valueOptions.delay(0, 1);
5840
+ valueOptions.delay = valueOptions.delay(index, total);
5347
5841
  }
5348
5842
  valueOptions.duration && (valueOptions.duration = motionUtils.secondsToMilliseconds(valueOptions.duration));
5349
5843
  valueOptions.delay && (valueOptions.delay = motionUtils.secondsToMilliseconds(valueOptions.delay));
5350
- const animation = new NativeAnimation({
5844
+ animations.push(new NativeAnimation({
5351
5845
  ...valueOptions,
5352
5846
  element: document.documentElement,
5353
5847
  name: valueName,
5354
- pseudoElement: `::view-transition-${type}(${target})`,
5848
+ pseudoElement: `::view-transition-${type}(${name})`,
5355
5849
  keyframes: valueKeyframes,
5356
- });
5357
- animations.push(animation);
5850
+ }));
5851
+ explicitlyAnimated.add(`${name}:${type}`);
5852
+ if (valueName === "opacity") {
5853
+ opacityAnimated.add(`${name}:${type}`);
5854
+ }
5358
5855
  }
5359
5856
  }
5360
5857
  });
@@ -5373,45 +5870,161 @@ function startViewAnimation(builder) {
5373
5870
  const name = getViewAnimationLayerInfo(pseudoElement);
5374
5871
  if (!name)
5375
5872
  continue;
5376
- const targetDefinition = targets.get(name.layer);
5377
- if (!targetDefinition) {
5378
- /**
5379
- * If transition name is group then update the timing of the animation
5380
- * whereas if it's old or new then we could possibly replace it using
5381
- * the above method.
5382
- */
5383
- const transitionName = name.type === "group" ? "layout" : "";
5384
- let animationTransition = {
5385
- ...getValueTransition(defaultOptions, transitionName),
5386
- };
5387
- animationTransition.duration && (animationTransition.duration = motionUtils.secondsToMilliseconds(animationTransition.duration));
5388
- animationTransition =
5389
- applyGeneratorOptions(animationTransition);
5390
- const easing = mapEasingToNativeEasing(animationTransition.ease, animationTransition.duration);
5391
- effect.updateTiming({
5392
- delay: motionUtils.secondsToMilliseconds(animationTransition.delay ?? 0),
5393
- duration: animationTransition.duration,
5394
- easing,
5395
- });
5396
- animations.push(new NativeAnimationWrapper(animation));
5397
- }
5398
- else if (hasOpacity(targetDefinition, "enter") &&
5399
- hasOpacity(targetDefinition, "exit") &&
5400
- effect
5401
- .getKeyframes()
5402
- .some((keyframe) => keyframe.mixBlendMode)) {
5403
- animations.push(new NativeAnimationWrapper(animation));
5404
- }
5405
- else {
5406
- animation.cancel();
5873
+ const targetDefinition = layerTargets.get(name.layer);
5874
+ /**
5875
+ * We built our own animation for this layer, so drop the
5876
+ * browser-generated fade we're replacing. The UA
5877
+ * `plus-lighter` blend is a *separate* generated animation on
5878
+ * the same pseudo (it sets `mix-blend-mode` in its keyframes):
5879
+ * keep it *only* for a true opacity crossfade - both sides
5880
+ * fading - so a symmetric crossfade composites without
5881
+ * darkening, but a slide/transform (where both layers stay
5882
+ * opaque and overlap) doesn't flash bright from the addition.
5883
+ */
5884
+ if (explicitlyAnimated.has(`${name.layer}:${name.type}`)) {
5885
+ const isCrossfade = opacityAnimated.has(`${name.layer}:new`) &&
5886
+ opacityAnimated.has(`${name.layer}:old`);
5887
+ if (isCrossfade &&
5888
+ effect
5889
+ .getKeyframes()
5890
+ .some((keyframe) => keyframe.mixBlendMode)) {
5891
+ animations.push(new NativeAnimationWrapper(animation));
5892
+ }
5893
+ else {
5894
+ animation.cancel();
5895
+ }
5896
+ continue;
5407
5897
  }
5898
+ /**
5899
+ * Otherwise retime the browser-generated animation to
5900
+ * Motion's timing. This auto-enables the layout (group)
5901
+ * morph for any resolved/named target, and applies the
5902
+ * default timing to old/new layers we haven't explicitly
5903
+ * overridden.
5904
+ *
5905
+ * group + group-children both follow the layout timing so
5906
+ * the nesting container stays in sync with the morph.
5907
+ */
5908
+ /**
5909
+ * A survivor's old + new are the two halves of one
5910
+ * `plus-lighter` crossfade. They must share identical timing
5911
+ * (so their opacities stay mirrored and sum to 1 - else the
5912
+ * additive blend flashes bright wherever both are partly
5913
+ * visible) and fade linearly (the bounce belongs on the
5914
+ * group's geometry, not the opacity). So time them as the
5915
+ * group, rather than via their own - potentially staggered,
5916
+ * or enter/exit-derived - old/new options.
5917
+ */
5918
+ const stagger = layerStagger.get(name.layer);
5919
+ const isMorphCrossfade = (name.type === "old" || name.type === "new") &&
5920
+ !!stagger?.old &&
5921
+ !!stagger?.new;
5922
+ const timingType = name.type.startsWith("group") || isMorphCrossfade
5923
+ ? "group"
5924
+ : name.type;
5925
+ const [index, total] = staggerPosition(name.layer, timingType);
5926
+ const transitionName = timingType === "group" ? "layout" : "";
5927
+ let animationTransition = resolveLayerTransition(targetDefinition, timingType, transitionName, index === -1 ? 0 : index, total);
5928
+ /**
5929
+ * The crossfade should resolve at the spring's *perceptual*
5930
+ * (visual) duration - the geometry can keep bouncing, but the
5931
+ * opacity shouldn't drag through the settle. So capture
5932
+ * `visualDuration` before `applyGeneratorOptions` replaces it
5933
+ * with the full overshoot duration, and use it for the fade.
5934
+ */
5935
+ const visualDuration = animationTransition.visualDuration;
5936
+ animationTransition.duration && (animationTransition.duration = motionUtils.secondsToMilliseconds(animationTransition.duration));
5937
+ animationTransition =
5938
+ applyGeneratorOptions(animationTransition);
5939
+ const duration = isMorphCrossfade && visualDuration !== undefined
5940
+ ? motionUtils.secondsToMilliseconds(visualDuration)
5941
+ : animationTransition.duration;
5942
+ const easing = isMorphCrossfade
5943
+ ? "linear"
5944
+ : mapEasingToNativeEasing(animationTransition.ease, animationTransition.duration);
5945
+ effect.updateTiming({
5946
+ delay: motionUtils.secondsToMilliseconds(animationTransition.delay ?? 0),
5947
+ duration,
5948
+ easing,
5949
+ });
5950
+ animations.push(new NativeAnimationWrapper(animation));
5408
5951
  }
5952
+ /**
5953
+ * Animate each cropped layer's clip corners between the old and
5954
+ * new elements, so a cropped morph keeps rounded corners
5955
+ * (handling individual per-corner radii).
5956
+ */
5957
+ cropRadii.forEach((radii, name) => {
5958
+ if (!radii.old && !radii.new)
5959
+ return;
5960
+ const target = layerTargets.get(name);
5961
+ const [index, total] = staggerPosition(name, "group");
5962
+ const radiusOptions = resolveLayerTransition(target, "group", "layout", index === -1 ? 0 : index, total);
5963
+ radiusOptions.duration && (radiusOptions.duration = motionUtils.secondsToMilliseconds(radiusOptions.duration));
5964
+ radiusOptions.delay && (radiusOptions.delay = motionUtils.secondsToMilliseconds(radiusOptions.delay));
5965
+ for (const corner of cornerProps) {
5966
+ // `||` (not `??`) so an empty measurement (e.g. an
5967
+ // un-rendered element) falls back rather than producing
5968
+ // an invalid keyframe.
5969
+ const from = radii.old?.[corner] || radii.new?.[corner] || "0px";
5970
+ const to = radii.new?.[corner] || radii.old?.[corner] || "0px";
5971
+ // Skip square corners - nothing to round.
5972
+ if (parseFloat(from) === 0 && parseFloat(to) === 0) {
5973
+ continue;
5974
+ }
5975
+ animations.push(new NativeAnimation({
5976
+ ...radiusOptions,
5977
+ element: document.documentElement,
5978
+ name: corner,
5979
+ pseudoElement: `::view-transition-group(${name})`,
5980
+ keyframes: [from, to],
5981
+ }));
5982
+ }
5983
+ });
5409
5984
  resolve(new GroupAnimation(animations));
5410
- });
5985
+ })
5986
+ .catch(() =>
5987
+ /**
5988
+ * `ready` rejects when the transition is skipped - no visual
5989
+ * change, or superseded by an interrupting transition. The DOM
5990
+ * update still applied, so settle with no animations rather than
5991
+ * surfacing it as an error to an awaiting caller. A genuine
5992
+ * failure in `update()` rejects `updateCallbackDone` (already
5993
+ * settled by now), so propagate that instead.
5994
+ */
5995
+ transition.updateCallbackDone.then(() => resolve(new GroupAnimation([])), reject));
5411
5996
  });
5412
5997
  }
5413
- function hasOpacity(target, key) {
5414
- return target?.[key]?.keyframes.opacity;
5998
+ /**
5999
+ * The options that should time a given generated layer type, so a retimed
6000
+ * group/old/new picks up any per-target transition the user provided. Checks
6001
+ * the type's buckets in priority order (e.g. `new` before `enter`).
6002
+ */
6003
+ function layerOptions(target, type) {
6004
+ for (const bucket of typeBuckets[type] ?? []) {
6005
+ const options = target?.[bucket]?.options;
6006
+ if (options)
6007
+ return options;
6008
+ }
6009
+ }
6010
+ /**
6011
+ * Merge a base transition (e.g. the default `options`) with a per-layer/value
6012
+ * override. An explicit `duration` on the override must win over an inherited
6013
+ * generator's own timing: a spring prefers `visualDuration`, and
6014
+ * `spring.applyToOptions` overwrites `duration` with the computed settle time -
6015
+ * so without this the override is silently discarded. Dropping the inherited
6016
+ * `type`/`visualDuration` makes the layer a plain tween of that duration, unless
6017
+ * it asked for its own generator `type`/`visualDuration`.
6018
+ */
6019
+ function mergeTransition(base, override) {
6020
+ const merged = { ...base, ...override };
6021
+ if (override.duration !== undefined) {
6022
+ if (override.visualDuration === undefined)
6023
+ delete merged.visualDuration;
6024
+ if (override.type === undefined)
6025
+ delete merged.type;
6026
+ }
6027
+ return merged;
5415
6028
  }
5416
6029
 
5417
6030
  let builders = [];
@@ -5425,10 +6038,16 @@ function next() {
5425
6038
  function start(builder) {
5426
6039
  motionUtils.removeItem(builders, builder);
5427
6040
  current = builder;
5428
- startViewAnimation(builder).then((animation) => {
6041
+ startViewAnimation(builder)
6042
+ .then((animation) => {
5429
6043
  builder.notifyReady(animation);
5430
- animation.finished.finally(next);
5431
- });
6044
+ return animation.finished;
6045
+ })
6046
+ // A genuinely failed transition (a throwing update) rejects the
6047
+ // builder; a skipped/interrupted one resolves with no animations (see
6048
+ // start.ts). Either way, advance the queue - else later transitions hang.
6049
+ .catch((error) => builder.notifyReject(error))
6050
+ .finally(next);
5432
6051
  }
5433
6052
  function processQueue() {
5434
6053
  /**
@@ -5465,31 +6084,96 @@ class ViewTransitionBuilder {
5465
6084
  constructor(update, options = {}) {
5466
6085
  this.currentSubject = "root";
5467
6086
  this.targets = new Map();
6087
+ /**
6088
+ * Definitions that must be resolved to elements (and assigned a
6089
+ * `view-transition-name`) rather than treated as pre-named layers.
6090
+ */
6091
+ this.resolveDefs = new Set();
6092
+ /**
6093
+ * Subjects opted out of the default crop (clip + object-fit: cover +
6094
+ * animated corner radii) via `.crop(false)`.
6095
+ */
6096
+ this.noCrop = new Set();
6097
+ /**
6098
+ * Subjects paired with a different new-snapshot target (the second `.add()`
6099
+ * argument), so two distinct elements share one name and morph into each
6100
+ * other - a shared-element transition.
6101
+ */
6102
+ this.pairs = new Map();
6103
+ /**
6104
+ * A `view-transition-class` to apply to each subject's resolved elements,
6105
+ * so authors can target the generated layers from CSS by class rather than
6106
+ * the opaque generated name.
6107
+ */
6108
+ this.classNames = new Map();
5468
6109
  this.notifyReady = motionUtils.noop;
5469
- this.readyPromise = new Promise((resolve) => {
6110
+ this.notifyReject = motionUtils.noop;
6111
+ this.readyPromise = new Promise((resolve, reject) => {
5470
6112
  this.notifyReady = resolve;
6113
+ this.notifyReject = reject;
5471
6114
  });
5472
6115
  this.update = update;
5473
6116
  this.options = {
5474
6117
  interrupt: "wait",
5475
6118
  ...options,
5476
6119
  };
6120
+ // Avoid an unhandled rejection when a failed transition has no
6121
+ // `.then(_, reject)` handler attached (e.g. fire-and-forget).
6122
+ this.readyPromise.catch(motionUtils.noop);
5477
6123
  addToQueue(this);
5478
6124
  }
5479
- get(subject) {
6125
+ /**
6126
+ * Target elements resolved from a selector or Element, each assigned a
6127
+ * `view-transition-name` automatically.
6128
+ *
6129
+ * Passing a second target pairs them: the first is resolved in the old
6130
+ * snapshot and the second in the new, sharing one name so two *different*
6131
+ * elements morph into each other (e.g. `.add(card, ".modal")`). Symmetric -
6132
+ * pass them the other way round to morph back.
6133
+ */
6134
+ add(subject, newSubject) {
5480
6135
  this.currentSubject = subject;
6136
+ this.resolveDefs.add(subject);
6137
+ if (newSubject !== undefined)
6138
+ this.pairs.set(subject, newSubject);
6139
+ // Register the subject so it participates (and gets an automatic
6140
+ // layout/morph animation) even without an explicit enter/exit/layout.
6141
+ if (!this.targets.has(subject))
6142
+ this.targets.set(subject, {});
5481
6143
  return this;
5482
6144
  }
5483
- layout(keyframes, options) {
5484
- this.updateTarget("layout", keyframes, options);
6145
+ /**
6146
+ * Morphs are clipped + `object-fit: cover` (and their corners animate)
6147
+ * by default. Call `.crop(false)` to opt this subject out and fall back
6148
+ * to the browser default (which overflows on aspect-ratio change).
6149
+ */
6150
+ crop(enabled = true) {
6151
+ enabled
6152
+ ? this.noCrop.delete(this.currentSubject)
6153
+ : this.noCrop.add(this.currentSubject);
5485
6154
  return this;
5486
6155
  }
5487
- new(keyframes, options) {
5488
- this.updateTarget("new", keyframes, options);
6156
+ /**
6157
+ * Tag this subject's generated layers with a `view-transition-class`, so
6158
+ * they can be targeted from CSS - `::view-transition-group(.name)`,
6159
+ * `::view-transition-old/new(.name)`, `::view-transition-image-pair(.name)`
6160
+ * - without the opaque generated `view-transition-name`. Because `.add()`
6161
+ * can match many elements, a shared class targets them all at once (and,
6162
+ * for a pair, both ends). The escape hatch for z-index / custom keyframes
6163
+ * on a morph layer.
6164
+ */
6165
+ class(name) {
6166
+ this.classNames.set(this.currentSubject, name);
5489
6167
  return this;
5490
6168
  }
5491
- old(keyframes, options) {
5492
- this.updateTarget("old", keyframes, options);
6169
+ /**
6170
+ * Set the transition for this subject's morph. The morph is enabled
6171
+ * automatically by `.add()`; this just customises its timing (duration,
6172
+ * easing, a `delay`/`stagger`, …). On the implicit `root` subject it also
6173
+ * opts the page into the transition (the root crossfade).
6174
+ */
6175
+ layout(options = {}) {
6176
+ this.updateTarget("layout", {}, options);
5493
6177
  return this;
5494
6178
  }
5495
6179
  enter(keyframes, options) {
@@ -5500,9 +6184,21 @@ class ViewTransitionBuilder {
5500
6184
  this.updateTarget("exit", keyframes, options);
5501
6185
  return this;
5502
6186
  }
5503
- crossfade(options) {
5504
- this.updateTarget("enter", { opacity: 1 }, options);
5505
- this.updateTarget("exit", { opacity: 0 }, options);
6187
+ /**
6188
+ * Animate the new view directly, whether the element is appearing or
6189
+ * persisting (unlike `.enter()`, which only fires for a pure newcomer).
6190
+ * Pair with `.old()` for a crossfade or slide-through.
6191
+ */
6192
+ new(keyframes, options) {
6193
+ this.updateTarget("new", keyframes, options);
6194
+ return this;
6195
+ }
6196
+ /**
6197
+ * Animate the old view directly, whether the element is leaving or
6198
+ * persisting (unlike `.exit()`, which only fires for a pure leaver).
6199
+ */
6200
+ old(keyframes, options) {
6201
+ this.updateTarget("old", keyframes, options);
5506
6202
  return this;
5507
6203
  }
5508
6204
  updateTarget(target, keyframes, options = {}) {
@@ -5517,8 +6213,8 @@ class ViewTransitionBuilder {
5517
6213
  return this.readyPromise.then(resolve, reject);
5518
6214
  }
5519
6215
  }
5520
- function animateView(update, defaultOptions = {}) {
5521
- return new ViewTransitionBuilder(update, defaultOptions);
6216
+ function animateView(update, options = {}) {
6217
+ return new ViewTransitionBuilder(update, options);
5522
6218
  }
5523
6219
 
5524
6220
  const createAxisDelta = () => ({
@@ -6465,6 +7161,14 @@ function buildTransform(latestValues, transform, transformTemplate) {
6465
7161
  }
6466
7162
  }
6467
7163
  }
7164
+ // `pathRotation` composes onto `rotate` as a separate additive term so
7165
+ // the user's `rotate` is never clobbered. Deliberately not a slot in
7166
+ // `transformPropOrder`.
7167
+ const pathRotation = latestValues.pathRotation;
7168
+ if (pathRotation) {
7169
+ transformIsDefault = false;
7170
+ transformString += `rotate(${getValueAsType(pathRotation, numberValueTypes.pathRotation)}) `;
7171
+ }
6468
7172
  transformString = transformString.trim();
6469
7173
  // If we have a custom `transform` template, pass our transform values and
6470
7174
  // generated transformString to that before returning
@@ -7527,11 +8231,14 @@ function buildProjectionTransform(delta, treeScale, latestTransform) {
7527
8231
  transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
7528
8232
  }
7529
8233
  if (latestTransform) {
7530
- const { transformPerspective, rotate, rotateX, rotateY, skewX, skewY } = latestTransform;
8234
+ const { transformPerspective, rotate, pathRotation, rotateX, rotateY, skewX, skewY, } = latestTransform;
7531
8235
  if (transformPerspective)
7532
8236
  transform = `perspective(${transformPerspective}px) ${transform}`;
7533
8237
  if (rotate)
7534
8238
  transform += `rotate(${rotate}deg) `;
8239
+ // Additive `rotate()` so user `rotate` isn't clobbered.
8240
+ if (pathRotation)
8241
+ transform += `rotate(${pathRotation}deg) `;
7535
8242
  if (rotateX)
7536
8243
  transform += `rotateX(${rotateX}deg) `;
7537
8244
  if (rotateY)
@@ -7627,7 +8334,7 @@ function animateSingleValue(value, keyframes, options) {
7627
8334
 
7628
8335
  function addDomEvent(target, eventName, handler, options = { passive: true }) {
7629
8336
  target.addEventListener(eventName, handler, options);
7630
- return () => target.removeEventListener(eventName, handler);
8337
+ return () => target.removeEventListener(eventName, handler, options);
7631
8338
  }
7632
8339
 
7633
8340
  const compareByDepth = (a, b) => a.depth - b.depth;
@@ -8086,7 +8793,8 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8086
8793
  * Set animation origin after starting animation to avoid layout jump
8087
8794
  * caused by stopping previous layout animation
8088
8795
  */
8089
- this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged);
8796
+ this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged, animationOptions
8797
+ .path);
8090
8798
  }
8091
8799
  else {
8092
8800
  /**
@@ -8802,7 +9510,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8802
9510
  this.projectionDelta = createDelta();
8803
9511
  this.projectionDeltaWithTransform = createDelta();
8804
9512
  }
8805
- setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) {
9513
+ setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false, pathFn) {
8806
9514
  const snapshot = this.snapshot;
8807
9515
  const snapshotLatestValues = snapshot ? snapshot.latestValues : {};
8808
9516
  const mixedValues = { ...this.latestValues };
@@ -8824,10 +9532,26 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8824
9532
  !this.path.some(hasOpacityCrossfade));
8825
9533
  this.animationProgress = 0;
8826
9534
  let prevRelativeTarget;
9535
+ // The path decides whether the layout shift is worth curving
9536
+ // (distance floor) and resolves the interpolator from the delta.
9537
+ const interpolate = pathFn?.interpolateProjection(delta);
8827
9538
  this.mixTargetDelta = (latest) => {
8828
9539
  const progress = latest / 1000;
8829
- mixAxisDelta(targetDelta.x, delta.x, progress);
8830
- mixAxisDelta(targetDelta.y, delta.y, progress);
9540
+ const point = interpolate?.(progress);
9541
+ if (point) {
9542
+ targetDelta.x.translate = point.x;
9543
+ targetDelta.x.scale = mixNumber$1(delta.x.scale, 1, progress);
9544
+ targetDelta.x.origin = delta.x.origin;
9545
+ targetDelta.x.originPoint = delta.x.originPoint;
9546
+ targetDelta.y.translate = point.y;
9547
+ targetDelta.y.scale = mixNumber$1(delta.y.scale, 1, progress);
9548
+ targetDelta.y.origin = delta.y.origin;
9549
+ targetDelta.y.originPoint = delta.y.originPoint;
9550
+ }
9551
+ else {
9552
+ mixAxisDeltaLinear(targetDelta.x, delta.x, progress);
9553
+ mixAxisDeltaLinear(targetDelta.y, delta.y, progress);
9554
+ }
8831
9555
  this.setTargetDelta(targetDelta);
8832
9556
  if (this.relativeTarget &&
8833
9557
  this.relativeTargetOrigin &&
@@ -8852,6 +9576,13 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8852
9576
  this.animationValues = mixedValues;
8853
9577
  mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember);
8854
9578
  }
9579
+ if (point && point.rotate !== undefined) {
9580
+ // Dedicated `pathRotation` channel, not `rotate`, so an
9581
+ // animating `rotate` is composed with, never clobbered.
9582
+ if (!this.animationValues)
9583
+ this.animationValues = mixedValues;
9584
+ this.animationValues.pathRotation = point.rotate;
9585
+ }
8855
9586
  this.root.scheduleUpdateProjection();
8856
9587
  this.scheduleRender();
8857
9588
  this.animationProgress = progress;
@@ -8873,7 +9604,6 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8873
9604
  */
8874
9605
  this.pendingAnimation = frame.update(() => {
8875
9606
  globalProjectionState.hasAnimatedSinceResize = true;
8876
- activeAnimations.layout++;
8877
9607
  this.motionValue || (this.motionValue = motionValue(0));
8878
9608
  this.motionValue.jump(0, false);
8879
9609
  this.currentAnimation = animateSingleValue(this.motionValue, [0, 1000], {
@@ -8884,11 +9614,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8884
9614
  this.mixTargetDelta(latest);
8885
9615
  options.onUpdate && options.onUpdate(latest);
8886
9616
  },
8887
- onStop: () => {
8888
- activeAnimations.layout--;
8889
- },
8890
9617
  onComplete: () => {
8891
- activeAnimations.layout--;
8892
9618
  options.onComplete && options.onComplete();
8893
9619
  this.completeAnimation();
8894
9620
  },
@@ -9372,7 +10098,7 @@ function resetSkewAndRotation(node) {
9372
10098
  function removeLeadSnapshots(stack) {
9373
10099
  stack.removeLeadSnapshot();
9374
10100
  }
9375
- function mixAxisDelta(output, delta, p) {
10101
+ function mixAxisDeltaLinear(output, delta, p) {
9376
10102
  output.translate = mixNumber$1(delta.translate, 0, p);
9377
10103
  output.scale = mixNumber$1(delta.scale, 1, p);
9378
10104
  output.origin = delta.origin;
@@ -9477,39 +10203,221 @@ const HTMLProjectionNode = createProjectionNode({
9477
10203
  checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"),
9478
10204
  });
9479
10205
 
9480
- const layoutSelector = "[data-layout], [data-layout-id]";
9481
- const noop = () => { };
9482
- function snapshotFromTarget(projection) {
9483
- const target = projection.targetWithTransforms || projection.target;
9484
- if (!target)
9485
- return undefined;
9486
- const measuredBox = createBox();
9487
- const layoutBox = createBox();
9488
- copyBoxInto(measuredBox, target);
9489
- copyBoxInto(layoutBox, target);
10206
+ const layoutSelector = "[data-layout],[data-layout-id]";
10207
+ /**
10208
+ * All imperatively-created projection nodes live in one persistent tree,
10209
+ * shared across animateLayout() calls (and with any React-created nodes,
10210
+ * via the singleton document root). Keyed by element for reuse.
10211
+ */
10212
+ const layoutNodes = new WeakMap();
10213
+ /**
10214
+ * Builders created within the same synchronous tick are flushed together
10215
+ * as a single "commit": every node is snapshotted before any updateDom
10216
+ * runs, mirroring React batching renders from different parts of the tree.
10217
+ */
10218
+ let pendingBuilders;
10219
+ function collectLayoutElements(scope) {
10220
+ const elements = [];
10221
+ if (scope instanceof HTMLElement && scope.matches(layoutSelector)) {
10222
+ elements.push(scope);
10223
+ }
10224
+ scope.querySelectorAll(layoutSelector).forEach((element) => {
10225
+ if (element instanceof HTMLElement)
10226
+ elements.push(element);
10227
+ });
10228
+ return elements;
10229
+ }
10230
+ /**
10231
+ * Process any work scheduled on the frameloop now. A previous animation
10232
+ * may have been seeked while paused (controls.time = x) without a frame
10233
+ * having rendered it - we must materialise that state into the DOM
10234
+ * before taking snapshots.
10235
+ */
10236
+ function flushPendingFrame() {
10237
+ if (frameData.isProcessing)
10238
+ return;
10239
+ const now = time.now();
10240
+ frameData.delta = motionUtils.clamp(0, 1000 / 60, now - frameData.timestamp);
10241
+ frameData.timestamp = now;
10242
+ frameData.isProcessing = true;
10243
+ frameSteps.update.process(frameData);
10244
+ frameSteps.preRender.process(frameData);
10245
+ frameSteps.render.process(frameData);
10246
+ frameData.isProcessing = false;
10247
+ }
10248
+ function getProjectionParent(element) {
10249
+ let ancestor = element.parentElement;
10250
+ while (ancestor) {
10251
+ const node = layoutNodes.get(ancestor);
10252
+ if (node && node.instance)
10253
+ return node;
10254
+ ancestor = ancestor.parentElement;
10255
+ }
10256
+ return undefined;
10257
+ }
10258
+ function createVisualElement() {
10259
+ return new HTMLVisualElement({
10260
+ props: {},
10261
+ presenceContext: null,
10262
+ visualState: {
10263
+ latestValues: {},
10264
+ renderState: {
10265
+ transform: {},
10266
+ transformOrigin: {},
10267
+ style: {},
10268
+ vars: {},
10269
+ },
10270
+ },
10271
+ }, { allowProjection: true });
10272
+ }
10273
+ function readNodeOptions(element, transition) {
10274
+ const layoutAttr = element.getAttribute("data-layout");
10275
+ const layoutId = element.getAttribute("data-layout-id") ?? undefined;
9490
10276
  return {
9491
- animationId: projection.root?.animationId ?? 0,
9492
- measuredBox,
9493
- layoutBox,
9494
- latestValues: projection.animationValues || projection.latestValues || {},
9495
- source: projection.id,
10277
+ layoutId,
10278
+ layout: layoutAttr !== null ? true : undefined,
10279
+ animationType: (!layoutAttr || layoutAttr === "true"
10280
+ ? "both"
10281
+ : layoutAttr),
10282
+ transition,
10283
+ };
10284
+ }
10285
+ function prepareNode(element, transition) {
10286
+ let node = layoutNodes.get(element);
10287
+ if (!node) {
10288
+ let visualElement = visualElementStore.get(element);
10289
+ if (!visualElement)
10290
+ visualElement = createVisualElement();
10291
+ /**
10292
+ * A first-time element may carry a projection transform in its
10293
+ * inline style (e.g. it was cloned from an element mid-animation).
10294
+ * That transform isn't tracked in latestValues so the engine can't
10295
+ * reset it before measuring - clear it now so the first layout
10296
+ * measurement isn't inflated.
10297
+ */
10298
+ if (element.style.transform &&
10299
+ !hasTransform(visualElement.latestValues)) {
10300
+ element.style.transform = "";
10301
+ }
10302
+ node = new HTMLProjectionNode(visualElement.latestValues, getProjectionParent(element));
10303
+ visualElement.projection = node;
10304
+ node.setOptions({
10305
+ ...readNodeOptions(element, transition),
10306
+ visualElement,
10307
+ });
10308
+ node.mount(element);
10309
+ layoutNodes.set(element, node);
10310
+ }
10311
+ else {
10312
+ node.setOptions(readNodeOptions(element, transition));
10313
+ }
10314
+ node.isPresent = true;
10315
+ if (node.options.onExitComplete) {
10316
+ node.setOptions({ onExitComplete: undefined });
10317
+ }
10318
+ return node;
10319
+ }
10320
+ function sortDocumentOrder(elements) {
10321
+ return [...elements].sort((a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
10322
+ }
10323
+ function dropNode(element, node) {
10324
+ node.setOptions({ onExitComplete: undefined });
10325
+ /**
10326
+ * Stop any lingering animation so it can't leak into future updates.
10327
+ * A follow node can share its currentAnimation with a surviving lead
10328
+ * (via resumingFrom), in which case it isn't ours to stop.
10329
+ */
10330
+ const stack = node.getStack();
10331
+ if (!stack || node.isLead())
10332
+ node.currentAnimation?.stop();
10333
+ node.unmount();
10334
+ layoutNodes.delete(element);
10335
+ }
10336
+ function flushPendingBuilders() {
10337
+ const builders = pendingBuilders;
10338
+ pendingBuilders = undefined;
10339
+ flushPendingFrame();
10340
+ /**
10341
+ * Discover and mount every node across all builders before snapshotting
10342
+ * any of them. Mounting during an active update flags isLayoutDirty,
10343
+ * which would make that node's own willUpdate skip its snapshot.
10344
+ * Document order guarantees ancestors mount before descendants, even
10345
+ * when they're discovered by different builders.
10346
+ */
10347
+ const targets = new Map();
10348
+ for (const builder of builders) {
10349
+ for (const element of builder.collectTargets()) {
10350
+ const owners = targets.get(element);
10351
+ owners ? owners.push(builder) : targets.set(element, [builder]);
10352
+ }
10353
+ }
10354
+ const union = new Map();
10355
+ for (const element of sortDocumentOrder(targets.keys())) {
10356
+ const owners = targets.get(element);
10357
+ const node = prepareNode(element, owners[owners.length - 1].transitionFor(element));
10358
+ for (const owner of owners)
10359
+ owner.adopt(element, node);
10360
+ union.set(element, node);
10361
+ }
10362
+ union.forEach((node) => {
10363
+ node.isLayoutDirty = false;
10364
+ node.willUpdate();
10365
+ });
10366
+ const updatePromises = [];
10367
+ for (const builder of builders) {
10368
+ const result = builder.runUpdate();
10369
+ if (result)
10370
+ updatePromises.push(result);
10371
+ }
10372
+ const commit = () => {
10373
+ /**
10374
+ * Process all additions before any removals so that, even across
10375
+ * builders, a removed member knows whether a replacement with the
10376
+ * same layoutId was added in this commit.
10377
+ */
10378
+ const newMemberIds = new Set();
10379
+ for (const builder of builders) {
10380
+ builder.reconcileAdditions(newMemberIds);
10381
+ }
10382
+ for (const builder of builders) {
10383
+ builder.reconcileRemovals(newMemberIds);
10384
+ }
10385
+ let root;
10386
+ union.forEach((node) => (root || (root = node.root)));
10387
+ for (const builder of builders)
10388
+ root || (root = builder.getRoot());
10389
+ root?.didUpdate();
10390
+ /**
10391
+ * The root flushes the update on a microtask, synchronously
10392
+ * processing the frame that creates the layout animations. Collect
10393
+ * them in a later microtask step of the same pass.
10394
+ */
10395
+ microtask.render(() => {
10396
+ for (const builder of builders)
10397
+ builder.finalize();
10398
+ });
9496
10399
  };
10400
+ updatePromises.length ? Promise.all(updatePromises).then(commit) : commit();
9497
10401
  }
9498
10402
  class LayoutAnimationBuilder {
9499
10403
  constructor(scope, updateDom, defaultOptions) {
9500
- this.sharedTransitions = new Map();
9501
- this.notifyReady = noop;
9502
- this.rejectReady = noop;
9503
10404
  this.scope = scope;
9504
10405
  this.updateDom = updateDom;
9505
10406
  this.defaultOptions = defaultOptions;
10407
+ this.sharedTransitions = new Map();
10408
+ this.notifyReady = () => { };
10409
+ this.rejectReady = () => { };
10410
+ this.tracked = new Map();
10411
+ this.restorePoints = new Map();
9506
10412
  this.readyPromise = new Promise((resolve, reject) => {
9507
10413
  this.notifyReady = resolve;
9508
10414
  this.rejectReady = reject;
9509
10415
  });
9510
- frame.postRender(() => {
9511
- this.start().then(this.notifyReady).catch(this.rejectReady);
9512
- });
10416
+ if (!pendingBuilders) {
10417
+ pendingBuilders = [];
10418
+ queueMicrotask(flushPendingBuilders);
10419
+ }
10420
+ pendingBuilders.push(this);
9513
10421
  }
9514
10422
  shared(id, transition) {
9515
10423
  this.sharedTransitions.set(id, transition);
@@ -9518,114 +10426,107 @@ class LayoutAnimationBuilder {
9518
10426
  then(resolve, reject) {
9519
10427
  return this.readyPromise.then(resolve, reject);
9520
10428
  }
9521
- async start() {
9522
- const beforeElements = collectLayoutElements(this.scope);
9523
- const beforeRecords = this.buildRecords(beforeElements);
9524
- beforeRecords.forEach(({ projection }) => {
9525
- const hasCurrentAnimation = Boolean(projection.currentAnimation);
9526
- const isSharedLayout = Boolean(projection.options.layoutId);
9527
- if (hasCurrentAnimation && isSharedLayout) {
9528
- const snapshot = snapshotFromTarget(projection);
9529
- if (snapshot) {
9530
- projection.snapshot = snapshot;
9531
- }
9532
- else if (projection.snapshot) {
9533
- projection.snapshot = undefined;
9534
- }
9535
- }
9536
- else if (projection.snapshot &&
9537
- (projection.currentAnimation || projection.isProjecting())) {
9538
- projection.snapshot = undefined;
9539
- }
9540
- projection.isPresent = true;
9541
- projection.willUpdate();
10429
+ transitionFor(element) {
10430
+ const layoutId = element.getAttribute("data-layout-id");
10431
+ return ((layoutId && this.sharedTransitions.get(layoutId)) ||
10432
+ this.defaultOptions);
10433
+ }
10434
+ adopt(element, node) {
10435
+ this.tracked.set(element, node);
10436
+ this.restorePoints.set(element, {
10437
+ parent: element.parentElement,
10438
+ next: element.nextSibling,
9542
10439
  });
9543
- await this.updateDom();
9544
- const afterElements = collectLayoutElements(this.scope);
9545
- const afterRecords = this.buildRecords(afterElements);
9546
- this.handleExitingElements(beforeRecords, afterRecords);
9547
- afterRecords.forEach(({ projection }) => {
9548
- const instance = projection.instance;
9549
- const resumeFromInstance = projection.resumeFrom
9550
- ?.instance;
9551
- if (!instance || !resumeFromInstance)
9552
- return;
9553
- if (!("style" in instance))
9554
- return;
9555
- const currentTransform = instance.style.transform;
9556
- const resumeFromTransform = resumeFromInstance.style.transform;
9557
- if (currentTransform &&
9558
- resumeFromTransform &&
9559
- currentTransform === resumeFromTransform) {
9560
- instance.style.transform = "";
9561
- instance.style.transformOrigin = "";
10440
+ }
10441
+ collectTargets() {
10442
+ return collectLayoutElements(this.scope);
10443
+ }
10444
+ runUpdate() {
10445
+ try {
10446
+ const result = this.updateDom();
10447
+ if (result && typeof result.then === "function") {
10448
+ return result.then(undefined, (error) => {
10449
+ this.updateError = error;
10450
+ });
9562
10451
  }
9563
- });
9564
- afterRecords.forEach(({ projection }) => {
9565
- projection.isPresent = true;
9566
- });
9567
- const root = getProjectionRoot(afterRecords, beforeRecords);
9568
- root?.didUpdate();
9569
- await new Promise((resolve) => {
9570
- frame.postRender(() => resolve());
9571
- });
9572
- const animations = collectAnimations(afterRecords);
9573
- const animation = new GroupAnimation(animations);
9574
- return animation;
10452
+ }
10453
+ catch (error) {
10454
+ this.updateError = error;
10455
+ }
10456
+ return undefined;
9575
10457
  }
9576
- buildRecords(elements) {
9577
- const records = [];
9578
- const recordMap = new Map();
9579
- for (const element of elements) {
9580
- const parentRecord = findParentRecord(element, recordMap, this.scope);
9581
- const { layout, layoutId } = readLayoutAttributes(element);
9582
- const override = layoutId
9583
- ? this.sharedTransitions.get(layoutId)
9584
- : undefined;
9585
- const transition = override || this.defaultOptions;
9586
- const record = getOrCreateRecord(element, parentRecord?.projection, {
9587
- layout,
9588
- layoutId,
9589
- animationType: typeof layout === "string" ? layout : "both",
9590
- transition: transition,
9591
- });
9592
- recordMap.set(element, record);
9593
- records.push(record);
10458
+ reconcileAdditions(newMemberIds) {
10459
+ for (const element of collectLayoutElements(this.scope)) {
10460
+ if (this.tracked.has(element))
10461
+ continue;
10462
+ const node = prepareNode(element, this.transitionFor(element));
10463
+ this.adopt(element, node);
10464
+ node.options.layoutId && newMemberIds.add(node.options.layoutId);
9594
10465
  }
9595
- return records;
9596
10466
  }
9597
- handleExitingElements(beforeRecords, afterRecords) {
9598
- const afterElementsSet = new Set(afterRecords.map((record) => record.element));
9599
- beforeRecords.forEach((record) => {
9600
- if (afterElementsSet.has(record.element))
10467
+ reconcileRemovals(newMemberIds) {
10468
+ this.tracked.forEach((node, element) => {
10469
+ if (element.isConnected)
9601
10470
  return;
9602
- // For shared layout elements, relegate to set up resumeFrom
9603
- // so the remaining element animates from this position
9604
- if (record.projection.options.layoutId) {
9605
- record.projection.isPresent = false;
9606
- record.projection.relegate();
9607
- }
9608
- record.visualElement.unmount();
9609
- visualElementStore.delete(record.element);
10471
+ const restore = this.restorePoints.get(element);
10472
+ this.restorePoints.delete(element);
10473
+ const { layoutId } = node.options;
10474
+ const stack = node.getStack();
10475
+ const hasSurvivor = stack &&
10476
+ stack.members.some((member) => member !== node &&
10477
+ member.instance
10478
+ ?.isConnected);
10479
+ /**
10480
+ * A removed lead with a surviving stack member - and no
10481
+ * replacement member added this commit - runs an exit
10482
+ * crossfade: restore the element to its old position in the
10483
+ * DOM, relegate it and let the survivor take over. It's
10484
+ * removed again once the animation completes.
10485
+ */
10486
+ if (layoutId &&
10487
+ node.isLead() &&
10488
+ hasSurvivor &&
10489
+ !newMemberIds.has(layoutId)) {
10490
+ if (restore && restore.parent.isConnected) {
10491
+ restore.parent.insertBefore(element, restore.next && restore.next.parentNode === restore.parent
10492
+ ? restore.next
10493
+ : null);
10494
+ node.isPresent = false;
10495
+ node.setOptions({
10496
+ onExitComplete: () => {
10497
+ element.remove();
10498
+ dropNode(element, node);
10499
+ },
10500
+ });
10501
+ if (node.relegate())
10502
+ return;
10503
+ element.remove();
10504
+ }
10505
+ }
10506
+ dropNode(element, node);
10507
+ this.tracked.delete(element);
9610
10508
  });
9611
- // Clear resumeFrom on EXISTING nodes that point to unmounted projections
9612
- // This prevents crossfade animation when the source element was removed entirely
9613
- // But preserve resumeFrom for NEW nodes so they can animate from the old position
9614
- // Also preserve resumeFrom for lead nodes that were just promoted via relegate
9615
- const beforeElementsSet = new Set(beforeRecords.map((record) => record.element));
9616
- afterRecords.forEach(({ element, projection }) => {
9617
- if (beforeElementsSet.has(element) &&
9618
- projection.resumeFrom &&
9619
- !projection.resumeFrom.instance &&
9620
- !projection.isLead()) {
9621
- projection.resumeFrom = undefined;
9622
- projection.snapshot = undefined;
10509
+ }
10510
+ getRoot() {
10511
+ let root;
10512
+ this.tracked.forEach((node) => (root || (root = node.root)));
10513
+ return root;
10514
+ }
10515
+ finalize() {
10516
+ if (this.updateError) {
10517
+ this.rejectReady(this.updateError);
10518
+ return;
10519
+ }
10520
+ const animations = new Set();
10521
+ this.tracked.forEach((node) => {
10522
+ if (node.instance && node.currentAnimation) {
10523
+ animations.add(node.currentAnimation);
9623
10524
  }
9624
10525
  });
10526
+ this.notifyReady(new GroupAnimation([...animations]));
9625
10527
  }
9626
10528
  }
9627
10529
  function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9628
- // animateLayout(updateDom)
9629
10530
  if (typeof scopeOrUpdateDom === "function") {
9630
10531
  return {
9631
10532
  scope: document,
@@ -9633,107 +10534,15 @@ function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9633
10534
  defaultOptions: updateDomOrOptions,
9634
10535
  };
9635
10536
  }
9636
- // animateLayout(scope, updateDom, options?)
9637
- const elements = resolveElements(scopeOrUpdateDom);
9638
- const scope = elements[0] || document;
10537
+ const scope = scopeOrUpdateDom instanceof Document
10538
+ ? scopeOrUpdateDom
10539
+ : resolveElements(scopeOrUpdateDom)[0] ?? document;
9639
10540
  return {
9640
10541
  scope,
9641
10542
  updateDom: updateDomOrOptions,
9642
10543
  defaultOptions: options,
9643
10544
  };
9644
10545
  }
9645
- function collectLayoutElements(scope) {
9646
- const elements = Array.from(scope.querySelectorAll(layoutSelector));
9647
- if (scope instanceof Element && scope.matches(layoutSelector)) {
9648
- if (!elements.includes(scope)) {
9649
- elements.unshift(scope);
9650
- }
9651
- }
9652
- return elements;
9653
- }
9654
- function readLayoutAttributes(element) {
9655
- const layoutId = element.getAttribute("data-layout-id") || undefined;
9656
- const rawLayout = element.getAttribute("data-layout");
9657
- let layout;
9658
- if (rawLayout === "" || rawLayout === "true") {
9659
- layout = true;
9660
- }
9661
- else if (rawLayout) {
9662
- layout = rawLayout;
9663
- }
9664
- return {
9665
- layout,
9666
- layoutId,
9667
- };
9668
- }
9669
- function createVisualState() {
9670
- return {
9671
- latestValues: {},
9672
- renderState: {
9673
- transform: {},
9674
- transformOrigin: {},
9675
- style: {},
9676
- vars: {},
9677
- },
9678
- };
9679
- }
9680
- function getOrCreateRecord(element, parentProjection, projectionOptions) {
9681
- const existing = visualElementStore.get(element);
9682
- const visualElement = existing ??
9683
- new HTMLVisualElement({
9684
- props: {},
9685
- presenceContext: null,
9686
- visualState: createVisualState(),
9687
- }, { allowProjection: true });
9688
- if (!existing || !visualElement.projection) {
9689
- visualElement.projection = new HTMLProjectionNode(visualElement.latestValues, parentProjection);
9690
- }
9691
- visualElement.projection.setOptions({
9692
- ...projectionOptions,
9693
- visualElement,
9694
- });
9695
- if (!visualElement.current) {
9696
- visualElement.mount(element);
9697
- }
9698
- else if (!visualElement.projection.instance) {
9699
- // Mount projection if VisualElement is already mounted but projection isn't
9700
- // This happens when animate() was called before animateLayout()
9701
- visualElement.projection.mount(element);
9702
- }
9703
- if (!existing) {
9704
- visualElementStore.set(element, visualElement);
9705
- }
9706
- return {
9707
- element,
9708
- visualElement,
9709
- projection: visualElement.projection,
9710
- };
9711
- }
9712
- function findParentRecord(element, recordMap, scope) {
9713
- let parent = element.parentElement;
9714
- while (parent) {
9715
- const record = recordMap.get(parent);
9716
- if (record)
9717
- return record;
9718
- if (parent === scope)
9719
- break;
9720
- parent = parent.parentElement;
9721
- }
9722
- return undefined;
9723
- }
9724
- function getProjectionRoot(afterRecords, beforeRecords) {
9725
- const record = afterRecords[0] || beforeRecords[0];
9726
- return record?.projection.root;
9727
- }
9728
- function collectAnimations(afterRecords) {
9729
- const animations = new Set();
9730
- afterRecords.forEach((record) => {
9731
- const animation = record.projection.currentAnimation;
9732
- if (animation)
9733
- animations.add(animation);
9734
- });
9735
- return Array.from(animations);
9736
- }
9737
10546
 
9738
10547
  /**
9739
10548
  * @deprecated
@@ -9774,7 +10583,6 @@ exports.SVGVisualElement = SVGVisualElement;
9774
10583
  exports.ViewTransitionBuilder = ViewTransitionBuilder;
9775
10584
  exports.VisualElement = VisualElement;
9776
10585
  exports.acceleratedValues = acceleratedValues;
9777
- exports.activeAnimations = activeAnimations;
9778
10586
  exports.addAttrValue = addAttrValue;
9779
10587
  exports.addDomEvent = addDomEvent;
9780
10588
  exports.addScaleCorrector = addScaleCorrector;
@@ -9796,6 +10604,7 @@ exports.applyGeneratorOptions = applyGeneratorOptions;
9796
10604
  exports.applyPointDelta = applyPointDelta;
9797
10605
  exports.applyPxDefaults = applyPxDefaults;
9798
10606
  exports.applyTreeDeltas = applyTreeDeltas;
10607
+ exports.arc = arc;
9799
10608
  exports.aspectRatio = aspectRatio;
9800
10609
  exports.attachFollow = attachFollow;
9801
10610
  exports.attachSpring = attachSpring;