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