motion-dom 14.1.1 → 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 (39) hide show
  1. package/dist/cjs/index.js +1151 -186
  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/interfaces/motion-value.mjs +1 -0
  10. package/dist/es/animation/interfaces/motion-value.mjs.map +1 -1
  11. package/dist/es/animation/keyframes/DOMKeyframesResolver.mjs +25 -1
  12. package/dist/es/animation/keyframes/DOMKeyframesResolver.mjs.map +1 -1
  13. package/dist/es/animation/waapi/supports/waapi.mjs +1 -1
  14. package/dist/es/animation/waapi/supports/waapi.mjs.map +1 -1
  15. package/dist/es/animation/waapi/transforms/TransformAnimation.mjs +854 -0
  16. package/dist/es/animation/waapi/transforms/TransformAnimation.mjs.map +1 -0
  17. package/dist/es/animation/waapi/transforms/groups.mjs +4 -0
  18. package/dist/es/animation/waapi/transforms/groups.mjs.map +1 -0
  19. package/dist/es/effects/style/index.mjs +6 -3
  20. package/dist/es/effects/style/index.mjs.map +1 -1
  21. package/dist/es/effects/style/transform.mjs +2 -7
  22. package/dist/es/effects/style/transform.mjs.map +1 -1
  23. package/dist/es/index.mjs +3 -3
  24. package/dist/es/projection/node/create-projection-node.mjs +10 -0
  25. package/dist/es/projection/node/create-projection-node.mjs.map +1 -1
  26. package/dist/es/render/VisualElement.mjs +16 -3
  27. package/dist/es/render/VisualElement.mjs.map +1 -1
  28. package/dist/es/render/html/utils/build-transform.mjs +1 -1
  29. package/dist/es/render/html/utils/build-transform.mjs.map +1 -1
  30. package/dist/es/value/index.mjs +12 -0
  31. package/dist/es/value/index.mjs.map +1 -1
  32. package/dist/index.d.ts +77 -12
  33. package/dist/motion-dom.dev.js +1151 -186
  34. package/dist/motion-dom.js +1 -1
  35. package/dist/size-rollup-motion-value.js +1 -1
  36. package/dist/size-rollup-motion-value.js.map +1 -1
  37. package/dist/size-rollup-style-effect.js +1 -1
  38. package/dist/size-rollup-style-effect.js.map +1 -1
  39. package/package.json +2 -2
@@ -1599,6 +1599,7 @@
1599
1599
  }
1600
1600
 
1601
1601
  const percentToProgress = (percent) => percent / 100;
1602
+ const round = (value) => Math.round(value * 10000) / 10000;
1602
1603
  class JSAnimation extends WithPromise {
1603
1604
  constructor(options) {
1604
1605
  super();
@@ -1706,10 +1707,10 @@
1706
1707
  }
1707
1708
  }
1708
1709
  tick(timestamp, sample = false) {
1709
- const { generator, totalDuration, mixKeyframes, mirroredGenerator, resolvedDuration, calculatedDuration, } = this;
1710
+ const { generator, totalDuration, calculatedDuration } = this;
1710
1711
  if (this.startTime === null)
1711
1712
  return generator.next(0);
1712
- const { delay = 0, keyframes, repeat, repeatType, repeatDelay, type, onUpdate, finalKeyframe, } = this.options;
1713
+ const { delay = 0, keyframes, type, onUpdate, finalKeyframe, } = this.options;
1713
1714
  if (this.startTime === this.pendingStartTime) {
1714
1715
  this.startTime = resolveStartTime(this.startTime, timestamp);
1715
1716
  }
@@ -1742,7 +1743,55 @@
1742
1743
  if (this.state === "finished" && this.holdTime === null) {
1743
1744
  this.currentTime = totalDuration;
1744
1745
  }
1745
- 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;
1746
1795
  let frameGenerator = generator;
1747
1796
  if (repeat) {
1748
1797
  /**
@@ -1750,7 +1799,7 @@
1750
1799
  * than duration we'll get values like 2.5 (midway through the
1751
1800
  * third iteration)
1752
1801
  */
1753
- const progress = Math.min(this.currentTime, totalDuration) / resolvedDuration;
1802
+ const progress = Math.min(currentTime, totalDuration) / resolvedDuration;
1754
1803
  /**
1755
1804
  * Get the current iteration (0 indexed). For instance the floor of
1756
1805
  * 2.5 is 2.
@@ -1803,25 +1852,6 @@
1803
1852
  if (mixKeyframes && !isInDelayPhase) {
1804
1853
  state.value = mixKeyframes(state.value);
1805
1854
  }
1806
- let { done } = state;
1807
- if (!isInDelayPhase && calculatedDuration !== null) {
1808
- done =
1809
- this.playbackSpeed >= 0
1810
- ? this.currentTime >= totalDuration
1811
- : this.currentTime <= 0;
1812
- }
1813
- const isAnimationFinished = this.holdTime === null &&
1814
- (this.state === "finished" || (this.state === "running" && done));
1815
- // TODO: The exception for inertia could be cleaner here
1816
- if (isAnimationFinished && type !== inertia) {
1817
- state.value = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
1818
- }
1819
- if (onUpdate) {
1820
- onUpdate(state.value);
1821
- }
1822
- if (isAnimationFinished) {
1823
- this.finish();
1824
- }
1825
1855
  return state;
1826
1856
  }
1827
1857
  /**
@@ -2830,44 +2860,71 @@
2830
2860
  }
2831
2861
  this.options = options;
2832
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
+ }
2833
2898
  /**
2834
2899
  * WAAPI doesn't natively have any interruption capabilities.
2835
2900
  *
2836
2901
  * Rather than read committed styles back out of the DOM, we can
2837
- * create a renderless JS animation and sample it twice to calculate
2838
- * its current value, "previous" value, and therefore allow
2839
- * 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.
2840
2905
  */
2841
2906
  updateMotionValue(value) {
2842
- const { motionValue, onUpdate, onComplete, element, ...options } = this.options;
2907
+ const { motionValue, element, name } = this.options;
2843
2908
  if (!motionValue)
2844
2909
  return;
2845
2910
  if (value !== undefined) {
2846
2911
  motionValue.set(value);
2847
2912
  return;
2848
2913
  }
2849
- const sampleAnimation = new JSAnimation({
2850
- ...options,
2851
- autoplay: false,
2852
- });
2853
- /**
2854
- * Use wall-clock elapsed time for sampling.
2855
- * Under CPU load, WAAPI's currentTime may not reflect actual
2856
- * elapsed time, causing incorrect sampling and visual jumps.
2857
- */
2858
- const sampleTime = Math.max(sampleDelta, time.now() - this.startTime);
2859
- const delta = motionUtils.clamp(0, sampleDelta, sampleTime - sampleDelta);
2860
- 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);
2861
2920
  /**
2862
2921
  * Write the estimated value to inline style so it persists
2863
2922
  * after cancel(), covering the async gap before the next
2864
2923
  * animation starts.
2865
2924
  */
2866
- const { name } = this.options;
2867
2925
  if (element && name)
2868
2926
  setStyle(element, name, current);
2869
- motionValue.setWithVelocity(sampleAnimation.sample(Math.max(0, sampleTime - delta)).value, current, delta);
2870
- sampleAnimation.stop();
2927
+ motionValue.setWithVelocity(this.sample(sampleTime - delta * Math.sign(speed)), current, delta / Math.abs(speed || 1));
2871
2928
  }
2872
2929
  }
2873
2930
 
@@ -2961,64 +3018,973 @@
2961
3018
  browserColorFunctions.test(keyframes[i])) {
2962
3019
  return true;
2963
3020
  }
2964
- }
2965
- return false;
2966
- }
2967
-
2968
- const colorProperties = new Set([
2969
- "color",
2970
- "backgroundColor",
2971
- "outlineColor",
2972
- "fill",
2973
- "stroke",
2974
- "borderColor",
2975
- "borderTopColor",
2976
- "borderRightColor",
2977
- "borderBottomColor",
2978
- "borderLeftColor",
2979
- ]);
2980
- const supportsWaapi = /*@__PURE__*/ motionUtils.memo(() => Object.hasOwnProperty.call(Element.prototype, "animate"));
2981
- function supportsBrowserAnimation(options) {
2982
- 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
+ };
2983
3704
  /**
2984
- * Most values can't be accelerated at all, so check the name before
2985
- * 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.
2986
3707
  */
2987
- if (!name ||
2988
- !(acceleratedValues.has(name) || colorProperties.has(name))) {
2989
- return false;
2990
- }
2991
- 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
+ };
2992
3818
  /**
2993
- * We use instanceof checks instead of isHTMLElement()/isSVGElement()
2994
- * because we explicitly **don't** want elements in different timing
2995
- * contexts (i.e. popups) to be accelerated, as it's not possible to sync
2996
- * these animations properly with those driven from the main window
2997
- * 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.
2998
3822
  */
2999
- if (!(subject instanceof HTMLElement) &&
3000
- !(subject instanceof SVGElement)) {
3001
- return false;
3002
- }
3003
- const { onUpdate, transformTemplate } = motionValue.owner.getProps();
3004
- 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();
3005
3877
  /**
3006
- * Force WAAPI for color properties with browser-only color formats
3007
- * (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.
3008
3880
  */
3009
- (acceleratedValues.has(name) ||
3010
- (colorProperties.has(name) &&
3011
- hasBrowserOnlyColors(keyframes))) &&
3012
- (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
+ }
3013
3915
  /**
3014
- * If we're outputting values to onUpdate then we can't use WAAPI as there's
3015
- * 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.
3016
3918
  */
3017
- !onUpdate &&
3018
- !repeatDelay &&
3019
- repeatType !== "mirror" &&
3020
- damping !== 0 &&
3021
- 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;
3022
3988
  }
3023
3989
 
3024
3990
  class AsyncMotionValueAnimation extends WithPromise {
@@ -3090,6 +4056,11 @@
3090
4056
  * values may not be valid CSS and would trigger browser warnings.
3091
4057
  */
3092
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);
3093
4064
  /**
3094
4065
  * Resolve startTime for the animation. A startTime passed in options
3095
4066
  * (an optimised appear handoff syncing to its WAAPI animation) takes
@@ -3105,7 +4076,10 @@
3105
4076
  * animation started in that moment stays in sync. WAAPI has no frame
3106
4077
  * of ours to do that on.
3107
4078
  */
3108
- if (sync && (useWaapi || this.resolvedAt !== this.createdAt)) {
4079
+ if (sync &&
4080
+ (useWaapi ||
4081
+ isGroupedTransform ||
4082
+ this.resolvedAt !== this.createdAt)) {
3109
4083
  options.startTime ?? (options.startTime = resolveStartTime(this.createdAt, this.resolvedAt));
3110
4084
  }
3111
4085
  let animation;
@@ -3123,6 +4097,9 @@
3123
4097
  animation = new JSAnimation(options);
3124
4098
  }
3125
4099
  }
4100
+ else if (isGroupedTransform) {
4101
+ animation = new TransformAnimation(options);
4102
+ }
3126
4103
  else {
3127
4104
  animation = new JSAnimation(options);
3128
4105
  }
@@ -3138,6 +4115,12 @@
3138
4115
  then(onResolve, _onReject) {
3139
4116
  return this.finished.finally(onResolve).then(() => { });
3140
4117
  }
4118
+ /**
4119
+ * The value now, if the animation runs on the compositor.
4120
+ */
4121
+ liveValue() {
4122
+ return this._animation?.liveValue?.();
4123
+ }
3141
4124
  get animation() {
3142
4125
  if (!this._animation) {
3143
4126
  this.keyframeResolver?.resume();
@@ -3575,6 +4558,18 @@
3575
4558
  if (collectMotionValues.current) {
3576
4559
  collectMotionValues.current.push(this);
3577
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() {
3578
4573
  return this.current;
3579
4574
  }
3580
4575
  /**
@@ -3801,6 +4796,7 @@
3801
4796
  name,
3802
4797
  motionValue: value,
3803
4798
  element: isHandoff ? undefined : element,
4799
+ hasOnUpdate: !!valueTransition.onUpdate,
3804
4800
  };
3805
4801
  /**
3806
4802
  * If there's no transition defined for this value, we can generate
@@ -4400,6 +5396,30 @@
4400
5396
  constructor(unresolvedKeyframes, onComplete, name, motionValue, element) {
4401
5397
  super(unresolvedKeyframes, onComplete, name, motionValue, element, true);
4402
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
+ }
4403
5423
  readKeyframes() {
4404
5424
  const { unresolvedKeyframes, element, name } = this;
4405
5425
  if (!element || !element.current)
@@ -4743,15 +5763,6 @@
4743
5763
  return motionUtils.isObject(element) && "ownerSVGElement" in element;
4744
5764
  }
4745
5765
 
4746
- /**
4747
- * Provided a value and a ValueType, returns the value as that value type.
4748
- */
4749
- const getValueAsType = (value, type) => {
4750
- return type && typeof value === "number"
4751
- ? type.transform(value)
4752
- : value;
4753
- };
4754
-
4755
5766
  function resolveElements(elementOrSelector, scope, selectorCache) {
4756
5767
  if (elementOrSelector == null) {
4757
5768
  return [];
@@ -4925,18 +5936,12 @@
4925
5936
  });
4926
5937
  }
4927
5938
 
4928
- const translateAlias$1 = {
4929
- x: "translateX",
4930
- y: "translateY",
4931
- z: "translateZ",
4932
- transformPerspective: "perspective",
4933
- };
4934
5939
  /**
4935
5940
  * Cache of `translateX(`-style openers so each render is a few string
4936
5941
  * concatenations rather than a template per transform.
4937
5942
  */
4938
5943
  const openers = {};
4939
- function buildTransform$1(state) {
5944
+ function buildTransform(state) {
4940
5945
  let transform = "";
4941
5946
  const { transformKeys: keys = [], transformValues: values = {} } = state;
4942
5947
  /**
@@ -4945,7 +5950,7 @@
4945
5950
  */
4946
5951
  for (let i = 0; i < keys.length; i++) {
4947
5952
  const key = keys[i];
4948
- const value = values[key].get();
5953
+ const value = values[key].getCurrent();
4949
5954
  if (value === undefined)
4950
5955
  continue;
4951
5956
  const parsed = typeof value === "number" ? value : parseFloat(value);
@@ -4953,7 +5958,7 @@
4953
5958
  transform +=
4954
5959
  (transform && " ") +
4955
5960
  (openers[key] ||
4956
- (openers[key] = (translateAlias$1[key] || key) + "(")) +
5961
+ (openers[key] = (translateAlias[key] || key) + "(")) +
4957
5962
  getValueAsType(value, transformValueTypes[key]) +
4958
5963
  ")";
4959
5964
  }
@@ -4996,7 +6001,8 @@
4996
6001
  addStyleValue(element, state, "transformBox", new MotionValue("fill-box"));
4997
6002
  }
4998
6003
  state.set("transform", new MotionValue("none"), () => {
4999
- element.style.transform = buildTransform$1(state);
6004
+ transformGroups.get(element)?.check();
6005
+ element.style.transform = buildTransform(state);
5000
6006
  });
5001
6007
  }
5002
6008
  computed = state.get("transform");
@@ -5014,12 +6020,12 @@
5014
6020
  }
5015
6021
  else if (isCSSVar(key)) {
5016
6022
  render = () => {
5017
- element.style.setProperty(key, value.get());
6023
+ element.style.setProperty(key, value.getCurrent());
5018
6024
  };
5019
6025
  }
5020
6026
  else {
5021
6027
  render = () => {
5022
- element.style[key] = getValueAsType(value.get(), numberValueTypes[key]);
6028
+ element.style[key] = getValueAsType(value.getCurrent(), numberValueTypes[key]);
5023
6029
  };
5024
6030
  }
5025
6031
  return state.set(key, value, render, computed);
@@ -5051,73 +6057,8 @@
5051
6057
  test: isStyleSubject,
5052
6058
  read: readStyleValue,
5053
6059
  });
5054
- const styleEffect = /*@__PURE__*/ createSelectorEffect(styleSubjectEffect);
5055
-
5056
- const translateAlias = {
5057
- x: "translateX",
5058
- y: "translateY",
5059
- z: "translateZ",
5060
- transformPerspective: "perspective",
5061
- };
5062
- const numTransforms = transformPropOrder.length;
5063
- /**
5064
- * Build a CSS transform style from individual x/y/scale etc properties.
5065
- *
5066
- * This outputs with a default order of transforms/scales/rotations, this can be customised by
5067
- * providing a transformTemplate function.
5068
- */
5069
- function buildTransform(latestValues, transform, transformTemplate) {
5070
- // The transform string we're going to build into.
5071
- let transformString = "";
5072
- let transformIsDefault = true;
5073
- /**
5074
- * Loop over all possible transforms in order, adding the ones that
5075
- * are present to the transform string.
5076
- */
5077
- for (let i = 0; i < numTransforms; i++) {
5078
- const key = transformPropOrder[i];
5079
- const value = latestValues[key];
5080
- if (value === undefined)
5081
- continue;
5082
- let valueIsDefault = true;
5083
- if (typeof value === "number") {
5084
- valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
5085
- }
5086
- else {
5087
- const parsed = parseFloat(value);
5088
- valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0;
5089
- }
5090
- if (!valueIsDefault || transformTemplate) {
5091
- const valueAsType = getValueAsType(value, numberValueTypes[key]);
5092
- if (!valueIsDefault) {
5093
- transformIsDefault = false;
5094
- const transformName = translateAlias[key] || key;
5095
- transformString += `${transformName}(${valueAsType}) `;
5096
- }
5097
- if (transformTemplate) {
5098
- transform[key] = valueAsType;
5099
- }
5100
- }
5101
- }
5102
- // `pathRotation` composes onto `rotate` as a separate additive term so
5103
- // the user's `rotate` is never clobbered. Deliberately not a slot in
5104
- // `transformPropOrder`.
5105
- const pathRotation = latestValues.pathRotation;
5106
- if (pathRotation) {
5107
- transformIsDefault = false;
5108
- transformString += `rotate(${getValueAsType(pathRotation, numberValueTypes.pathRotation)}) `;
5109
- }
5110
- transformString = transformString.trim();
5111
- // If we have a custom `transform` template, pass our transform values and
5112
- // generated transformString to that before returning
5113
- if (transformTemplate) {
5114
- transformString = transformTemplate(transform, transformIsDefault ? "" : transformString);
5115
- }
5116
- else if (transformIsDefault) {
5117
- transformString = "none";
5118
- }
5119
- return transformString;
5120
- }
6060
+ const styleEffect =
6061
+ /*@__PURE__*/ createSelectorEffect(styleSubjectEffect);
5121
6062
 
5122
6063
  function buildHTMLStyles(state, latestValues, transformTemplate) {
5123
6064
  const { style, vars, transformOrigin } = state;
@@ -5157,7 +6098,7 @@
5157
6098
  }
5158
6099
  if (!latestValues.transform) {
5159
6100
  if (hasTransform || transformTemplate) {
5160
- style.transform = buildTransform(latestValues, state.transform, transformTemplate);
6101
+ style.transform = buildTransform$1(latestValues, state.transform, transformTemplate);
5161
6102
  }
5162
6103
  else if (style.transform) {
5163
6104
  /**
@@ -8061,8 +9002,11 @@
8061
9002
  const removeOnChange = value.on("change", (latestValue) => {
8062
9003
  this.latestValues[key] = latestValue;
8063
9004
  this.props.onUpdate && frame.preRender(this.notifyUpdate);
8064
- if (valueIsTransform && this.projection) {
8065
- this.projection.isTransformDirty = true;
9005
+ if (valueIsTransform) {
9006
+ if (this.projection) {
9007
+ this.projection.isTransformDirty = true;
9008
+ }
9009
+ transformGroups.get(this.current)?.check();
8066
9010
  }
8067
9011
  this.scheduleRender();
8068
9012
  });
@@ -8146,9 +9090,18 @@
8146
9090
  * added to our map, old ones removed, and listeners updated.
8147
9091
  */
8148
9092
  update(props, presenceContext) {
8149
- if (props.transformTemplate || this.props.transformTemplate) {
9093
+ const { transformTemplate, onUpdate } = this.props;
9094
+ if (props.transformTemplate || transformTemplate) {
8150
9095
  this.scheduleRender();
8151
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
+ }
8152
9105
  this.prevProps = this.props;
8153
9106
  this.props = props;
8154
9107
  this.prevPresenceContext = this.presenceContext;
@@ -9443,6 +10396,7 @@
9443
10396
  }
9444
10397
  }
9445
10398
  }
10399
+ const demoteTransforms = ({ instance }) => instance && transformGroups.get(instance)?.demote();
9446
10400
  function cancelTreeOptimisedTransformAnimations(projectionNode) {
9447
10401
  projectionNode.hasCheckedOptimisedAppear = true;
9448
10402
  if (projectionNode.root === projectionNode)
@@ -9804,10 +10758,17 @@
9804
10758
  !this.root.isUpdating && this.root.startUpdate();
9805
10759
  if (this.isLayoutDirty)
9806
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);
9807
10767
  this.isLayoutDirty = true;
9808
10768
  for (let i = 0; i < this.path.length; i++) {
9809
10769
  const node = this.path[i];
9810
10770
  node.shouldResetTransform = true;
10771
+ demoteTransforms(node);
9811
10772
  /**
9812
10773
  * Percentage translates resolve against layoutBox dimensions,
9813
10774
  * so ancestors with them must be re-measured after transform reset.
@@ -10010,6 +10971,7 @@
10010
10971
  const isResetRequested = this.isLayoutDirty ||
10011
10972
  this.shouldResetTransform ||
10012
10973
  this.options.alwaysMeasureLayout;
10974
+ isResetRequested && demoteTransforms(this);
10013
10975
  const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta);
10014
10976
  const transformTemplate = this.getTransformTemplate();
10015
10977
  const transformTemplateValue = transformTemplate
@@ -11622,7 +12584,7 @@
11622
12584
  exports.buildProjectionTransform = buildProjectionTransform;
11623
12585
  exports.buildSVGAttrs = buildSVGAttrs;
11624
12586
  exports.buildSVGPath = buildSVGPath;
11625
- exports.buildTransform = buildTransform;
12587
+ exports.buildTransform = buildTransform$1;
11626
12588
  exports.calcAxisDelta = calcAxisDelta;
11627
12589
  exports.calcBoxDelta = calcBoxDelta;
11628
12590
  exports.calcChildStagger = calcChildStagger;
@@ -11795,6 +12757,8 @@
11795
12757
  exports.rgbUnit = rgbUnit;
11796
12758
  exports.rgba = rgba;
11797
12759
  exports.rootProjectionNode = rootProjectionNode;
12760
+ exports.round = round;
12761
+ exports.sampleDelta = sampleDelta;
11798
12762
  exports.scale = scale;
11799
12763
  exports.scaleCorrectors = scaleCorrectors;
11800
12764
  exports.scalePoint = scalePoint;
@@ -11818,6 +12782,7 @@
11818
12782
  exports.supportsPartialKeyframes = supportsPartialKeyframes;
11819
12783
  exports.supportsScrollTimeline = supportsScrollTimeline;
11820
12784
  exports.supportsViewTimeline = supportsViewTimeline;
12785
+ exports.supportsWaapi = supportsWaapi;
11821
12786
  exports.svgEffect = svgEffect;
11822
12787
  exports.svgSubjectEffect = svgSubjectEffect;
11823
12788
  exports.sync = sync;