motion-dom 14.1.0 → 14.2.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 (41) hide show
  1. package/dist/cjs/index.js +1165 -187
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/es/animation/AsyncMotionValueAnimation.mjs +19 -1
  4. package/dist/es/animation/AsyncMotionValueAnimation.mjs.map +1 -1
  5. package/dist/es/animation/JSAnimation.mjs +54 -24
  6. package/dist/es/animation/JSAnimation.mjs.map +1 -1
  7. package/dist/es/animation/NativeAnimationExtended.mjs +47 -20
  8. package/dist/es/animation/NativeAnimationExtended.mjs.map +1 -1
  9. package/dist/es/animation/generators/utils/create-generator-easing.mjs +14 -1
  10. package/dist/es/animation/generators/utils/create-generator-easing.mjs.map +1 -1
  11. package/dist/es/animation/interfaces/motion-value.mjs +1 -0
  12. package/dist/es/animation/interfaces/motion-value.mjs.map +1 -1
  13. package/dist/es/animation/keyframes/DOMKeyframesResolver.mjs +25 -1
  14. package/dist/es/animation/keyframes/DOMKeyframesResolver.mjs.map +1 -1
  15. package/dist/es/animation/waapi/supports/waapi.mjs +1 -1
  16. package/dist/es/animation/waapi/supports/waapi.mjs.map +1 -1
  17. package/dist/es/animation/waapi/transforms/TransformAnimation.mjs +854 -0
  18. package/dist/es/animation/waapi/transforms/TransformAnimation.mjs.map +1 -0
  19. package/dist/es/animation/waapi/transforms/groups.mjs +4 -0
  20. package/dist/es/animation/waapi/transforms/groups.mjs.map +1 -0
  21. package/dist/es/effects/style/index.mjs +6 -3
  22. package/dist/es/effects/style/index.mjs.map +1 -1
  23. package/dist/es/effects/style/transform.mjs +2 -7
  24. package/dist/es/effects/style/transform.mjs.map +1 -1
  25. package/dist/es/index.mjs +3 -3
  26. package/dist/es/projection/node/create-projection-node.mjs +10 -0
  27. package/dist/es/projection/node/create-projection-node.mjs.map +1 -1
  28. package/dist/es/render/VisualElement.mjs +16 -3
  29. package/dist/es/render/VisualElement.mjs.map +1 -1
  30. package/dist/es/render/html/utils/build-transform.mjs +1 -1
  31. package/dist/es/render/html/utils/build-transform.mjs.map +1 -1
  32. package/dist/es/value/index.mjs +12 -0
  33. package/dist/es/value/index.mjs.map +1 -1
  34. package/dist/index.d.ts +77 -12
  35. package/dist/motion-dom.dev.js +1165 -187
  36. package/dist/motion-dom.js +1 -1
  37. package/dist/size-rollup-motion-value.js +1 -1
  38. package/dist/size-rollup-motion-value.js.map +1 -1
  39. package/dist/size-rollup-style-effect.js +1 -1
  40. package/dist/size-rollup-style-effect.js.map +1 -1
  41. package/package.json +3 -3
@@ -805,7 +805,20 @@
805
805
  * Create a progress => progress easing function from a generator.
806
806
  */
807
807
  function createGeneratorEasing(options, scale = 100, createGenerator) {
808
- const generator = createGenerator({ ...options, keyframes: [0, scale] });
808
+ /**
809
+ * The easing is generated over 0 - scale, but velocity is in the
810
+ * value's own units, so scale it to match. Otherwise an interrupted
811
+ * spring hands off the wrong speed, or direction. Keyframes with
812
+ * units (colours, filters, mixed units) give NaN, which is falsy,
813
+ * so their velocity passes through unscaled.
814
+ */
815
+ const { keyframes: k, velocity: v } = options;
816
+ const delta = k && k[k.length - 1] - k[0];
817
+ const generator = createGenerator({
818
+ ...options,
819
+ velocity: v && delta ? (v * scale) / delta : v,
820
+ keyframes: [0, scale],
821
+ });
809
822
  const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);
810
823
  return {
811
824
  type: "keyframes",
@@ -1586,6 +1599,7 @@
1586
1599
  }
1587
1600
 
1588
1601
  const percentToProgress = (percent) => percent / 100;
1602
+ const round = (value) => Math.round(value * 10000) / 10000;
1589
1603
  class JSAnimation extends WithPromise {
1590
1604
  constructor(options) {
1591
1605
  super();
@@ -1693,10 +1707,10 @@
1693
1707
  }
1694
1708
  }
1695
1709
  tick(timestamp, sample = false) {
1696
- const { generator, totalDuration, mixKeyframes, mirroredGenerator, resolvedDuration, calculatedDuration, } = this;
1710
+ const { generator, totalDuration, calculatedDuration } = this;
1697
1711
  if (this.startTime === null)
1698
1712
  return generator.next(0);
1699
- const { delay = 0, keyframes, repeat, repeatType, repeatDelay, type, onUpdate, finalKeyframe, } = this.options;
1713
+ const { delay = 0, keyframes, type, onUpdate, finalKeyframe, } = this.options;
1700
1714
  if (this.startTime === this.pendingStartTime) {
1701
1715
  this.startTime = resolveStartTime(this.startTime, timestamp);
1702
1716
  }
@@ -1729,7 +1743,55 @@
1729
1743
  if (this.state === "finished" && this.holdTime === null) {
1730
1744
  this.currentTime = totalDuration;
1731
1745
  }
1732
- let elapsed = this.currentTime;
1746
+ const state = this.generate(this.currentTime, isInDelayPhase);
1747
+ let { done } = state;
1748
+ if (!isInDelayPhase && calculatedDuration !== null) {
1749
+ done =
1750
+ this.playbackSpeed >= 0
1751
+ ? this.currentTime >= totalDuration
1752
+ : this.currentTime <= 0;
1753
+ }
1754
+ const isAnimationFinished = this.holdTime === null &&
1755
+ (this.state === "finished" || (this.state === "running" && done));
1756
+ // TODO: The exception for inertia could be cleaner here
1757
+ if (isAnimationFinished && type !== inertia) {
1758
+ state.value = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
1759
+ }
1760
+ if (onUpdate) {
1761
+ onUpdate(state.value);
1762
+ }
1763
+ if (isAnimationFinished) {
1764
+ this.finish();
1765
+ }
1766
+ return state;
1767
+ }
1768
+ /**
1769
+ * This animation's time, including delay, at a timestamp.
1770
+ */
1771
+ at(timestamp) {
1772
+ return (this.holdTime ??
1773
+ round((timestamp - this.startTime) * this.playbackSpeed));
1774
+ }
1775
+ /**
1776
+ * The value at a timestamp, without changing this animation's state.
1777
+ * If resolved, it ends at the last resolved keyframe, which is in the
1778
+ * same unit as the others, rather than at finalKeyframe.
1779
+ */
1780
+ sampleAt(timestamp, resolved) {
1781
+ const { options, totalDuration } = this;
1782
+ const t = this.at(timestamp) - (options.delay || 0);
1783
+ return t >= totalDuration && options.type !== inertia
1784
+ ? getFinalKeyframe(options.keyframes, options, resolved ? undefined : options.finalKeyframe)
1785
+ : this.generate(Math.max(t, 0), t < 0).value;
1786
+ }
1787
+ /**
1788
+ * The generator's state `currentTime` ms after the delay, without
1789
+ * changing the animation's own state.
1790
+ */
1791
+ generate(currentTime, isInDelayPhase) {
1792
+ const { generator, totalDuration, mixKeyframes, mirroredGenerator, resolvedDuration, } = this;
1793
+ const { keyframes, repeat, repeatType, repeatDelay } = this.options;
1794
+ let elapsed = currentTime;
1733
1795
  let frameGenerator = generator;
1734
1796
  if (repeat) {
1735
1797
  /**
@@ -1737,7 +1799,7 @@
1737
1799
  * than duration we'll get values like 2.5 (midway through the
1738
1800
  * third iteration)
1739
1801
  */
1740
- const progress = Math.min(this.currentTime, totalDuration) / resolvedDuration;
1802
+ const progress = Math.min(currentTime, totalDuration) / resolvedDuration;
1741
1803
  /**
1742
1804
  * Get the current iteration (0 indexed). For instance the floor of
1743
1805
  * 2.5 is 2.
@@ -1790,25 +1852,6 @@
1790
1852
  if (mixKeyframes && !isInDelayPhase) {
1791
1853
  state.value = mixKeyframes(state.value);
1792
1854
  }
1793
- let { done } = state;
1794
- if (!isInDelayPhase && calculatedDuration !== null) {
1795
- done =
1796
- this.playbackSpeed >= 0
1797
- ? this.currentTime >= totalDuration
1798
- : this.currentTime <= 0;
1799
- }
1800
- const isAnimationFinished = this.holdTime === null &&
1801
- (this.state === "finished" || (this.state === "running" && done));
1802
- // TODO: The exception for inertia could be cleaner here
1803
- if (isAnimationFinished && type !== inertia) {
1804
- state.value = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
1805
- }
1806
- if (onUpdate) {
1807
- onUpdate(state.value);
1808
- }
1809
- if (isAnimationFinished) {
1810
- this.finish();
1811
- }
1812
1855
  return state;
1813
1856
  }
1814
1857
  /**
@@ -2817,44 +2860,71 @@
2817
2860
  }
2818
2861
  this.options = options;
2819
2862
  }
2863
+ /**
2864
+ * The animation's time now, in ms. Wall-clock rather than WAAPI's
2865
+ * currentTime while running, as under CPU load currentTime may not
2866
+ * reflect the actual elapsed time, causing incorrect sampling and
2867
+ * visual jumps.
2868
+ */
2869
+ elapsed() {
2870
+ return this.state === "running"
2871
+ ? (time.now() - this.startTime) * this.speed
2872
+ : this.time * 1000;
2873
+ }
2874
+ /**
2875
+ * The value at a time, from a renderless JS animation.
2876
+ */
2877
+ sample(sampleTime) {
2878
+ if (!this.sampler) {
2879
+ const { motionValue, onUpdate, onComplete, onPlay, onStop, element, ...options } = this.options;
2880
+ /**
2881
+ * Stop it straight away so its driver doesn't run every frame.
2882
+ * It can still be sampled.
2883
+ */
2884
+ this.sampler = new JSAnimation({ ...options, autoplay: false });
2885
+ this.sampler.stop();
2886
+ }
2887
+ return this.sampler.sample(Math.max(0, sampleTime)).value;
2888
+ }
2889
+ /**
2890
+ * The value now, as WAAPI doesn't set the motion value while it runs.
2891
+ */
2892
+ liveValue() {
2893
+ const { state } = this;
2894
+ if (state === "running" || state === "paused") {
2895
+ return this.sample(this.elapsed());
2896
+ }
2897
+ }
2820
2898
  /**
2821
2899
  * WAAPI doesn't natively have any interruption capabilities.
2822
2900
  *
2823
2901
  * Rather than read committed styles back out of the DOM, we can
2824
- * create a renderless JS animation and sample it twice to calculate
2825
- * its current value, "previous" value, and therefore allow
2826
- * Motion to calculate velocity for any subsequent animation.
2902
+ * sample a renderless JS animation twice to calculate its current
2903
+ * value, "previous" value, and therefore allow Motion to calculate
2904
+ * velocity for any subsequent animation.
2827
2905
  */
2828
2906
  updateMotionValue(value) {
2829
- const { motionValue, onUpdate, onComplete, element, ...options } = this.options;
2907
+ const { motionValue, element, name } = this.options;
2830
2908
  if (!motionValue)
2831
2909
  return;
2832
2910
  if (value !== undefined) {
2833
2911
  motionValue.set(value);
2834
2912
  return;
2835
2913
  }
2836
- const sampleAnimation = new JSAnimation({
2837
- ...options,
2838
- autoplay: false,
2839
- });
2840
- /**
2841
- * Use wall-clock elapsed time for sampling.
2842
- * Under CPU load, WAAPI's currentTime may not reflect actual
2843
- * elapsed time, causing incorrect sampling and visual jumps.
2844
- */
2845
- const sampleTime = Math.max(sampleDelta, time.now() - this.startTime);
2846
- const delta = motionUtils.clamp(0, sampleDelta, sampleTime - sampleDelta);
2847
- const current = sampleAnimation.sample(sampleTime).value;
2914
+ const { speed } = this;
2915
+ const sampleTime = this.elapsed();
2916
+ const delta = this.state === "running" && speed
2917
+ ? motionUtils.clamp(0, sampleDelta, sampleTime)
2918
+ : 0;
2919
+ const current = this.sample(sampleTime);
2848
2920
  /**
2849
2921
  * Write the estimated value to inline style so it persists
2850
2922
  * after cancel(), covering the async gap before the next
2851
2923
  * animation starts.
2852
2924
  */
2853
- const { name } = this.options;
2854
2925
  if (element && name)
2855
2926
  setStyle(element, name, current);
2856
- motionValue.setWithVelocity(sampleAnimation.sample(Math.max(0, sampleTime - delta)).value, current, delta);
2857
- sampleAnimation.stop();
2927
+ motionValue.setWithVelocity(this.sample(sampleTime - delta * Math.sign(speed)), current, delta / Math.abs(speed || 1));
2858
2928
  }
2859
2929
  }
2860
2930
 
@@ -2948,64 +3018,973 @@
2948
3018
  browserColorFunctions.test(keyframes[i])) {
2949
3019
  return true;
2950
3020
  }
2951
- }
2952
- return false;
2953
- }
2954
-
2955
- const colorProperties = new Set([
2956
- "color",
2957
- "backgroundColor",
2958
- "outlineColor",
2959
- "fill",
2960
- "stroke",
2961
- "borderColor",
2962
- "borderTopColor",
2963
- "borderRightColor",
2964
- "borderBottomColor",
2965
- "borderLeftColor",
2966
- ]);
2967
- const supportsWaapi = /*@__PURE__*/ motionUtils.memo(() => Object.hasOwnProperty.call(Element.prototype, "animate"));
2968
- function supportsBrowserAnimation(options) {
2969
- const { motionValue, name, repeatDelay, repeatType, damping, type, keyframes, } = options;
3021
+ }
3022
+ return false;
3023
+ }
3024
+
3025
+ const colorProperties = new Set([
3026
+ "color",
3027
+ "backgroundColor",
3028
+ "outlineColor",
3029
+ "fill",
3030
+ "stroke",
3031
+ "borderColor",
3032
+ "borderTopColor",
3033
+ "borderRightColor",
3034
+ "borderBottomColor",
3035
+ "borderLeftColor",
3036
+ ]);
3037
+ const supportsWaapi = /*@__PURE__*/ motionUtils.memo(() => Object.hasOwnProperty.call(Element.prototype, "animate"));
3038
+ function supportsBrowserAnimation(options) {
3039
+ const { motionValue, name, repeatDelay, repeatType, damping, type, keyframes, } = options;
3040
+ /**
3041
+ * Most values can't be accelerated at all, so check the name before
3042
+ * looking at the element or its props.
3043
+ */
3044
+ if (!name ||
3045
+ !(acceleratedValues.has(name) || colorProperties.has(name))) {
3046
+ return false;
3047
+ }
3048
+ const subject = motionValue?.owner?.current;
3049
+ /**
3050
+ * We use instanceof checks instead of isHTMLElement()/isSVGElement()
3051
+ * because we explicitly **don't** want elements in different timing
3052
+ * contexts (i.e. popups) to be accelerated, as it's not possible to sync
3053
+ * these animations properly with those driven from the main window
3054
+ * frameloop.
3055
+ */
3056
+ if (!(subject instanceof HTMLElement) &&
3057
+ !(subject instanceof SVGElement)) {
3058
+ return false;
3059
+ }
3060
+ const { onUpdate, transformTemplate } = motionValue.owner.getProps();
3061
+ return (supportsWaapi() &&
3062
+ /**
3063
+ * Force WAAPI for color properties with browser-only color formats
3064
+ * (oklch, oklab, lab, lch, etc.) that the JS animation path can't parse.
3065
+ */
3066
+ (acceleratedValues.has(name) ||
3067
+ (colorProperties.has(name) &&
3068
+ hasBrowserOnlyColors(keyframes))) &&
3069
+ (name !== "transform" || !transformTemplate) &&
3070
+ /**
3071
+ * If we're outputting values to onUpdate then we can't use WAAPI as there's
3072
+ * no way to read the value from WAAPI every frame.
3073
+ */
3074
+ !onUpdate &&
3075
+ !repeatDelay &&
3076
+ repeatType !== "mirror" &&
3077
+ damping !== 0 &&
3078
+ type !== "inertia");
3079
+ }
3080
+
3081
+ /**
3082
+ * Provided a value and a ValueType, returns the value as that value type.
3083
+ */
3084
+ const getValueAsType = (value, type) => {
3085
+ return type && typeof value === "number"
3086
+ ? type.transform(value)
3087
+ : value;
3088
+ };
3089
+
3090
+ const translateAlias = {
3091
+ x: "translateX",
3092
+ y: "translateY",
3093
+ z: "translateZ",
3094
+ transformPerspective: "perspective",
3095
+ };
3096
+ const numTransforms = transformPropOrder.length;
3097
+ /**
3098
+ * Build a CSS transform style from individual x/y/scale etc properties.
3099
+ *
3100
+ * This outputs with a default order of transforms/scales/rotations, this can be customised by
3101
+ * providing a transformTemplate function.
3102
+ */
3103
+ function buildTransform$1(latestValues, transform, transformTemplate) {
3104
+ // The transform string we're going to build into.
3105
+ let transformString = "";
3106
+ let transformIsDefault = true;
3107
+ /**
3108
+ * Loop over all possible transforms in order, adding the ones that
3109
+ * are present to the transform string.
3110
+ */
3111
+ for (let i = 0; i < numTransforms; i++) {
3112
+ const key = transformPropOrder[i];
3113
+ const value = latestValues[key];
3114
+ if (value === undefined)
3115
+ continue;
3116
+ let valueIsDefault = true;
3117
+ if (typeof value === "number") {
3118
+ valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
3119
+ }
3120
+ else {
3121
+ const parsed = parseFloat(value);
3122
+ valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0;
3123
+ }
3124
+ if (!valueIsDefault || transformTemplate) {
3125
+ const valueAsType = getValueAsType(value, numberValueTypes[key]);
3126
+ if (!valueIsDefault) {
3127
+ transformIsDefault = false;
3128
+ const transformName = translateAlias[key] || key;
3129
+ transformString += `${transformName}(${valueAsType}) `;
3130
+ }
3131
+ if (transformTemplate) {
3132
+ transform[key] = valueAsType;
3133
+ }
3134
+ }
3135
+ }
3136
+ // `pathRotation` composes onto `rotate` as a separate additive term so
3137
+ // the user's `rotate` is never clobbered. Deliberately not a slot in
3138
+ // `transformPropOrder`.
3139
+ const pathRotation = latestValues.pathRotation;
3140
+ if (pathRotation) {
3141
+ transformIsDefault = false;
3142
+ transformString += `rotate(${getValueAsType(pathRotation, numberValueTypes.pathRotation)}) `;
3143
+ }
3144
+ transformString = transformString.trim();
3145
+ // If we have a custom `transform` template, pass our transform values and
3146
+ // generated transformString to that before returning
3147
+ if (transformTemplate) {
3148
+ transformString = transformTemplate(transform, transformIsDefault ? "" : transformString);
3149
+ }
3150
+ else if (transformIsDefault) {
3151
+ transformString = "none";
3152
+ }
3153
+ return transformString;
3154
+ }
3155
+
3156
+ const transformGroups = new WeakMap();
3157
+
3158
+ /**
3159
+ * Sample at the interruption sampling rate, up to a cap for long
3160
+ * animations.
3161
+ */
3162
+ const maxSamples = 200;
3163
+ /**
3164
+ * How far values may stray from the WAAPI animation: as a fraction of
3165
+ * each value's change when they share an easing, otherwise in px or deg,
3166
+ * or for scale.
3167
+ */
3168
+ const easingTolerance = 0.001;
3169
+ const sampleTolerance = 0.1;
3170
+ const scaleTolerance = 0.001;
3171
+ /**
3172
+ * If an outside write, or a seek the WAAPI animation can't follow,
3173
+ * happens again within this window, the group is being driven every
3174
+ * frame (scrubbing, drag), which is cheaper on the main thread than
3175
+ * rebuilding the WAAPI animation every frame.
3176
+ */
3177
+ const churnWindow = 100;
3178
+ /**
3179
+ * Named easings that are the same cubic-bezier in JS and CSS.
3180
+ */
3181
+ const isNativeEasing = (ease) => /^(linear|ease(In|Out|InOut))$/.test(ease);
3182
+ const byTime = (a, b) => a - b;
3183
+ /**
3184
+ * n + 1 evenly spaced timestamps, from one timestamp to another.
3185
+ */
3186
+ const spread = (from, to, n) => {
3187
+ const result = [];
3188
+ for (let i = 0; i <= n; i++)
3189
+ result.push(mixNumber$1(from, to, i / n));
3190
+ return result;
3191
+ };
3192
+ const getOwner = (options) => options.motionValue.owner;
3193
+ const getGroup = (element) => transformGroups.get(element);
3194
+ const read = (owner, key) => owner.latestValues ? owner.latestValues[key] : owner.getValue(key)?.get();
3195
+ /**
3196
+ * Whether this animation should join its element's transform group.
3197
+ * Animations that can't be accelerated still join, so the group knows
3198
+ * to stay on the main thread while they run. Browsers without linear()
3199
+ * easing stay on the main thread.
3200
+ */
3201
+ const canGroupTransform = ({ name, motionValue, }) => name &&
3202
+ transformPropOrder.includes(name) &&
3203
+ motionValue?.owner?.current instanceof HTMLElement &&
3204
+ supportsWaapi() &&
3205
+ supportsLinearEasing();
3206
+ function canAccelerateTransform(options) {
3207
+ const owner = getOwner(options);
3208
+ const { onUpdate, transformTemplate } = owner.getProps();
3209
+ return (
3210
+ /**
3211
+ * A handoff from an optimised appear animation is already running
3212
+ * on its own WAAPI animation. onUpdate needs every value, every
3213
+ * frame.
3214
+ */
3215
+ !options.isHandoff &&
3216
+ !onUpdate &&
3217
+ !options.hasOnUpdate &&
3218
+ /**
3219
+ * transformTemplate could output anything.
3220
+ */
3221
+ !transformTemplate &&
3222
+ options.type !== "inertia" &&
3223
+ /**
3224
+ * A literal transform, or pathRotation, replaces or adds to the
3225
+ * transform we'd build. styleEffect builds its own as "none".
3226
+ */
3227
+ (read(owner, "transform") || "none") === "none" &&
3228
+ !read(owner, "pathRotation") &&
3229
+ /**
3230
+ * Layout animations write transform every frame.
3231
+ */
3232
+ !owner.projection?.isProjecting());
3233
+ }
3234
+ class TransformAnimation extends JSAnimation {
3235
+ constructor(options) {
3236
+ const element = getOwner(options).current;
3237
+ const { driver = frameloopDriver } = options;
3238
+ /**
3239
+ * Before JSAnimation replaces the type with its generator.
3240
+ */
3241
+ const canAccelerate = canAccelerateTransform(options);
3242
+ /**
3243
+ * The driver ticks on the main thread only once the group has
3244
+ * moved there. Until then, starting or stopping tells the group to
3245
+ * update its WAAPI animation.
3246
+ */
3247
+ options.driver = (update) => {
3248
+ const js = driver(update);
3249
+ return {
3250
+ js,
3251
+ now: js.now,
3252
+ start: (keepAlive = true) => {
3253
+ const group = getGroup(element);
3254
+ const isJS = !group || group.isJS;
3255
+ /**
3256
+ * keepAlive is false when seeking. Seeking the WAAPI
3257
+ * animation is free, but if a seek needs a rebuild and
3258
+ * keeps happening, the group moves to the main thread.
3259
+ */
3260
+ isJS
3261
+ ? js.start(keepAlive)
3262
+ : group.schedule(false, !keepAlive);
3263
+ },
3264
+ stop: () => {
3265
+ js.stop();
3266
+ const group = getGroup(element);
3267
+ group?.schedule(!group.isFinishing);
3268
+ },
3269
+ };
3270
+ };
3271
+ super(options);
3272
+ this.canAccelerate = canAccelerate;
3273
+ /**
3274
+ * stop is bound in JSAnimation, so wrap it rather than override.
3275
+ * Before stopping, set the motion value to where the WAAPI
3276
+ * animation is now, with velocity, for the next animation to
3277
+ * start from.
3278
+ */
3279
+ const { stop } = this;
3280
+ this.stop = () => {
3281
+ this.isAccelerated() && this.sync();
3282
+ stop();
3283
+ };
3284
+ }
3285
+ get group() {
3286
+ return getGroup(getOwner(this.options).current);
3287
+ }
3288
+ get js() {
3289
+ return this.driver?.js;
3290
+ }
3291
+ get name() {
3292
+ return this.options.name;
3293
+ }
3294
+ /**
3295
+ * When this stops moving, or, if it repeats forever, when it starts
3296
+ * repeating, and how long each repeat takes. Held (paused, or at
3297
+ * speed 0) animations never stop moving.
3298
+ */
3299
+ timing() {
3300
+ const { startTime, speed, totalDuration } = this;
3301
+ const { delay = 0, repeatType } = this.options;
3302
+ return this.holdTime !== null
3303
+ ? [Infinity, 0]
3304
+ : totalDuration === Infinity
3305
+ ? [
3306
+ startTime + delay / speed,
3307
+ (this.resolvedDuration * (repeatType === "loop" ? 1 : 2)) /
3308
+ speed || 1,
3309
+ ]
3310
+ : [startTime + (delay + totalDuration) / speed, 0];
3311
+ }
3312
+ /**
3313
+ * Whether this is running, or paused, on the compositor.
3314
+ */
3315
+ isAccelerated() {
3316
+ const { group, state } = this;
3317
+ return (group?.tracks.has(this) &&
3318
+ !group.isJS &&
3319
+ this.canAccelerate &&
3320
+ (state === "running" || state === "paused"));
3321
+ }
3322
+ /**
3323
+ * The value now, while this runs on the compositor and so doesn't
3324
+ * set its motion value every frame.
3325
+ */
3326
+ liveValue() {
3327
+ return this.isAccelerated() ? this.sampleAt(time.now()) : undefined;
3328
+ }
3329
+ /**
3330
+ * If this is a two-keyframe tween whose easing WAAPI runs exactly,
3331
+ * when it starts and stops moving, and that easing.
3332
+ */
3333
+ tween() {
3334
+ const { keyframes: keyframes$1, type, ease, times, repeat, delay = 0 } = this.options;
3335
+ const easing = motionUtils.isBezierDefinition(ease)
3336
+ ? cubicBezierAsString(ease)
3337
+ : isNativeEasing(ease) && supportedWaapiEasing[ease];
3338
+ if (easing &&
3339
+ !repeat &&
3340
+ !times &&
3341
+ keyframes$1.length === 2 &&
3342
+ type === keyframes &&
3343
+ this.holdTime === null) {
3344
+ const start = this.startTime + delay / this.speed;
3345
+ return [start, start + this.resolvedDuration / this.speed, easing];
3346
+ }
3347
+ }
3348
+ /**
3349
+ * The timestamps between two timestamps where this reaches a
3350
+ * keyframe or starts a repeat, where it can turn or jump.
3351
+ */
3352
+ boundaries(from, to) {
3353
+ const { startTime, speed, resolvedDuration, options } = this;
3354
+ const { delay = 0, repeat = 0, repeatDelay = 0, repeatType, times, keyframes: keyframes$1, type, } = options;
3355
+ const offsets = (type || keyframes) === keyframes
3356
+ ? times || defaultOffset(keyframes$1)
3357
+ : [0, 1];
3358
+ const start = startTime + delay / speed;
3359
+ const result = [];
3360
+ if (this.holdTime !== null || !(resolvedDuration > 0))
3361
+ return result;
3362
+ for (let i = Math.max(0, Math.floor(((from - start) * speed) / resolvedDuration)); i <= repeat; i++) {
3363
+ const iterationStart = start + (i * resolvedDuration) / speed;
3364
+ if (iterationStart > to)
3365
+ break;
3366
+ for (const offset of offsets) {
3367
+ const t = iterationStart +
3368
+ ((i % 2 && repeatType && repeatType !== "loop"
3369
+ ? 1 - offset
3370
+ : offset) *
3371
+ (resolvedDuration - repeatDelay)) /
3372
+ speed;
3373
+ t > from && t < to && result.push(t);
3374
+ }
3375
+ }
3376
+ return result;
3377
+ }
3378
+ /**
3379
+ * The value at a timestamp, as a number.
3380
+ */
3381
+ numberAt(timestamp) {
3382
+ return parseFloat(this.sampleAt(timestamp, true));
3383
+ }
3384
+ /**
3385
+ * Write the current value, and velocity, to the motion value.
3386
+ */
3387
+ sync() {
3388
+ const now = time.now();
3389
+ this.options.motionValue.setWithVelocity(this.sampleAt(now - sampleDelta, true), this.sampleAt(now, true), sampleDelta);
3390
+ }
3391
+ play() {
3392
+ /**
3393
+ * A stopped animation (one that was interrupted) can't play again,
3394
+ * so it mustn't join the group.
3395
+ */
3396
+ if (this.isStopped)
3397
+ return;
3398
+ (this.group || createGroup(getOwner(this.options))).tracks.add(this);
3399
+ super.play();
3400
+ }
3401
+ pause() {
3402
+ super.pause();
3403
+ if (this.isAccelerated()) {
3404
+ this.sync();
3405
+ this.group.schedule(false);
3406
+ }
3407
+ }
3408
+ /**
3409
+ * JSAnimation finishes on its next tick, which only happens on the
3410
+ * main thread, so finish now.
3411
+ */
3412
+ complete() {
3413
+ super.complete();
3414
+ const { group } = this;
3415
+ group && !group.isJS && this.canAccelerate && this.tick(time.now());
3416
+ }
3417
+ /**
3418
+ * Without a tick to rebase it, a held time still includes the delay,
3419
+ * so take it off here, as a JS animation does on its next tick.
3420
+ */
3421
+ get time() {
3422
+ if (this.isAccelerated()) {
3423
+ return motionUtils.millisecondsToSeconds(motionUtils.clamp(0, this.totalDuration, this.at(time.now()) - (this.options.delay || 0)));
3424
+ }
3425
+ return super.time;
3426
+ }
3427
+ set time(newTime) {
3428
+ super.time = newTime;
3429
+ }
3430
+ /**
3431
+ * Scroll timelines set time every frame, so run these on the main
3432
+ * thread.
3433
+ */
3434
+ attachTimeline(timeline) {
3435
+ this.canAccelerate = false;
3436
+ this.group?.demote(true);
3437
+ return super.attachTimeline(timeline);
3438
+ }
3439
+ }
3440
+ function createGroup(owner) {
3441
+ const element = owner.current;
3442
+ const tracks = new Set();
3443
+ const byKey = new Map();
3444
+ /**
3445
+ * Transforms that aren't animating, as built into the WAAPI animation.
3446
+ */
3447
+ let statics = {};
3448
+ /**
3449
+ * The transforms in the WAAPI animation, in order.
3450
+ */
3451
+ let keys = [];
3452
+ let built = new Map();
3453
+ let segments = [];
3454
+ let needsBuild = false;
3455
+ let isScheduled = false;
3456
+ let hasChurned = false;
3457
+ let lastChurn = -Infinity;
3458
+ const has = (key) => {
3459
+ for (const track of tracks)
3460
+ if (track.name === key)
3461
+ return true;
3462
+ };
3463
+ /**
3464
+ * The transform values at a timestamp or, without one, from the
3465
+ * motion values. Animations that don't repeat forever are sampled no
3466
+ * earlier than settled, so a loop that starts from an earlier cycle
3467
+ * boundary holds them at their end.
3468
+ */
3469
+ const valuesAt = (timestamp, settled) => {
3470
+ const values = {};
3471
+ for (const key of timestamp === undefined ? transformPropOrder : keys) {
3472
+ const track = byKey.get(key);
3473
+ const value = timestamp === undefined
3474
+ ? read(owner, key)
3475
+ : track
3476
+ ? track.sampleAt(settled > timestamp && !track.timing()[1]
3477
+ ? settled
3478
+ : timestamp)
3479
+ : statics[key];
3480
+ if (value !== undefined)
3481
+ values[key] = value;
3482
+ }
3483
+ return values;
3484
+ };
3485
+ /**
3486
+ * Build the transform at a timestamp. Unlike buildTransform, every key
3487
+ * is written, even at its default, so each keyframe has the same list
3488
+ * of functions and the browser interpolates them one by one.
3489
+ */
3490
+ const compose = (timestamp, settled) => {
3491
+ let transform = "";
3492
+ const values = valuesAt(timestamp, settled);
3493
+ for (const key in values) {
3494
+ transform +=
3495
+ (translateAlias[key] || key) +
3496
+ "(" +
3497
+ getValueAsType(values[key], numberValueTypes[key]) +
3498
+ ") ";
3499
+ }
3500
+ return transform || "none";
3501
+ };
3502
+ /**
3503
+ * Write the transform as an inline style, as the renderer would.
3504
+ */
3505
+ const commit = (values = valuesAt()) => {
3506
+ element.style.transform = buildTransform$1(values, {});
3507
+ };
3508
+ /**
3509
+ * Cancel the WAAPI animations, by default first committing the
3510
+ * transform. The renderer writes its own version on its next render.
3511
+ */
3512
+ const stop = (shouldCommit = true) => {
3513
+ shouldCommit && commit();
3514
+ segments.forEach(({ animation }) => animation.cancel());
3515
+ segments = [];
3516
+ };
3517
+ const add = (animation, offset, end = Infinity) => {
3518
+ const segment = { animation, offset, end };
3519
+ animation.startTime = time.now() + offset;
3520
+ /**
3521
+ * Animations finish when the WAAPI animation reaches their end.
3522
+ * Once a loop has taken over, the finished animation isn't needed.
3523
+ */
3524
+ if (end < Infinity) {
3525
+ animation.onfinish = () => {
3526
+ segment.isDone = true;
3527
+ if (segments.some((s) => s.end === Infinity)) {
3528
+ animation.cancel();
3529
+ segments = segments.filter((s) => s !== segment);
3530
+ }
3531
+ group.schedule(false);
3532
+ };
3533
+ }
3534
+ /**
3535
+ * Something else cancelled it, so carry on on the main thread.
3536
+ */
3537
+ animation.oncancel = () => segments.includes(segment) && group.demote();
3538
+ segments.push(segment);
3539
+ };
3540
+ /**
3541
+ * Where a value jumps between two timestamps, as when a repeat starts
3542
+ * again: the timestamps either side of the jump, or none if it moves
3543
+ * there continuously.
3544
+ */
3545
+ const jumpAt = (value, a, b) => {
3546
+ const change = (x, y) => Math.abs(value(y) - value(x));
3547
+ const size = change(a, b);
3548
+ while (b - a > 0.01) {
3549
+ const mid = (a + b) / 2;
3550
+ change(a, mid) > change(mid, b) ? (b = mid) : (a = mid);
3551
+ }
3552
+ return change(a, b) > size / 2 ? [a, b] : [];
3553
+ };
3554
+ /**
3555
+ * If every moving animation follows the same eased progress between
3556
+ * two timestamps, the easing that describes it.
3557
+ */
3558
+ const getEasing = (moving, from, to, bounds) => {
3559
+ const samples = Math.min(maxSamples, Math.max(2, Math.ceil((to - from) / sampleDelta)));
3560
+ /**
3561
+ * Too many keyframes or repeats to follow with this many samples.
3562
+ */
3563
+ if (bounds.length * 4 > samples)
3564
+ return;
3565
+ const at = spread(from, to, samples).concat(bounds).sort(byTime);
3566
+ const position = (t) => motionUtils.progress(from, to, t);
3567
+ let shared;
3568
+ let progressAt;
3569
+ for (const track of moving) {
3570
+ const values = at.map((t) => track.numberAt(t));
3571
+ const [first] = values;
3572
+ const range = values[values.length - 1] - first;
3573
+ const progress = values.map((value) => range ? (value - first) / range : value - first);
3574
+ /**
3575
+ * A value that doesn't change, like one still in its delay,
3576
+ * fits any easing. One that changes but ends where it started
3577
+ * fits none.
3578
+ */
3579
+ if (!range) {
3580
+ if (progress.some((p) => !(Math.abs(p) <= easingTolerance))) {
3581
+ return;
3582
+ }
3583
+ }
3584
+ else if (!shared) {
3585
+ shared = progress;
3586
+ progressAt = (t) => (track.numberAt(t) - first) / range;
3587
+ }
3588
+ else if (progress.some((p, i) => !(Math.abs(p - shared[i]) <= easingTolerance))) {
3589
+ return;
3590
+ }
3591
+ }
3592
+ if (!shared ||
3593
+ shared.every((p, i) => Math.abs(p - position(at[i])) <= easingTolerance)) {
3594
+ return "linear";
3595
+ }
3596
+ /**
3597
+ * A repeat that starts again jumps back, which takes two points at
3598
+ * the same position.
3599
+ */
3600
+ const points = [];
3601
+ const point = (t, p = progressAt(t)) => points.push(round(p) + " " + round(position(t) * 100) + "%");
3602
+ shared.forEach((p, i) => {
3603
+ i &&
3604
+ Math.abs(p - shared[i - 1]) > 0.2 &&
3605
+ jumpAt(progressAt, at[i - 1], at[i]).forEach((t) => point(t));
3606
+ point(at[i], p);
3607
+ });
3608
+ return "linear(" + points + ")";
3609
+ };
3610
+ /**
3611
+ * Sample timestamps between two timestamps, closer together where the
3612
+ * moving animations curve.
3613
+ */
3614
+ const sample = (moving, from, to, bounds) => {
3615
+ const times = [from];
3616
+ /**
3617
+ * Values that aren't numbers, like calc(), are left to the
3618
+ * browser to interpolate.
3619
+ */
3620
+ const isStraight = (a, b) => moving.every((track) => !(Math.abs(track.numberAt((a + b) / 2) -
3621
+ (track.numberAt(a) + track.numberAt(b)) / 2) >
3622
+ (track.name.startsWith("scale")
3623
+ ? scaleTolerance
3624
+ : sampleTolerance)));
3625
+ const split = (a, b, depth) => {
3626
+ if (b - a < 1 || isStraight(a, b)) {
3627
+ times.push(b);
3628
+ }
3629
+ else if (depth < 4) {
3630
+ split(a, (a + b) / 2, depth + 1);
3631
+ split((a + b) / 2, b, depth + 1);
3632
+ }
3633
+ else {
3634
+ /**
3635
+ * Keyframes either side of a jump, like a repeat starting
3636
+ * again, so it doesn't play as a quick sweep.
3637
+ */
3638
+ for (const track of moving) {
3639
+ times.push(...jumpAt((t) => track.numberAt(t), a, b));
3640
+ }
3641
+ times.push(b);
3642
+ }
3643
+ };
3644
+ /**
3645
+ * Split at least every 100ms, and at every keyframe and repeat,
3646
+ * either side of where a value can jump.
3647
+ */
3648
+ const ends = spread(from, to, Math.ceil((to - from) / 100));
3649
+ for (const t of bounds)
3650
+ ends.push(t, Math.min(t + 0.01, to));
3651
+ let start = from;
3652
+ for (const end of ends.sort(byTime)) {
3653
+ end > start && split(start, end, 0);
3654
+ start = end;
3655
+ }
3656
+ return times.sort(byTime);
3657
+ };
3658
+ /**
3659
+ * If every moving animation is the same tween, started together, as
3660
+ * happens for the values of one animate() call or transition, when
3661
+ * they move and their native easing.
3662
+ */
3663
+ const getTween = (moving) => {
3664
+ let shared;
3665
+ for (const track of moving) {
3666
+ const tween = track.tween();
3667
+ if (!tween ||
3668
+ shared?.some((v, i) => i < 2
3669
+ ? Math.abs(tween[i] - v) > 1
3670
+ : tween[i] !== v)) {
3671
+ return;
3672
+ }
3673
+ shared = tween;
3674
+ }
3675
+ return shared;
3676
+ };
3677
+ /**
3678
+ * A WAAPI animation of the composed transform between two timestamps.
3679
+ */
3680
+ const run = (moving, from, to, options = { fill: "both" }, settled, nativeEasing) => {
3681
+ const bounds = moving.flatMap((track) => track.boundaries(from, to));
3682
+ const easing = nativeEasing || getEasing(moving, from, to, bounds);
3683
+ const times = easing ? [from, to] : sample(moving, from, to, bounds);
3684
+ const transform = times.map((t) => compose(t, settled));
3685
+ let keyframes = { transform };
3686
+ if (!easing) {
3687
+ keyframes.offset = times.map((t) => motionUtils.progress(from, to, t));
3688
+ }
3689
+ /**
3690
+ * If nothing moves, don't hold a transform, which, even at its
3691
+ * default, would make the element a containing block. The empty
3692
+ * animation still finishes the animations.
3693
+ */
3694
+ if (transform.every((t) => t === transform[0])) {
3695
+ commit(valuesAt(from, settled));
3696
+ keyframes = null;
3697
+ }
3698
+ return element.animate(keyframes, {
3699
+ ...options,
3700
+ duration: to - from,
3701
+ easing: easing || "linear",
3702
+ });
3703
+ };
2970
3704
  /**
2971
- * Most values can't be accelerated at all, so check the name before
2972
- * looking at the element or its props.
3705
+ * Replace the WAAPI animations with ones built from now. Returns
3706
+ * undefined if the animations can't be composed.
2973
3707
  */
2974
- if (!name ||
2975
- !(acceleratedValues.has(name) || colorProperties.has(name))) {
2976
- return false;
2977
- }
2978
- const subject = motionValue?.owner?.current;
3708
+ const animate = (now) => {
3709
+ /**
3710
+ * The finite part runs until the last finite animation (or the
3711
+ * last delay) ends. Infinitely repeating animations then continue
3712
+ * as one looping WAAPI animation, which needs them to share a
3713
+ * cycle.
3714
+ */
3715
+ let end = now;
3716
+ let cycle = 0;
3717
+ let cycleStart = 0;
3718
+ const moving = [];
3719
+ const looping = [];
3720
+ const ends = new Set();
3721
+ byKey.clear();
3722
+ built = new Map();
3723
+ for (const track of tracks) {
3724
+ byKey.set(track.name, track);
3725
+ const [trackEnd, trackCycle] = track.timing();
3726
+ const isHeld = trackEnd === Infinity;
3727
+ built.set(track, [track.at(now), track.speed, isHeld]);
3728
+ /**
3729
+ * Held animations don't move, so keep their motion values up
3730
+ * to date, as a JSAnimation would on a seek.
3731
+ */
3732
+ if (isHeld) {
3733
+ track.sync();
3734
+ continue;
3735
+ }
3736
+ if (track.speed < 0)
3737
+ return;
3738
+ if (trackCycle) {
3739
+ if (cycle) {
3740
+ const phase = (trackEnd - cycleStart) / trackCycle;
3741
+ if (Math.abs(trackCycle - cycle) > 1 ||
3742
+ Math.abs(phase - Math.round(phase)) * cycle > 1) {
3743
+ return;
3744
+ }
3745
+ }
3746
+ else {
3747
+ cycle = trackCycle;
3748
+ cycleStart = trackEnd;
3749
+ }
3750
+ looping.push(track);
3751
+ }
3752
+ else {
3753
+ ends.add(trackEnd);
3754
+ }
3755
+ moving.push(track);
3756
+ end = Math.max(end, trackEnd);
3757
+ }
3758
+ statics = {};
3759
+ /**
3760
+ * Transforms that aren't animating are left out at their default.
3761
+ */
3762
+ keys = transformPropOrder.filter((key) => {
3763
+ if (byKey.has(key))
3764
+ return true;
3765
+ const value = (statics[key] = read(owner, key));
3766
+ return (value !== undefined &&
3767
+ parseFloat(value) !==
3768
+ (key.startsWith("scale") ? 1 : 0));
3769
+ });
3770
+ stop(false);
3771
+ /**
3772
+ * Values that share one tween are one WAAPI animation of it, with
3773
+ * two keyframes and its own easing, from when they started.
3774
+ */
3775
+ const tween = !cycle && getTween(moving);
3776
+ try {
3777
+ if (tween && tween[1] > now) {
3778
+ const [from, to, easing] = tween;
3779
+ add(run(moving, from, to, undefined, undefined, easing), from - now, to - from);
3780
+ }
3781
+ else if (end > now) {
3782
+ add(run(moving, now, end), 0, end - now);
3783
+ /**
3784
+ * Animations that end sooner finish on the events of
3785
+ * empty animations that end with them.
3786
+ */
3787
+ ends.forEach((trackEnd) => trackEnd < end - 1 &&
3788
+ add(element.animate(null, {
3789
+ duration: trackEnd - now,
3790
+ }), 0, trackEnd - now));
3791
+ }
3792
+ if (cycle) {
3793
+ /**
3794
+ * Build one cycle from a cycle boundary, so it repeats
3795
+ * seamlessly, and start it part way through.
3796
+ */
3797
+ const from = cycleStart + Math.floor((end - cycleStart) / cycle) * cycle;
3798
+ add(run(looping, from, from + cycle, {
3799
+ iterations: Infinity,
3800
+ iterationStart: (end - from) / cycle,
3801
+ /**
3802
+ * It must not fill backwards over the finite part
3803
+ * that runs before it.
3804
+ */
3805
+ fill: "forwards",
3806
+ }, end), end - now);
3807
+ }
3808
+ }
3809
+ catch {
3810
+ return;
3811
+ }
3812
+ /**
3813
+ * Everything is held, so hold it with an inline style instead.
3814
+ */
3815
+ segments.length || stop();
3816
+ return true;
3817
+ };
2979
3818
  /**
2980
- * We use instanceof checks instead of isHTMLElement()/isSVGElement()
2981
- * because we explicitly **don't** want elements in different timing
2982
- * contexts (i.e. popups) to be accelerated, as it's not possible to sync
2983
- * these animations properly with those driven from the main window
2984
- * frameloop.
3819
+ * If every animation has been paused, played, seeked or sped up
3820
+ * together since the WAAPI animation was built, do the same to it.
3821
+ * Returns false if it needs rebuilding instead.
2985
3822
  */
2986
- if (!(subject instanceof HTMLElement) &&
2987
- !(subject instanceof SVGElement)) {
2988
- return false;
2989
- }
2990
- const { onUpdate, transformTemplate } = motionValue.owner.getProps();
2991
- return (supportsWaapi() &&
3823
+ const retime = (now) => {
3824
+ let elapsed;
3825
+ let rate = 0;
3826
+ for (const track of tracks) {
3827
+ const state = built.get(track);
3828
+ if (!state)
3829
+ return false;
3830
+ const [builtTime, builtSpeed, wasHeld] = state;
3831
+ const trackTime = track.at(now);
3832
+ const isHeld = track.timing()[0] === Infinity;
3833
+ if (wasHeld) {
3834
+ if (isHeld && trackTime === builtTime)
3835
+ continue;
3836
+ return false;
3837
+ }
3838
+ const trackElapsed = (trackTime - builtTime) / builtSpeed;
3839
+ const trackRate = isHeld ? 0 : track.speed / builtSpeed;
3840
+ if (elapsed === undefined) {
3841
+ elapsed = trackElapsed;
3842
+ rate = trackRate;
3843
+ }
3844
+ else if (Math.abs(trackElapsed - elapsed) > 1 ||
3845
+ trackRate !== rate) {
3846
+ return false;
3847
+ }
3848
+ }
3849
+ if (elapsed === undefined)
3850
+ return true;
3851
+ if (!segments.length)
3852
+ return false;
3853
+ for (const { offset, end, isDone } of segments) {
3854
+ const local = elapsed - offset;
3855
+ if (end < Infinity &&
3856
+ (isDone ? local < end - 1 : local < 0 || local >= end)) {
3857
+ return false;
3858
+ }
3859
+ }
3860
+ for (const { animation, offset, isDone } of segments) {
3861
+ if (isDone)
3862
+ continue;
3863
+ const local = elapsed - offset;
3864
+ if (rate) {
3865
+ animation.playbackRate = rate;
3866
+ animation.startTime = now - local / rate;
3867
+ }
3868
+ else {
3869
+ animation.pause();
3870
+ animation.currentTime = local;
3871
+ }
3872
+ }
3873
+ return true;
3874
+ };
3875
+ const build = () => {
3876
+ const now = time.now();
2992
3877
  /**
2993
- * Force WAAPI for color properties with browser-only color formats
2994
- * (oklch, oklab, lab, lch, etc.) that the JS animation path can't parse.
3878
+ * Finish the animations that have reached their end, which the
3879
+ * WAAPI animation has already rendered.
2995
3880
  */
2996
- (acceleratedValues.has(name) ||
2997
- (colorProperties.has(name) &&
2998
- hasBrowserOnlyColors(keyframes))) &&
2999
- (name !== "transform" || !transformTemplate) &&
3881
+ if (!group.isJS) {
3882
+ group.isFinishing = true;
3883
+ tracks.forEach((track) => {
3884
+ const [trackEnd, trackCycle] = track.timing();
3885
+ if (track.state === "running" &&
3886
+ track.speed > 0 &&
3887
+ !trackCycle &&
3888
+ trackEnd <= now + 1) {
3889
+ track.complete();
3890
+ /**
3891
+ * From now it's checked for outside writes like any
3892
+ * other static transform. If the WAAPI animation never
3893
+ * rendered it (it was instant), rebuild with its value.
3894
+ */
3895
+ statics[track.name] = read(owner, track.name);
3896
+ built.has(track) || (needsBuild = true);
3897
+ }
3898
+ });
3899
+ group.isFinishing = false;
3900
+ }
3901
+ isScheduled = false;
3902
+ tracks.forEach(({ state }, track) => {
3903
+ if (state === "idle" || state === "finished")
3904
+ tracks.delete(track);
3905
+ });
3906
+ if (!tracks.size) {
3907
+ transformGroups.delete(element);
3908
+ group.isJS || stop();
3909
+ return;
3910
+ }
3911
+ for (const track of tracks) {
3912
+ if (!track.canAccelerate)
3913
+ return group.demote(true);
3914
+ }
3000
3915
  /**
3001
- * If we're outputting values to onUpdate then we can't use WAAPI as there's
3002
- * no way to read the value from WAAPI every frame.
3916
+ * Everything that kept the group on the main thread has finished,
3917
+ * so move the remaining animations back to the compositor.
3003
3918
  */
3004
- !onUpdate &&
3005
- !repeatDelay &&
3006
- repeatType !== "mirror" &&
3007
- damping !== 0 &&
3008
- type !== "inertia");
3919
+ if (group.isJS) {
3920
+ group.isJS = false;
3921
+ needsBuild = true;
3922
+ tracks.forEach((track) => track.js?.stop());
3923
+ }
3924
+ const shouldBuild = needsBuild;
3925
+ const churned = hasChurned;
3926
+ needsBuild = hasChurned = false;
3927
+ if (shouldBuild || !retime(now)) {
3928
+ if (churned) {
3929
+ if (now - lastChurn < churnWindow)
3930
+ return group.demote();
3931
+ lastChurn = now;
3932
+ }
3933
+ if (!animate(now))
3934
+ return group.demote();
3935
+ }
3936
+ };
3937
+ const group = {
3938
+ tracks,
3939
+ isJS: false,
3940
+ isFinishing: false,
3941
+ schedule(build_, isChurn) {
3942
+ needsBuild || (needsBuild = build_);
3943
+ hasChurned || (hasChurned = !!isChurn);
3944
+ /**
3945
+ * Build in this frame's render step, so it's in place before
3946
+ * anything reads the DOM in postRender, or straight after the
3947
+ * current task outside of a frame.
3948
+ */
3949
+ if (!isScheduled) {
3950
+ isScheduled = true;
3951
+ frameData.isProcessing
3952
+ ? frame.render(build, false, true)
3953
+ : queueMicrotask(build);
3954
+ }
3955
+ },
3956
+ /**
3957
+ * An outside write. Rebuild once, but if it keeps happening, move
3958
+ * to the main thread.
3959
+ */
3960
+ check() {
3961
+ if (group.isJS)
3962
+ return;
3963
+ for (const key in statics) {
3964
+ if (read(owner, key) !== statics[key] && !has(key)) {
3965
+ return group.schedule(true, true);
3966
+ }
3967
+ }
3968
+ },
3969
+ demote(canReturn) {
3970
+ if (group.isJS)
3971
+ return;
3972
+ /**
3973
+ * Unless only another animation is holding the group on the
3974
+ * main thread, these animations stay there until they end.
3975
+ */
3976
+ tracks.forEach((track) => {
3977
+ track.isAccelerated() && track.sync();
3978
+ canReturn || (track.canAccelerate = false);
3979
+ });
3980
+ group.isJS = true;
3981
+ built = new Map();
3982
+ stop();
3983
+ tracks.forEach((track) => track.state === "running" && track.js?.start());
3984
+ },
3985
+ };
3986
+ transformGroups.set(element, group);
3987
+ return group;
3009
3988
  }
3010
3989
 
3011
3990
  class AsyncMotionValueAnimation extends WithPromise {
@@ -3077,6 +4056,11 @@
3077
4056
  * values may not be valid CSS and would trigger browser warnings.
3078
4057
  */
3079
4058
  const useWaapi = canAnimateValue && !isHandoff && supportsBrowserAnimation(options);
4059
+ /**
4060
+ * Independent transforms (x, scale etc) on an HTML element are
4061
+ * composed into one WAAPI transform animation per element.
4062
+ */
4063
+ const isGroupedTransform = !useWaapi && canGroupTransform(options);
3080
4064
  /**
3081
4065
  * Resolve startTime for the animation. A startTime passed in options
3082
4066
  * (an optimised appear handoff syncing to its WAAPI animation) takes
@@ -3092,7 +4076,10 @@
3092
4076
  * animation started in that moment stays in sync. WAAPI has no frame
3093
4077
  * of ours to do that on.
3094
4078
  */
3095
- if (sync && (useWaapi || this.resolvedAt !== this.createdAt)) {
4079
+ if (sync &&
4080
+ (useWaapi ||
4081
+ isGroupedTransform ||
4082
+ this.resolvedAt !== this.createdAt)) {
3096
4083
  options.startTime ?? (options.startTime = resolveStartTime(this.createdAt, this.resolvedAt));
3097
4084
  }
3098
4085
  let animation;
@@ -3110,6 +4097,9 @@
3110
4097
  animation = new JSAnimation(options);
3111
4098
  }
3112
4099
  }
4100
+ else if (isGroupedTransform) {
4101
+ animation = new TransformAnimation(options);
4102
+ }
3113
4103
  else {
3114
4104
  animation = new JSAnimation(options);
3115
4105
  }
@@ -3125,6 +4115,12 @@
3125
4115
  then(onResolve, _onReject) {
3126
4116
  return this.finished.finally(onResolve).then(() => { });
3127
4117
  }
4118
+ /**
4119
+ * The value now, if the animation runs on the compositor.
4120
+ */
4121
+ liveValue() {
4122
+ return this._animation?.liveValue?.();
4123
+ }
3128
4124
  get animation() {
3129
4125
  if (!this._animation) {
3130
4126
  this.keyframeResolver?.resume();
@@ -3562,6 +4558,18 @@
3562
4558
  if (collectMotionValues.current) {
3563
4559
  collectMotionValues.current.push(this);
3564
4560
  }
4561
+ /**
4562
+ * A value animating on the compositor isn't updated every frame,
4563
+ * so read it from its animation.
4564
+ */
4565
+ const sampled = this.animation?.liveValue?.();
4566
+ return sampled === undefined ? this.current : sampled;
4567
+ }
4568
+ /**
4569
+ * The value as last set. Unlike get(), this doesn't read an animation
4570
+ * running on the compositor, which renders the value itself.
4571
+ */
4572
+ getCurrent() {
3565
4573
  return this.current;
3566
4574
  }
3567
4575
  /**
@@ -3788,6 +4796,7 @@
3788
4796
  name,
3789
4797
  motionValue: value,
3790
4798
  element: isHandoff ? undefined : element,
4799
+ hasOnUpdate: !!valueTransition.onUpdate,
3791
4800
  };
3792
4801
  /**
3793
4802
  * If there's no transition defined for this value, we can generate
@@ -4387,6 +5396,30 @@
4387
5396
  constructor(unresolvedKeyframes, onComplete, name, motionValue, element) {
4388
5397
  super(unresolvedKeyframes, onComplete, name, motionValue, element, true);
4389
5398
  }
5399
+ /**
5400
+ * Keyframes that don't need reading from the DOM, or measuring,
5401
+ * resolve straight away rather than in the frame loop's batched read.
5402
+ */
5403
+ scheduleResolve() {
5404
+ if (this.canReadNow()) {
5405
+ this.readKeyframes();
5406
+ if (!this.needsMeasurement)
5407
+ return this.complete();
5408
+ }
5409
+ super.scheduleResolve();
5410
+ }
5411
+ canReadNow() {
5412
+ const { unresolvedKeyframes, element, motionValue } = this;
5413
+ const origin = unresolvedKeyframes[0] ?? motionValue?.get();
5414
+ if (!element?.current || origin === undefined)
5415
+ return false;
5416
+ for (let i = 0; i < unresolvedKeyframes.length; i++) {
5417
+ if (containsCSSVariable(i ? unresolvedKeyframes[i] : origin)) {
5418
+ return false;
5419
+ }
5420
+ }
5421
+ return true;
5422
+ }
4390
5423
  readKeyframes() {
4391
5424
  const { unresolvedKeyframes, element, name } = this;
4392
5425
  if (!element || !element.current)
@@ -4730,15 +5763,6 @@
4730
5763
  return motionUtils.isObject(element) && "ownerSVGElement" in element;
4731
5764
  }
4732
5765
 
4733
- /**
4734
- * Provided a value and a ValueType, returns the value as that value type.
4735
- */
4736
- const getValueAsType = (value, type) => {
4737
- return type && typeof value === "number"
4738
- ? type.transform(value)
4739
- : value;
4740
- };
4741
-
4742
5766
  function resolveElements(elementOrSelector, scope, selectorCache) {
4743
5767
  if (elementOrSelector == null) {
4744
5768
  return [];
@@ -4912,18 +5936,12 @@
4912
5936
  });
4913
5937
  }
4914
5938
 
4915
- const translateAlias$1 = {
4916
- x: "translateX",
4917
- y: "translateY",
4918
- z: "translateZ",
4919
- transformPerspective: "perspective",
4920
- };
4921
5939
  /**
4922
5940
  * Cache of `translateX(`-style openers so each render is a few string
4923
5941
  * concatenations rather than a template per transform.
4924
5942
  */
4925
5943
  const openers = {};
4926
- function buildTransform$1(state) {
5944
+ function buildTransform(state) {
4927
5945
  let transform = "";
4928
5946
  const { transformKeys: keys = [], transformValues: values = {} } = state;
4929
5947
  /**
@@ -4932,7 +5950,7 @@
4932
5950
  */
4933
5951
  for (let i = 0; i < keys.length; i++) {
4934
5952
  const key = keys[i];
4935
- const value = values[key].get();
5953
+ const value = values[key].getCurrent();
4936
5954
  if (value === undefined)
4937
5955
  continue;
4938
5956
  const parsed = typeof value === "number" ? value : parseFloat(value);
@@ -4940,7 +5958,7 @@
4940
5958
  transform +=
4941
5959
  (transform && " ") +
4942
5960
  (openers[key] ||
4943
- (openers[key] = (translateAlias$1[key] || key) + "(")) +
5961
+ (openers[key] = (translateAlias[key] || key) + "(")) +
4944
5962
  getValueAsType(value, transformValueTypes[key]) +
4945
5963
  ")";
4946
5964
  }
@@ -4983,7 +6001,8 @@
4983
6001
  addStyleValue(element, state, "transformBox", new MotionValue("fill-box"));
4984
6002
  }
4985
6003
  state.set("transform", new MotionValue("none"), () => {
4986
- element.style.transform = buildTransform$1(state);
6004
+ transformGroups.get(element)?.check();
6005
+ element.style.transform = buildTransform(state);
4987
6006
  });
4988
6007
  }
4989
6008
  computed = state.get("transform");
@@ -5001,12 +6020,12 @@
5001
6020
  }
5002
6021
  else if (isCSSVar(key)) {
5003
6022
  render = () => {
5004
- element.style.setProperty(key, value.get());
6023
+ element.style.setProperty(key, value.getCurrent());
5005
6024
  };
5006
6025
  }
5007
6026
  else {
5008
6027
  render = () => {
5009
- element.style[key] = getValueAsType(value.get(), numberValueTypes[key]);
6028
+ element.style[key] = getValueAsType(value.getCurrent(), numberValueTypes[key]);
5010
6029
  };
5011
6030
  }
5012
6031
  return state.set(key, value, render, computed);
@@ -5038,73 +6057,8 @@
5038
6057
  test: isStyleSubject,
5039
6058
  read: readStyleValue,
5040
6059
  });
5041
- const styleEffect = /*@__PURE__*/ createSelectorEffect(styleSubjectEffect);
5042
-
5043
- const translateAlias = {
5044
- x: "translateX",
5045
- y: "translateY",
5046
- z: "translateZ",
5047
- transformPerspective: "perspective",
5048
- };
5049
- const numTransforms = transformPropOrder.length;
5050
- /**
5051
- * Build a CSS transform style from individual x/y/scale etc properties.
5052
- *
5053
- * This outputs with a default order of transforms/scales/rotations, this can be customised by
5054
- * providing a transformTemplate function.
5055
- */
5056
- function buildTransform(latestValues, transform, transformTemplate) {
5057
- // The transform string we're going to build into.
5058
- let transformString = "";
5059
- let transformIsDefault = true;
5060
- /**
5061
- * Loop over all possible transforms in order, adding the ones that
5062
- * are present to the transform string.
5063
- */
5064
- for (let i = 0; i < numTransforms; i++) {
5065
- const key = transformPropOrder[i];
5066
- const value = latestValues[key];
5067
- if (value === undefined)
5068
- continue;
5069
- let valueIsDefault = true;
5070
- if (typeof value === "number") {
5071
- valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
5072
- }
5073
- else {
5074
- const parsed = parseFloat(value);
5075
- valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0;
5076
- }
5077
- if (!valueIsDefault || transformTemplate) {
5078
- const valueAsType = getValueAsType(value, numberValueTypes[key]);
5079
- if (!valueIsDefault) {
5080
- transformIsDefault = false;
5081
- const transformName = translateAlias[key] || key;
5082
- transformString += `${transformName}(${valueAsType}) `;
5083
- }
5084
- if (transformTemplate) {
5085
- transform[key] = valueAsType;
5086
- }
5087
- }
5088
- }
5089
- // `pathRotation` composes onto `rotate` as a separate additive term so
5090
- // the user's `rotate` is never clobbered. Deliberately not a slot in
5091
- // `transformPropOrder`.
5092
- const pathRotation = latestValues.pathRotation;
5093
- if (pathRotation) {
5094
- transformIsDefault = false;
5095
- transformString += `rotate(${getValueAsType(pathRotation, numberValueTypes.pathRotation)}) `;
5096
- }
5097
- transformString = transformString.trim();
5098
- // If we have a custom `transform` template, pass our transform values and
5099
- // generated transformString to that before returning
5100
- if (transformTemplate) {
5101
- transformString = transformTemplate(transform, transformIsDefault ? "" : transformString);
5102
- }
5103
- else if (transformIsDefault) {
5104
- transformString = "none";
5105
- }
5106
- return transformString;
5107
- }
6060
+ const styleEffect =
6061
+ /*@__PURE__*/ createSelectorEffect(styleSubjectEffect);
5108
6062
 
5109
6063
  function buildHTMLStyles(state, latestValues, transformTemplate) {
5110
6064
  const { style, vars, transformOrigin } = state;
@@ -5144,7 +6098,7 @@
5144
6098
  }
5145
6099
  if (!latestValues.transform) {
5146
6100
  if (hasTransform || transformTemplate) {
5147
- style.transform = buildTransform(latestValues, state.transform, transformTemplate);
6101
+ style.transform = buildTransform$1(latestValues, state.transform, transformTemplate);
5148
6102
  }
5149
6103
  else if (style.transform) {
5150
6104
  /**
@@ -8048,8 +9002,11 @@
8048
9002
  const removeOnChange = value.on("change", (latestValue) => {
8049
9003
  this.latestValues[key] = latestValue;
8050
9004
  this.props.onUpdate && frame.preRender(this.notifyUpdate);
8051
- if (valueIsTransform && this.projection) {
8052
- this.projection.isTransformDirty = true;
9005
+ if (valueIsTransform) {
9006
+ if (this.projection) {
9007
+ this.projection.isTransformDirty = true;
9008
+ }
9009
+ transformGroups.get(this.current)?.check();
8053
9010
  }
8054
9011
  this.scheduleRender();
8055
9012
  });
@@ -8133,9 +9090,18 @@
8133
9090
  * added to our map, old ones removed, and listeners updated.
8134
9091
  */
8135
9092
  update(props, presenceContext) {
8136
- if (props.transformTemplate || this.props.transformTemplate) {
9093
+ const { transformTemplate, onUpdate } = this.props;
9094
+ if (props.transformTemplate || transformTemplate) {
8137
9095
  this.scheduleRender();
8138
9096
  }
9097
+ /**
9098
+ * Transforms on the compositor can't use a new transformTemplate
9099
+ * or onUpdate, so move them to the main thread.
9100
+ */
9101
+ if ((props.transformTemplate && !transformTemplate) ||
9102
+ (props.onUpdate && !onUpdate)) {
9103
+ transformGroups.get(this.current)?.demote();
9104
+ }
8139
9105
  this.prevProps = this.props;
8140
9106
  this.props = props;
8141
9107
  this.prevPresenceContext = this.presenceContext;
@@ -9430,6 +10396,7 @@
9430
10396
  }
9431
10397
  }
9432
10398
  }
10399
+ const demoteTransforms = ({ instance }) => instance && transformGroups.get(instance)?.demote();
9433
10400
  function cancelTreeOptimisedTransformAnimations(projectionNode) {
9434
10401
  projectionNode.hasCheckedOptimisedAppear = true;
9435
10402
  if (projectionNode.root === projectionNode)
@@ -9791,10 +10758,17 @@
9791
10758
  !this.root.isUpdating && this.root.startUpdate();
9792
10759
  if (this.isLayoutDirty)
9793
10760
  return;
10761
+ /**
10762
+ * Accelerated transforms aren't reflected in latestValues or
10763
+ * removed by resetTransform, so move them back to the main
10764
+ * thread before this node, or its ancestors, are measured.
10765
+ */
10766
+ demoteTransforms(this);
9794
10767
  this.isLayoutDirty = true;
9795
10768
  for (let i = 0; i < this.path.length; i++) {
9796
10769
  const node = this.path[i];
9797
10770
  node.shouldResetTransform = true;
10771
+ demoteTransforms(node);
9798
10772
  /**
9799
10773
  * Percentage translates resolve against layoutBox dimensions,
9800
10774
  * so ancestors with them must be re-measured after transform reset.
@@ -9997,6 +10971,7 @@
9997
10971
  const isResetRequested = this.isLayoutDirty ||
9998
10972
  this.shouldResetTransform ||
9999
10973
  this.options.alwaysMeasureLayout;
10974
+ isResetRequested && demoteTransforms(this);
10000
10975
  const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta);
10001
10976
  const transformTemplate = this.getTransformTemplate();
10002
10977
  const transformTemplateValue = transformTemplate
@@ -11609,7 +12584,7 @@
11609
12584
  exports.buildProjectionTransform = buildProjectionTransform;
11610
12585
  exports.buildSVGAttrs = buildSVGAttrs;
11611
12586
  exports.buildSVGPath = buildSVGPath;
11612
- exports.buildTransform = buildTransform;
12587
+ exports.buildTransform = buildTransform$1;
11613
12588
  exports.calcAxisDelta = calcAxisDelta;
11614
12589
  exports.calcBoxDelta = calcBoxDelta;
11615
12590
  exports.calcChildStagger = calcChildStagger;
@@ -11782,6 +12757,8 @@
11782
12757
  exports.rgbUnit = rgbUnit;
11783
12758
  exports.rgba = rgba;
11784
12759
  exports.rootProjectionNode = rootProjectionNode;
12760
+ exports.round = round;
12761
+ exports.sampleDelta = sampleDelta;
11785
12762
  exports.scale = scale;
11786
12763
  exports.scaleCorrectors = scaleCorrectors;
11787
12764
  exports.scalePoint = scalePoint;
@@ -11805,6 +12782,7 @@
11805
12782
  exports.supportsPartialKeyframes = supportsPartialKeyframes;
11806
12783
  exports.supportsScrollTimeline = supportsScrollTimeline;
11807
12784
  exports.supportsViewTimeline = supportsViewTimeline;
12785
+ exports.supportsWaapi = supportsWaapi;
11808
12786
  exports.svgEffect = svgEffect;
11809
12787
  exports.svgSubjectEffect = svgSubjectEffect;
11810
12788
  exports.sync = sync;