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