motion-dom 14.11.1 → 14.13.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
@@ -895,9 +895,9 @@ function approximateRoot(envelope, derivative, initialGuess) {
895
895
  */
896
896
  const safeMin = 0.001;
897
897
  /**
898
- * Assumes zero initial velocity and the default mass: time-defined springs
899
- * ignore inherited velocity and only resolve without valid physics. Returns
900
- * NaN physics when the root search doesn't converge.
898
+ * Assumes zero initial velocity and the default mass: duration springs start
899
+ * from rest so they end exactly at their duration. Only resolves without
900
+ * valid physics. Returns NaN physics when the root search doesn't converge.
901
901
  */
902
902
  function findSpring({ duration = defaultDuration, bounce = defaultBounce, }) {
903
903
  let envelope;
@@ -975,7 +975,7 @@ function resolvePhysics(value, canBeZero) {
975
975
  if (isValidPhysics(value, canBeZero))
976
976
  return value;
977
977
  if (process.env.NODE_ENV !== "production") {
978
- motionUtils.warning(value === undefined, "Spring stiffness and mass must be positive, damping 0 or greater", "spring-invalid-physics");
978
+ motionUtils.warning(value === undefined || value === "auto", "Spring stiffness and mass must be positive, damping 0 or greater", "spring-invalid-physics");
979
979
  }
980
980
  return undefined;
981
981
  }
@@ -1043,11 +1043,12 @@ function springGenerator(optionsOrVisualDuration = defaultVisualDuration, bounce
1043
1043
  const state = { done: false, value: origin };
1044
1044
  const { stiffness, damping, mass, duration, isResolvedFromDuration, isTimeDefined, } = getSpringOptions({ ...options });
1045
1045
  /**
1046
- * Time-defined springs ignore inherited velocity. Velocity from
1047
- * interrupted animations causes massive oscillation on small-range
1048
- * animations.
1046
+ * A duration spring must end exactly at its duration, and it's settled
1047
+ * from rest by then. Inherited velocity could leave it still moving, so
1048
+ * it starts from rest. Every other spring, visualDuration included, ends
1049
+ * when it comes to rest, so inherits velocity as its initial condition.
1049
1050
  */
1050
- const inheritVelocity = (velocity) => isTimeDefined ? 0 : -motionUtils.millisecondsToSeconds(velocity);
1051
+ const inheritVelocity = (velocity) => isResolvedFromDuration ? 0 : -motionUtils.millisecondsToSeconds(velocity);
1051
1052
  const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));
1052
1053
  const undampedAngularFreq = motionUtils.millisecondsToSeconds(Math.sqrt(stiffness / mass));
1053
1054
  const decay = dampingRatio * undampedAngularFreq;
@@ -1061,7 +1062,7 @@ function springGenerator(optionsOrVisualDuration = defaultVisualDuration, bounce
1061
1062
  const s = {
1062
1063
  target,
1063
1064
  delta: target - origin,
1064
- velocity: inheritVelocity(options.velocity || 0) || 0,
1065
+ velocity: inheritVelocity(options.velocity) || 0,
1065
1066
  restSpeed: 0,
1066
1067
  restDelta: 0,
1067
1068
  };
@@ -1208,7 +1209,6 @@ function springGenerator(optionsOrVisualDuration = defaultVisualDuration, bounce
1208
1209
  const easing = generateLinearEasing((progress) => generator.next(easingDuration * progress).value, easingDuration, 30);
1209
1210
  return easingDuration + "ms " + easing;
1210
1211
  },
1211
- toTransition: () => { },
1212
1212
  };
1213
1213
  return generator;
1214
1214
  }
@@ -1687,8 +1687,18 @@ class JSAnimation extends WithPromise {
1687
1687
  */
1688
1688
  this.stop = () => {
1689
1689
  const { motionValue } = this.options;
1690
- if (motionValue && motionValue.updatedAt !== time.now()) {
1691
- this.tick(time.now());
1690
+ const now = time.now();
1691
+ if (motionValue && motionValue.updatedAt !== now) {
1692
+ /**
1693
+ * Catch the value up to now, but measure its velocity from the
1694
+ * previous frame: marking it as updated now keeps the value's
1695
+ * previous-frame sample. This tick is usually less than a frame
1696
+ * after the last, and the animation's time is rounded to whole
1697
+ * milliseconds, so measured from the last frame alone the
1698
+ * velocity an interrupting animation inherits could read as 0,
1699
+ * or a multiple of the real one.
1700
+ */
1701
+ this.tick((motionValue.updatedAt = now));
1692
1702
  }
1693
1703
  this.isStopped = true;
1694
1704
  if (this.state === "idle")
@@ -7316,6 +7326,29 @@ function compress(min, max, easing) {
7316
7326
  };
7317
7327
  }
7318
7328
 
7329
+ /**
7330
+ * A curved path ties x and y to one progress value, so it takes the part of
7331
+ * the velocity along the straight line from start to end.
7332
+ */
7333
+ const pointToProgressVelocity = (tx, ty, { x, y }) => {
7334
+ const lengthSquared = tx * tx + ty * ty;
7335
+ return lengthSquared < 1 ? 0 : (-1e3 * (x * tx + y * ty)) / lengthSquared;
7336
+ };
7337
+ /**
7338
+ * With `mass: "auto"`, mass comes from the element's size: a 300px square
7339
+ * has mass 1, bigger elements are heavier and slower (mass 0.25 to 2), and
7340
+ * damping scales with mass so the spring keeps its bounce. The result is a
7341
+ * physics spring.
7342
+ */
7343
+ const resolveAutoMass = (t, size = 300) => {
7344
+ const mass = motionUtils.clamp(0.25, 2, size / 300);
7345
+ const { stiffness, damping } = getSpringOptions({
7346
+ ...t,
7347
+ duration: t.duration && motionUtils.secondsToMilliseconds(t.duration),
7348
+ });
7349
+ return { ...t, stiffness, damping: damping * Math.sqrt(mass), mass };
7350
+ };
7351
+
7319
7352
  /**
7320
7353
  * Reset an axis to the provided origin box.
7321
7354
  *
@@ -8411,6 +8444,37 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8411
8444
  !calcLength(this.snapshot.measuredBox.y)) {
8412
8445
  this.snapshot = undefined;
8413
8446
  }
8447
+ /**
8448
+ * Record how fast the element is moving when it's measured, so
8449
+ * the next layout animation can start at the same speed.
8450
+ */
8451
+ if (this.snapshot) {
8452
+ const { visualElement } = this.options;
8453
+ /**
8454
+ * A paused or stopped animation hands on no velocity.
8455
+ */
8456
+ const isRunning = this.currentAnimation?.state === "running";
8457
+ const edges = isRunning && this.animationEdges;
8458
+ /**
8459
+ * A child moving inside its parent hands on only its
8460
+ * velocity relative to the parent.
8461
+ */
8462
+ if (isRunning && this.relativeTarget) {
8463
+ this.snapshot.relativeVelocity =
8464
+ this.relativeVelocity?.slice() || [];
8465
+ }
8466
+ const progress = (edges && this.motionValue?.getVelocity()) || 0;
8467
+ const velocity = [0, 1, 2, 3, 4, 5].map((i) => (i < 4
8468
+ ? edges &&
8469
+ (this.edgeValues
8470
+ ? this.edgeVelocity(i)
8471
+ : (-edges[i] * progress) / 1000)
8472
+ : visualElement
8473
+ ?.getValue(i < 5 ? "x" : "y")
8474
+ ?.getVelocity()) || 0);
8475
+ if (velocity.some(Boolean))
8476
+ this.snapshot.velocity = velocity;
8477
+ }
8414
8478
  }
8415
8479
  updateLayout() {
8416
8480
  if (!this.instance)
@@ -8936,11 +9000,62 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8936
9000
  // The path decides whether the layout shift is worth curving
8937
9001
  // (distance floor) and resolves the interpolator from the delta.
8938
9002
  const interpolate = pathFn?.interpolateProjection(delta);
9003
+ const box = this.layout?.layoutBox;
9004
+ let edges = box &&
9005
+ [box.x.min, box.x.max, box.y.min, box.y.max].map((edge, i) => {
9006
+ const { translate, scale, originPoint } = delta[i < 2 ? "x" : "y"];
9007
+ return (edge - originPoint) * (scale - 1) + translate;
9008
+ });
9009
+ /**
9010
+ * A zero-length layout axis has no finite edge offsets.
9011
+ */
9012
+ if (!edges?.every(isFinite))
9013
+ edges = undefined;
9014
+ this.animationEdges = edges;
9015
+ this.edgeValues =
9016
+ this.startVelocity =
9017
+ this.impulse =
9018
+ this.relativeVelocity =
9019
+ this.relativeStart =
9020
+ undefined;
9021
+ /**
9022
+ * A shared snapshot is measured with the old element's own
9023
+ * transforms (like x/y from drag), so it hands their velocity on
9024
+ * too. Otherwise those values keep animating themselves.
9025
+ */
9026
+ const velocity = snapshot?.velocity;
9027
+ /**
9028
+ * A child that wasn't moving inside an animating parent before
9029
+ * moved in page space, so that is its relative velocity.
9030
+ */
9031
+ const relative = snapshot?.relativeVelocity || velocity;
9032
+ if (relative?.slice(0, 4).some(Boolean) &&
9033
+ this.getClosestProjectingParent()) {
9034
+ this.relativeStart = relative;
9035
+ }
9036
+ if (velocity && edges) {
9037
+ const v = velocity
9038
+ .slice(0, 4)
9039
+ .map((edge, i) => edge +
9040
+ (isSharedLayoutAnimation
9041
+ ? velocity[4 + (i >> 1)]
9042
+ : 0));
9043
+ if (v.some(Boolean)) {
9044
+ this.startVelocity = interpolate
9045
+ ? pointToProgressVelocity(delta.x.translate, delta.y.translate, { x: (v[0] + v[1]) / 2, y: (v[2] + v[3]) / 2 })
9046
+ : v;
9047
+ }
9048
+ }
8939
9049
  this.mixTargetDelta = (latest) => {
8940
9050
  const progress = latest / 1000;
8941
9051
  const point = interpolate?.(progress);
8942
- mixAxisDeltaLinear(targetDelta.x, delta.x, progress);
8943
- mixAxisDeltaLinear(targetDelta.y, delta.y, progress);
9052
+ const values = this.edgeValues;
9053
+ for (let i = 0; i < 2; i++) {
9054
+ const axis = i ? "y" : "x";
9055
+ values
9056
+ ? edgesToDelta(targetDelta[axis], delta[axis], this.layout.layoutBox[axis], values[i * 2], values[i * 2 + 1])
9057
+ : mixAxisDeltaLinear(targetDelta[axis], delta[axis], progress);
9058
+ }
8944
9059
  if (point) {
8945
9060
  targetDelta.x.translate = point.x;
8946
9061
  targetDelta.y.translate = point.y;
@@ -8952,7 +9067,41 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8952
9067
  this.relativeParent &&
8953
9068
  this.relativeParent.layout) {
8954
9069
  calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox, this.options.layoutAnchor || undefined);
8955
- mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress);
9070
+ const from = this.relativeTargetOrigin;
9071
+ const to = relativeLayout;
9072
+ /**
9073
+ * A child mixes its place in its parent by progress,
9074
+ * so a nested tree moves as one.
9075
+ */
9076
+ mixBox(this.relativeTarget, from, to, progress);
9077
+ /**
9078
+ * Springs are linear, so the child's own velocity adds
9079
+ * the impulse response on top of the mix.
9080
+ */
9081
+ /**
9082
+ * Only springs take velocity, so a tween skips this.
9083
+ */
9084
+ if (this.isSpringLayout) {
9085
+ const box = this.relativeTarget;
9086
+ const impulse = this.impulse || 0;
9087
+ const start = this.relativeStart;
9088
+ const now = time.now();
9089
+ const dt = (now - this.relativeTime) / 1000;
9090
+ this.relativeTime = now;
9091
+ const speeds = (this.relativeVelocity || (this.relativeVelocity = [0, 0, 0, 0]));
9092
+ for (let i = 0; i < 4; i++) {
9093
+ const axis = i < 2 ? "x" : "y";
9094
+ const edge = i & 1 ? "max" : "min";
9095
+ if (start)
9096
+ box[axis][edge] += start[i] * impulse;
9097
+ if (prevRelativeTarget && dt > 0) {
9098
+ speeds[i] =
9099
+ (box[axis][edge] -
9100
+ prevRelativeTarget[axis][edge]) /
9101
+ dt;
9102
+ }
9103
+ }
9104
+ }
8956
9105
  /**
8957
9106
  * If this is an unchanged relative target we can consider the
8958
9107
  * projection not dirty.
@@ -8984,8 +9133,11 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8984
9133
  }
8985
9134
  startAnimation(options) {
8986
9135
  this.notifyListeners("animationStart");
9136
+ const isSpring = (this.isSpringLayout = options.type === "spring");
8987
9137
  this.currentAnimation?.stop();
8988
9138
  this.resumingFrom?.currentAnimation?.stop();
9139
+ if (this.resumingFrom)
9140
+ this.resumingFrom.edgeValues = undefined;
8989
9141
  if (this.pendingAnimation) {
8990
9142
  cancelFrame(this.pendingAnimation);
8991
9143
  this.pendingAnimation = undefined;
@@ -8999,9 +9151,114 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
8999
9151
  globalProjectionState.hasAnimatedSinceResize = true;
9000
9152
  this.motionValue || (this.motionValue = motionValue(0));
9001
9153
  this.motionValue.jump(0, false);
9002
- this.currentAnimation = animateSingleValue(this.motionValue, [0, 1000], {
9003
- ...options,
9004
- velocity: 0,
9154
+ /**
9155
+ * A duration spring ignores velocity, like in animate(), so
9156
+ * it ends on time.
9157
+ */
9158
+ const velocity = this.startVelocity;
9159
+ this.startVelocity = undefined;
9160
+ let transition = options;
9161
+ let mainVelocity = 0;
9162
+ if (isSpring) {
9163
+ /**
9164
+ * With mass: "auto", mass comes from the element's own
9165
+ * size.
9166
+ */
9167
+ if (options.mass === "auto") {
9168
+ const box = this.layout?.layoutBox;
9169
+ transition = resolveAutoMass(options, box &&
9170
+ Math.sqrt(calcLength(box.x) * calcLength(box.y)));
9171
+ }
9172
+ /**
9173
+ * Only springs take a velocity. A tween keeps one
9174
+ * driver, so its controls (pause, time) reach it all.
9175
+ */
9176
+ const relative = this.relativeStart;
9177
+ if ((velocity || relative) && !options.repeat) {
9178
+ if (typeof velocity === "number") {
9179
+ mainVelocity = velocity;
9180
+ }
9181
+ else {
9182
+ /**
9183
+ * Each edge (x min, x max, y min, y max) gets its
9184
+ * own spring in pixels, with its own start
9185
+ * velocity. An edge that doesn't move keeps
9186
+ * still, and a thrown element keeps its size.
9187
+ * One generator steps them all with the main
9188
+ * spring, so one animation drives them and its
9189
+ * controls reach them all.
9190
+ */
9191
+ const edges = velocity && this.animationEdges;
9192
+ transition = {
9193
+ ...transition,
9194
+ type: (o) => {
9195
+ const springs = [
9196
+ o.velocity,
9197
+ ...(velocity || []),
9198
+ ].map((v, i) => spring({
9199
+ ...o,
9200
+ keyframes: i
9201
+ ? [edges[i - 1], 0]
9202
+ : o.keyframes,
9203
+ velocity: v,
9204
+ }));
9205
+ const count = springs.length;
9206
+ /**
9207
+ * The response to 1000 px/s, for a
9208
+ * child's velocity inside its parent.
9209
+ * Coarse rest thresholds, because a
9210
+ * small offset of it is far below 1px.
9211
+ */
9212
+ relative &&
9213
+ springs.push(spring({
9214
+ ...o,
9215
+ keyframes: [0, 0],
9216
+ velocity: 1000,
9217
+ restDelta: 0.5,
9218
+ restSpeed: 5,
9219
+ }));
9220
+ let time = 0;
9221
+ const values = [];
9222
+ const generator = {
9223
+ calculatedDuration: null,
9224
+ next: (t) => {
9225
+ time = t;
9226
+ const state = springs[0].next(t);
9227
+ let done = state.done;
9228
+ for (let i = 1; i < springs.length; i++) {
9229
+ const { value, done: rest } = springs[i].next(t);
9230
+ if (i < count) {
9231
+ values[i - 1] = value;
9232
+ }
9233
+ else {
9234
+ this.impulse = value / 1000;
9235
+ }
9236
+ done = done && rest;
9237
+ }
9238
+ if (edges)
9239
+ this.edgeValues = values;
9240
+ state.done = done;
9241
+ return state;
9242
+ },
9243
+ };
9244
+ /**
9245
+ * Measure the duration now, then go back
9246
+ * to the start, so a delay shows the
9247
+ * start and not the end.
9248
+ */
9249
+ generator.calculatedDuration =
9250
+ calcGeneratorDuration(generator);
9251
+ generator.next(0);
9252
+ this.edgeVelocity = (i) => springs[i + 1].velocity(time);
9253
+ return generator;
9254
+ },
9255
+ };
9256
+ }
9257
+ }
9258
+ }
9259
+ const main = animateSingleValue(this.motionValue, [0, 1000], {
9260
+ ...transition,
9261
+ velocity: mainVelocity,
9005
9262
  isSync: true,
9006
9263
  onUpdate: (latest) => {
9007
9264
  this.mixTargetDelta(latest);
@@ -9012,6 +9269,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
9012
9269
  this.completeAnimation();
9013
9270
  },
9014
9271
  });
9272
+ this.currentAnimation = main;
9015
9273
  notifyLayoutAnimationStart(this.currentAnimation, this);
9016
9274
  if (this.resumingFrom) {
9017
9275
  this.resumingFrom.currentAnimation = this.currentAnimation;
@@ -9029,11 +9287,15 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
9029
9287
  this.resumingFrom =
9030
9288
  this.currentAnimation =
9031
9289
  this.animationValues =
9032
- undefined;
9290
+ this.edgeValues =
9291
+ this.edgeVelocity =
9292
+ this.impulse =
9293
+ undefined;
9033
9294
  this.notifyListeners("animationComplete");
9034
9295
  }
9035
9296
  finishAnimation() {
9036
9297
  if (this.currentAnimation) {
9298
+ this.edgeValues = this.impulse = undefined;
9037
9299
  this.mixTargetDelta?.(animationTarget);
9038
9300
  this.currentAnimation.stop();
9039
9301
  }
@@ -9529,6 +9791,18 @@ function calcProjection(node) {
9529
9791
  function resetSkewAndRotation(node) {
9530
9792
  node.resetSkewAndRotation();
9531
9793
  }
9794
+ /**
9795
+ * Build an axis delta that moves the layout's edges by these offsets (px).
9796
+ */
9797
+ function edgesToDelta(output, delta, layout, min, max) {
9798
+ const length = layout.max - layout.min;
9799
+ const scale = length ? Math.max(0, (length + max - min) / length) : 1;
9800
+ const origin = (output.originPoint = delta.originPoint);
9801
+ output.origin = delta.origin;
9802
+ output.scale = scale;
9803
+ output.translate =
9804
+ layout.min + min - (origin + (layout.min - origin) * scale);
9805
+ }
9532
9806
  function mixAxisDeltaLinear(output, delta, p) {
9533
9807
  output.translate = mixNumber$1(delta.translate, 0, p);
9534
9808
  output.scale = mixNumber$1(delta.scale, 1, p);
@@ -12412,15 +12686,14 @@ function addPinchListeners(element, getValues, getEnabledOptions, onPinchStart)
12412
12686
  * step and the focal point stays in place.
12413
12687
  */
12414
12688
  const tick = () => {
12415
- if (dragControls()?.isDragging)
12416
- return stopSnap();
12417
12689
  const { value: p, done } = generator.next(time.now() - startTime);
12418
12690
  if (done)
12419
12691
  stopSnap();
12420
12692
  const [k, r, fx, fy] = at(p);
12421
12693
  scaleOption !== false && scale.set(k);
12422
12694
  rotateOption !== false && rotate.set(r);
12423
- if (moves) {
12695
+ // A drag that starts mid-snap owns x/y from then on.
12696
+ if (moves && !dragControls()?.isDragging) {
12424
12697
  x.set(snapToOrigin ? mixNumber$1(x0, 0, p) : fx);
12425
12698
  y.set(snapToOrigin ? mixNumber$1(y0, 0, p) : fy);
12426
12699
  }
@@ -15640,6 +15913,7 @@ exports.getFinalKeyframe = getFinalKeyframe;
15640
15913
  exports.getMixer = getMixer;
15641
15914
  exports.getOptimisedAppearId = getOptimisedAppearId;
15642
15915
  exports.getOriginIndex = getOriginIndex;
15916
+ exports.getSpringOptions = getSpringOptions;
15643
15917
  exports.getValueAsType = getValueAsType;
15644
15918
  exports.getValueTransition = getValueTransition;
15645
15919
  exports.getVariableValue = getVariableValue;