motion-dom 13.1.1 → 13.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.
package/dist/cjs/index.js CHANGED
@@ -736,15 +736,16 @@ resolution = 10 // as milliseconds
736
736
  * to prevent infinite loops
737
737
  */
738
738
  const maxGeneratorDuration = 20000;
739
- function calcGeneratorDuration(generator) {
739
+ function calcGeneratorDuration(generator, timeStep = 50, maxDuration = maxGeneratorDuration, keyframes) {
740
740
  let duration = 0;
741
- const timeStep = 50;
742
741
  let state = generator.next(duration);
743
- while (!state.done && duration < maxGeneratorDuration) {
742
+ keyframes?.push(state.value);
743
+ while (!state.done && duration < maxDuration) {
744
744
  duration += timeStep;
745
745
  state = generator.next(duration);
746
+ keyframes?.push(state.value);
746
747
  }
747
- return duration >= maxGeneratorDuration ? Infinity : duration;
748
+ return duration >= maxDuration ? Infinity : duration;
748
749
  }
749
750
 
750
751
  /**
@@ -828,9 +829,13 @@ function findSpring({ duration = springDefaults.duration, bounce = springDefault
828
829
  const exponentialDecay = undampedFreq * dampingRatio;
829
830
  const delta = exponentialDecay * duration;
830
831
  const d = delta * velocity + velocity;
831
- const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration;
832
+ const e = dampingRatio *
833
+ dampingRatio *
834
+ undampedFreq *
835
+ undampedFreq *
836
+ duration;
832
837
  const f = Math.exp(-delta);
833
- const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio);
838
+ const g = calcAngularFreq(undampedFreq * undampedFreq, dampingRatio);
834
839
  const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1;
835
840
  return (factor * ((d - e) * f)) / g;
836
841
  };
@@ -861,7 +866,7 @@ function findSpring({ duration = springDefaults.duration, bounce = springDefault
861
866
  };
862
867
  }
863
868
  else {
864
- const stiffness = Math.pow(undampedFreq, 2) * mass;
869
+ const stiffness = undampedFreq * undampedFreq * mass;
865
870
  return {
866
871
  stiffness,
867
872
  damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),
@@ -941,6 +946,7 @@ function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce
941
946
  const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));
942
947
  const initialDelta = target - origin;
943
948
  const undampedAngularFreq = motionUtils.millisecondsToSeconds(Math.sqrt(stiffness / mass));
949
+ const decay = dampingRatio * undampedAngularFreq;
944
950
  /**
945
951
  * If we're working on a granular scale, use smaller defaults for determining
946
952
  * when the spring is finished.
@@ -957,35 +963,38 @@ function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce
957
963
  : springDefaults.restDelta.default);
958
964
  let resolveSpring;
959
965
  let resolveVelocity;
960
- // Underdamped coefficients, hoisted for use in the inlined next() hot path
961
- let angularFreq;
962
- let A;
963
- let sinCoeff;
964
- let cosCoeff;
965
966
  if (dampingRatio < 1) {
966
- angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
967
- A =
968
- (initialVelocity +
969
- dampingRatio * undampedAngularFreq * initialDelta) /
970
- angularFreq;
967
+ const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
968
+ const A = (initialVelocity + decay * initialDelta) / angularFreq;
969
+ // Coefficients for the analytical derivative (px/ms)
970
+ const sinCoeff = decay * A + initialDelta * angularFreq;
971
+ const cosCoeff = decay * initialDelta - A * angularFreq;
972
+ /**
973
+ * The underdamped hot path needs both position and velocity every
974
+ * frame and they share the same exp/sin/cos terms, so sample both
975
+ * at once, memoized by t, to only calculate them once per frame.
976
+ */
977
+ let sampledT = -1;
978
+ let position = 0;
979
+ let velocityAtT = 0;
980
+ const sample = (t) => {
981
+ if (t !== sampledT) {
982
+ sampledT = t;
983
+ const envelope = Math.exp(-decay * t);
984
+ const sin = Math.sin(angularFreq * t);
985
+ const cos = Math.cos(angularFreq * t);
986
+ position = target - envelope * (A * sin + initialDelta * cos);
987
+ velocityAtT = envelope * (sinCoeff * sin + cosCoeff * cos);
988
+ }
989
+ };
971
990
  // Underdamped spring
972
991
  resolveSpring = (t) => {
973
- const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
974
- return (target -
975
- envelope *
976
- (A * Math.sin(angularFreq * t) +
977
- initialDelta * Math.cos(angularFreq * t)));
992
+ sample(t);
993
+ return position;
978
994
  };
979
- // Analytical derivative of underdamped spring (px/ms)
980
- sinCoeff =
981
- dampingRatio * undampedAngularFreq * A + initialDelta * angularFreq;
982
- cosCoeff =
983
- dampingRatio * undampedAngularFreq * initialDelta - A * angularFreq;
984
995
  resolveVelocity = (t) => {
985
- const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
986
- return envelope *
987
- (sinCoeff * Math.sin(angularFreq * t) +
988
- cosCoeff * Math.cos(angularFreq * t));
996
+ sample(t);
997
+ return velocityAtT;
989
998
  };
990
999
  }
991
1000
  else if (dampingRatio === 1) {
@@ -1003,13 +1012,12 @@ function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce
1003
1012
  // Overdamped spring
1004
1013
  const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);
1005
1014
  resolveSpring = (t) => {
1006
- const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
1015
+ const envelope = Math.exp(-decay * t);
1007
1016
  // When performing sinh or cosh values can hit Infinity so we cap them here
1008
1017
  const freqForT = Math.min(dampedAngularFreq * t, 300);
1009
1018
  return (target -
1010
1019
  (envelope *
1011
- ((initialVelocity +
1012
- dampingRatio * undampedAngularFreq * initialDelta) *
1020
+ ((initialVelocity + decay * initialDelta) *
1013
1021
  Math.sinh(freqForT) +
1014
1022
  dampedAngularFreq *
1015
1023
  initialDelta *
@@ -1017,43 +1025,21 @@ function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce
1017
1025
  dampedAngularFreq);
1018
1026
  };
1019
1027
  // Analytical derivative of overdamped spring (px/ms)
1020
- const P = (initialVelocity +
1021
- dampingRatio * undampedAngularFreq * initialDelta) /
1022
- dampedAngularFreq;
1023
- const sinhCoeff = dampingRatio * undampedAngularFreq * P - initialDelta * dampedAngularFreq;
1024
- const coshCoeff = dampingRatio * undampedAngularFreq * initialDelta - P * dampedAngularFreq;
1028
+ const P = (initialVelocity + decay * initialDelta) / dampedAngularFreq;
1029
+ const sinhCoeff = decay * P - initialDelta * dampedAngularFreq;
1030
+ const coshCoeff = decay * initialDelta - P * dampedAngularFreq;
1025
1031
  resolveVelocity = (t) => {
1026
- const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
1032
+ const envelope = Math.exp(-decay * t);
1027
1033
  const freqForT = Math.min(dampedAngularFreq * t, 300);
1028
- return envelope *
1034
+ return (envelope *
1029
1035
  (sinhCoeff * Math.sinh(freqForT) +
1030
- coshCoeff * Math.cosh(freqForT));
1036
+ coshCoeff * Math.cosh(freqForT)));
1031
1037
  };
1032
1038
  }
1033
1039
  const generator = {
1034
1040
  calculatedDuration: isResolvedFromDuration ? duration || null : null,
1035
1041
  velocity: (t) => motionUtils.secondsToMilliseconds(resolveVelocity(t)),
1036
1042
  next: (t) => {
1037
- /**
1038
- * For underdamped physics springs we need both position and
1039
- * velocity each tick. Compute shared trig values once to avoid
1040
- * duplicate Math.exp/sin/cos calls on the hot path.
1041
- */
1042
- if (!isResolvedFromDuration && dampingRatio < 1) {
1043
- const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
1044
- const sin = Math.sin(angularFreq * t);
1045
- const cos = Math.cos(angularFreq * t);
1046
- const current = target -
1047
- envelope *
1048
- (A * sin + initialDelta * cos);
1049
- const currentVelocity = motionUtils.secondsToMilliseconds(envelope *
1050
- (sinCoeff * sin + cosCoeff * cos));
1051
- state.done =
1052
- Math.abs(currentVelocity) <= restSpeed &&
1053
- Math.abs(target - current) <= restDelta;
1054
- state.value = state.done ? target : current;
1055
- return state;
1056
- }
1057
1043
  const current = resolveSpring(t);
1058
1044
  if (!isResolvedFromDuration) {
1059
1045
  const currentVelocity = motionUtils.secondsToMilliseconds(resolveVelocity(t));
@@ -1084,19 +1070,13 @@ spring.applyToOptions = (options) => {
1084
1070
  return options;
1085
1071
  };
1086
1072
 
1087
- const velocitySampleDuration = 5; // ms
1088
- function getGeneratorVelocity(resolveValue, t, current) {
1089
- const prevT = Math.max(t - velocitySampleDuration, 0);
1090
- return motionUtils.velocityPerSecond(current - resolveValue(prevT), t - prevT);
1091
- }
1092
-
1093
1073
  function inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed, }) {
1094
1074
  const origin = keyframes[0];
1095
1075
  const state = {
1096
1076
  done: false,
1097
1077
  value: origin,
1098
1078
  };
1099
- const isOutOfBounds = (v) => (min !== undefined && v < min) || (max !== undefined && v > max);
1079
+ const isOutOfBounds = (v) => v < min || v > max;
1100
1080
  const nearestBoundary = (v) => {
1101
1081
  if (min === undefined)
1102
1082
  return max;
@@ -1114,12 +1094,10 @@ function inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, b
1114
1094
  if (target !== ideal)
1115
1095
  amplitude = target - origin;
1116
1096
  const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant);
1117
- const calcLatest = (t) => target + calcDelta(t);
1118
1097
  const applyFriction = (t) => {
1119
1098
  const delta = calcDelta(t);
1120
- const latest = calcLatest(t);
1121
1099
  state.done = Math.abs(delta) <= restDelta;
1122
- state.value = state.done ? target : latest;
1100
+ state.value = state.done ? target : target + delta;
1123
1101
  };
1124
1102
  /**
1125
1103
  * Ideally this would resolve for t in a stateless way, we could
@@ -1135,7 +1113,12 @@ function inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, b
1135
1113
  timeReachedBoundary = t;
1136
1114
  spring$1 = spring({
1137
1115
  keyframes: [state.value, nearestBoundary(state.value)],
1138
- velocity: getGeneratorVelocity(calcLatest, t, state.value), // TODO: This should be passing * 1000
1116
+ /**
1117
+ * The friction curve is target + calcDelta(t), so its exact
1118
+ * derivative is -calcDelta(t) / timeConstant in units/ms,
1119
+ * converted here to the units/second expected by spring.
1120
+ */
1121
+ velocity: (-calcDelta(t) / timeConstant) * 1000,
1139
1122
  damping: bounceDamping,
1140
1123
  stiffness: bounceStiffness,
1141
1124
  restDelta,
@@ -1304,6 +1287,12 @@ function keyframes({ duration = 300, keyframes: keyframeValues, times, ease = "e
1304
1287
  };
1305
1288
  }
1306
1289
 
1290
+ const velocitySampleDuration = 5; // ms
1291
+ function getGeneratorVelocity(resolveValue, t, current) {
1292
+ const prevT = Math.max(t - velocitySampleDuration, 0);
1293
+ return motionUtils.velocityPerSecond(current - resolveValue(prevT), t - prevT);
1294
+ }
1295
+
1307
1296
  const isNotNull = (value) => value !== null;
1308
1297
  function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe, speed = 1) {
1309
1298
  const resolvedKeyframes = keyframes.filter(isNotNull);
@@ -4310,6 +4299,47 @@ const supportsPartialKeyframes = /*@__PURE__*/ motionUtils.memo(() => {
4310
4299
  return true;
4311
4300
  });
4312
4301
 
4302
+ /**
4303
+ * Effects registered via `animate.addEffect()`, most recent first.
4304
+ */
4305
+ const effects = [];
4306
+ function addEffect(effect) {
4307
+ motionUtils.invariant(typeof effect.test === "function" && typeof effect.read === "function", "Effects passed to animate.addEffect() need test() and read().", "effect-missing-test");
4308
+ removeEffect(effect);
4309
+ effects.unshift(effect);
4310
+ }
4311
+ function removeEffect(effect) {
4312
+ motionUtils.removeItem(effects, effect);
4313
+ }
4314
+ function findEffect(subject) {
4315
+ return effects.find((effect) => effect.test(subject));
4316
+ }
4317
+ /**
4318
+ * Animate the keys of `subject` via `effect`. Motion values are created on
4319
+ * first animation, seeded from `effect.read()` or the first keyframe, and
4320
+ * then bound to the subject via the effect for the rest of its life.
4321
+ */
4322
+ function animateEffectSubject(effect, subject, keyframes, transition = {}) {
4323
+ const animations = [];
4324
+ for (const key in keyframes) {
4325
+ const target = keyframes[key];
4326
+ let value = effect.get(subject, key);
4327
+ if (!value) {
4328
+ const initial = effect.read(subject, key, target) ?? firstKeyframe(target);
4329
+ motionUtils.invariant(initial !== undefined, `"${key}" can't be read from the animated subject. Provide [from, to] keyframes.`, "effect-unreadable-value");
4330
+ value = motionValue(initial);
4331
+ effect(subject, { [key]: value });
4332
+ }
4333
+ value.start(animateMotionValue(key, value, target, getValueTransition(transition, key)));
4334
+ value.animation && animations.push(value.animation);
4335
+ }
4336
+ return animations;
4337
+ }
4338
+ function firstKeyframe(target) {
4339
+ const first = Array.isArray(target) ? target[0] : undefined;
4340
+ return first === null ? undefined : first;
4341
+ }
4342
+
4313
4343
  function resolveElements(elementOrSelector, scope, selectorCache) {
4314
4344
  if (elementOrSelector == null) {
4315
4345
  return [];
@@ -4354,7 +4384,13 @@ const getValueAsType = (value, type) => {
4354
4384
  };
4355
4385
 
4356
4386
  class MotionValueState {
4357
- constructor() {
4387
+ /**
4388
+ * @param step - The frameloop step renders are scheduled in. Defaults
4389
+ * to `frame.render`. Effects that feed a render loop running in
4390
+ * `frame.render` (GPU scenes) should write in `frame.preRender`.
4391
+ */
4392
+ constructor(step = frame.render) {
4393
+ this.step = step;
4358
4394
  this.latest = {};
4359
4395
  this.values = new Map();
4360
4396
  }
@@ -4371,7 +4407,7 @@ class MotionValueState {
4371
4407
  else {
4372
4408
  this.latest[name] = v;
4373
4409
  }
4374
- render && frame.render(render);
4410
+ render && this.step(render);
4375
4411
  };
4376
4412
  onChange();
4377
4413
  const cancelOnChange = value.on("change", onChange);
@@ -4390,10 +4426,10 @@ class MotionValueState {
4390
4426
  }
4391
4427
  }
4392
4428
 
4393
- function createEffect(addValue) {
4429
+ function createEffect(addValue, { step, ...options } = {}) {
4394
4430
  const stateCache = new WeakMap();
4395
- return (subject, values) => {
4396
- const state = stateCache.get(subject) ?? new MotionValueState();
4431
+ const effect = (subject, values) => {
4432
+ const state = stateCache.get(subject) ?? new MotionValueState(step);
4397
4433
  stateCache.set(subject, state);
4398
4434
  const subscriptions = [];
4399
4435
  for (const key in values) {
@@ -4406,6 +4442,9 @@ function createEffect(addValue) {
4406
4442
  cancel();
4407
4443
  };
4408
4444
  };
4445
+ return Object.assign(effect, options, {
4446
+ get: (subject, key) => stateCache.get(subject)?.get(key),
4447
+ });
4409
4448
  }
4410
4449
 
4411
4450
  function canSetAsProperty(element, name) {
@@ -10783,6 +10822,7 @@ exports.JSAnimation = JSAnimation;
10783
10822
  exports.KeyframeResolver = KeyframeResolver;
10784
10823
  exports.LayoutAnimationBuilder = LayoutAnimationBuilder;
10785
10824
  exports.MotionValue = MotionValue;
10825
+ exports.MotionValueState = MotionValueState;
10786
10826
  exports.NativeAnimation = NativeAnimation;
10787
10827
  exports.NativeAnimationExtended = NativeAnimationExtended;
10788
10828
  exports.NativeAnimationWrapper = NativeAnimationWrapper;
@@ -10794,11 +10834,13 @@ exports.VisualElement = VisualElement;
10794
10834
  exports.acceleratedValues = acceleratedValues;
10795
10835
  exports.addAttrValue = addAttrValue;
10796
10836
  exports.addDomEvent = addDomEvent;
10837
+ exports.addEffect = addEffect;
10797
10838
  exports.addScaleCorrector = addScaleCorrector;
10798
10839
  exports.addStyleValue = addStyleValue;
10799
10840
  exports.addValueToWillChange = addValueToWillChange;
10800
10841
  exports.alpha = alpha;
10801
10842
  exports.analyseComplexValue = analyseComplexValue;
10843
+ exports.animateEffectSubject = animateEffectSubject;
10802
10844
  exports.animateMotionValue = animateMotionValue;
10803
10845
  exports.animateSingleValue = animateSingleValue;
10804
10846
  exports.animateTarget = animateTarget;
@@ -10862,6 +10904,7 @@ exports.createAxis = createAxis;
10862
10904
  exports.createAxisDelta = createAxisDelta;
10863
10905
  exports.createBox = createBox;
10864
10906
  exports.createDelta = createDelta;
10907
+ exports.createEffect = createEffect;
10865
10908
  exports.createGeneratorEasing = createGeneratorEasing;
10866
10909
  exports.createProjectionNode = createProjectionNode;
10867
10910
  exports.createRenderBatcher = createRenderBatcher;
@@ -10878,6 +10921,7 @@ exports.eachAxis = eachAxis;
10878
10921
  exports.fillOffset = fillOffset;
10879
10922
  exports.fillWildcards = fillWildcards;
10880
10923
  exports.findDimensionValueType = findDimensionValueType;
10924
+ exports.findEffect = findEffect;
10881
10925
  exports.findValueType = findValueType;
10882
10926
  exports.flushKeyframeResolvers = flushKeyframeResolvers;
10883
10927
  exports.followValue = followValue;
@@ -10981,6 +11025,7 @@ exports.recordStats = recordStats;
10981
11025
  exports.removeAxisDelta = removeAxisDelta;
10982
11026
  exports.removeAxisTransforms = removeAxisTransforms;
10983
11027
  exports.removeBoxTransforms = removeBoxTransforms;
11028
+ exports.removeEffect = removeEffect;
10984
11029
  exports.removePointDelta = removePointDelta;
10985
11030
  exports.renderHTML = renderHTML;
10986
11031
  exports.renderSVG = renderSVG;