motion-dom 14.9.1 → 14.10.1

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 (46) hide show
  1. package/dist/cjs/index.js +729 -183
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/es/animation/GroupAnimation.mjs +21 -15
  4. package/dist/es/animation/GroupAnimation.mjs.map +1 -1
  5. package/dist/es/animation/JSAnimation.mjs +6 -0
  6. package/dist/es/animation/JSAnimation.mjs.map +1 -1
  7. package/dist/es/animation/NativeAnimation.mjs +5 -0
  8. package/dist/es/animation/NativeAnimation.mjs.map +1 -1
  9. package/dist/es/animation/animate/effects.mjs +15 -4
  10. package/dist/es/animation/animate/effects.mjs.map +1 -1
  11. package/dist/es/animation/animate/single-value.mjs +1 -1
  12. package/dist/es/animation/animate/single-value.mjs.map +1 -1
  13. package/dist/es/animation/generators/keyframes.mjs +44 -16
  14. package/dist/es/animation/generators/keyframes.mjs.map +1 -1
  15. package/dist/es/animation/interfaces/visual-element-target.mjs +1 -1
  16. package/dist/es/animation/interfaces/visual-element-target.mjs.map +1 -1
  17. package/dist/es/animation/keyframes/DOMKeyframesResolver.mjs +8 -3
  18. package/dist/es/animation/keyframes/DOMKeyframesResolver.mjs.map +1 -1
  19. package/dist/es/animation/keyframes/get-final.mjs +18 -4
  20. package/dist/es/animation/keyframes/get-final.mjs.map +1 -1
  21. package/dist/es/animation/waapi/transforms/TransformAnimation.mjs +347 -88
  22. package/dist/es/animation/waapi/transforms/TransformAnimation.mjs.map +1 -1
  23. package/dist/es/gestures/drag/VisualElementDragControls.mjs +3 -3
  24. package/dist/es/gestures/drag/VisualElementDragControls.mjs.map +1 -1
  25. package/dist/es/gestures/drag/index.mjs +4 -1
  26. package/dist/es/gestures/drag/index.mjs.map +1 -1
  27. package/dist/es/gestures/pan/PanSession.mjs +6 -2
  28. package/dist/es/gestures/pan/PanSession.mjs.map +1 -1
  29. package/dist/es/gestures/press/index.mjs +179 -8
  30. package/dist/es/gestures/press/index.mjs.map +1 -1
  31. package/dist/es/gestures/press/utils/keyboard.mjs +1 -1
  32. package/dist/es/gestures/press/utils/keyboard.mjs.map +1 -1
  33. package/dist/es/projection/styles/transform.mjs +39 -17
  34. package/dist/es/projection/styles/transform.mjs.map +1 -1
  35. package/dist/es/value/index.mjs +24 -20
  36. package/dist/es/value/index.mjs.map +1 -1
  37. package/dist/es/value/types/utils/animatable-none.mjs +13 -1
  38. package/dist/es/value/types/utils/animatable-none.mjs.map +1 -1
  39. package/dist/index.d.ts +163 -13
  40. package/dist/motion-dom.dev.js +729 -183
  41. package/dist/motion-dom.js +1 -1
  42. package/dist/size-rollup-motion-value.js +1 -1
  43. package/dist/size-rollup-motion-value.js.map +1 -1
  44. package/dist/size-rollup-style-effect.js +1 -1
  45. package/dist/size-rollup-style-effect.js.map +1 -1
  46. package/package.json +2 -2
package/dist/cjs/index.js CHANGED
@@ -1425,25 +1425,53 @@ function keyframes({ duration = 300, keyframes: keyframeValues, times, ease = "e
1425
1425
  value: keyframeValues[0],
1426
1426
  };
1427
1427
  /**
1428
- * Fast setup path for two keyframes one easing. interpolate() handles
1429
- * a custom mixer, and falls back to the usual one where it declines.
1430
- */
1431
- if (!customMixer &&
1432
- keyframeValues.length === 2 &&
1433
- !Array.isArray(easingFunctions) &&
1434
- (!times ||
1435
- times.length !== 2 ||
1436
- (times[0] === 0 && times[1] === 1))) {
1437
- const [origin, target] = keyframeValues;
1438
- const mixer = origin === target
1439
- ? undefined
1440
- : (motionUtils.MotionGlobalConfig.mix || mix)(origin, target);
1428
+ * Two keyframes, or keyframes that hold, move once, then hold, as each
1429
+ * value of a sequence does, ease and mix only the pair that moves.
1430
+ */
1431
+ let span = -1;
1432
+ if (!customMixer) {
1433
+ for (let i = 1; i < keyframeValues.length; i++) {
1434
+ if (keyframeValues[i] !== keyframeValues[i - 1]) {
1435
+ if (span >= 0) {
1436
+ span = -2;
1437
+ break;
1438
+ }
1439
+ span = i - 1;
1440
+ }
1441
+ }
1442
+ }
1443
+ if (span >= 0) {
1444
+ const offsets = times && times.length === keyframeValues.length
1445
+ ? times
1446
+ : defaultOffset(keyframeValues);
1447
+ const from = offsets[span] * duration;
1448
+ const to = offsets[span + 1] * duration;
1449
+ const origin = keyframeValues[span];
1450
+ const target = keyframeValues[span + 1];
1451
+ const ease = Array.isArray(easingFunctions)
1452
+ ? easingFunctions[span]
1453
+ : easingFunctions;
1454
+ const mixer = (motionUtils.MotionGlobalConfig.mix || mix)(origin, target);
1455
+ const last = keyframeValues.length - 2;
1441
1456
  return {
1442
1457
  calculatedDuration: duration,
1443
1458
  next: (t) => {
1444
- state.value = mixer
1445
- ? mixer(easingFunctions(duration > 0 ? motionUtils.clamp(0, 1, t / duration) : 1))
1446
- : target;
1459
+ /**
1460
+ * Held keyframes either side of the move are mixed as
1461
+ * interpolate() mixes them, so colours keep its format.
1462
+ */
1463
+ state.value =
1464
+ span && t < from
1465
+ ? mixer(0)
1466
+ : span < last && (t >= to || !duration)
1467
+ ? typeof target === "number"
1468
+ ? target
1469
+ : mixer(1)
1470
+ : mixer(ease(t >= to || !duration
1471
+ ? 1
1472
+ : t <= from
1473
+ ? 0
1474
+ : (t - from) / (to - from)));
1447
1475
  state.done = t >= duration;
1448
1476
  return state;
1449
1477
  },
@@ -1492,13 +1520,27 @@ function calcGeneratorVelocity(generator, t, initialVelocity = 0) {
1492
1520
  : getGeneratorVelocity((s) => generator.next(s).value, t, generator.next(t).value);
1493
1521
  }
1494
1522
 
1495
- const isNotNull = (value) => value !== null;
1496
1523
  function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe, speed = 1) {
1497
- const resolvedKeyframes = keyframes.filter(isNotNull);
1524
+ /**
1525
+ * The first and last keyframes that aren't null, and how many there
1526
+ * are. Found in one pass rather than filtering into a new array, as
1527
+ * this runs for every value of every animation.
1528
+ */
1529
+ let first;
1530
+ let last;
1531
+ let numResolved = 0;
1532
+ for (let i = 0; i < keyframes.length; i++) {
1533
+ const keyframe = keyframes[i];
1534
+ if (keyframe !== null) {
1535
+ if (!numResolved++)
1536
+ first = keyframe;
1537
+ last = keyframe;
1538
+ }
1539
+ }
1498
1540
  const useFirstKeyframe = speed < 0 || (repeat && repeatType !== "loop" && repeat % 2 === 1);
1499
- const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1;
1541
+ const index = useFirstKeyframe ? 0 : numResolved - 1;
1500
1542
  return !index || finalKeyframe === undefined
1501
- ? resolvedKeyframes[index]
1543
+ ? (index ? last : first)
1502
1544
  : finalKeyframe;
1503
1545
  }
1504
1546
 
@@ -1886,6 +1928,12 @@ class JSAnimation extends WithPromise {
1886
1928
  return motionUtils.millisecondsToSeconds(this.currentTime);
1887
1929
  }
1888
1930
  set time(newTime) {
1931
+ /**
1932
+ * Seeking out of "finished" leaves the animation paused, so play()
1933
+ * won't renew finished. Renew it here.
1934
+ */
1935
+ if (this.state === "finished")
1936
+ this.updateFinished();
1889
1937
  newTime = motionUtils.secondsToMilliseconds(newTime);
1890
1938
  this.currentTime = newTime;
1891
1939
  if (this.startTime === null ||
@@ -2172,14 +2220,26 @@ const defaultValueTypes = {
2172
2220
  const getDefaultValueType = (key) => defaultValueTypes[key];
2173
2221
 
2174
2222
  const customTypes = /*@__PURE__*/ new Set([filter, mask]);
2223
+ /**
2224
+ * The last call and its result. animate() on many elements asks for the
2225
+ * same none for each one, and parsing the value is the slow part.
2226
+ */
2227
+ let lastKey;
2228
+ let lastValue;
2229
+ let lastNone;
2175
2230
  function getAnimatableNone(key, value) {
2231
+ if (key === lastKey && value === lastValue)
2232
+ return lastNone;
2176
2233
  let defaultValueType = getDefaultValueType(key);
2177
2234
  if (!customTypes.has(defaultValueType))
2178
2235
  defaultValueType = complex;
2179
2236
  // If value is not recognised as animatable, ie "none", create an animatable version origin based on the target
2180
- return defaultValueType.getAnimatableNone
2237
+ lastNone = defaultValueType.getAnimatableNone
2181
2238
  ? defaultValueType.getAnimatableNone(value)
2182
2239
  : undefined;
2240
+ lastKey = key;
2241
+ lastValue = value;
2242
+ return lastNone;
2183
2243
  }
2184
2244
 
2185
2245
  function fillWildcards(keyframes) {
@@ -2771,8 +2831,13 @@ class NativeAnimation extends WithPromise {
2771
2831
  this.manualStartTime = null;
2772
2832
  this.finishedTime = null;
2773
2833
  this.animation.currentTime = motionUtils.secondsToMilliseconds(newTime);
2834
+ /**
2835
+ * Seeking out of "finished" leaves the animation paused, so play()
2836
+ * won't renew finished. Renew it here.
2837
+ */
2774
2838
  if (wasFinished) {
2775
2839
  this.animation.pause();
2840
+ this.updateFinished();
2776
2841
  }
2777
2842
  }
2778
2843
  /**
@@ -3200,10 +3265,40 @@ const scaleTolerance = 0.001;
3200
3265
  * rebuilding the WAAPI animation every frame.
3201
3266
  */
3202
3267
  const churnWindow = 100;
3268
+ /**
3269
+ * A WAAPI animation that starts moving later than this, as most segments
3270
+ * of a long sequence do, is built this long before it starts, rather than
3271
+ * all at once at the start.
3272
+ */
3273
+ const buildAhead = 100;
3203
3274
  /**
3204
3275
  * Named easings that are the same cubic-bezier in JS and CSS.
3205
3276
  */
3206
- const isNativeEasing = (ease) => /^(linear|ease(In|Out|InOut))$/.test(ease);
3277
+ const nativeEasings = new Set(["linear", "easeIn", "easeOut", "easeInOut"]);
3278
+ const isNativeEasing = (ease) => nativeEasings.has(ease);
3279
+ /**
3280
+ * The last trace of each easing WAAPI can't run into linear(), with its
3281
+ * number of samples, so the elements of a sequence that share an easing
3282
+ * and duration trace it once.
3283
+ */
3284
+ const traced = new WeakMap();
3285
+ const trace = (ease, samples) => {
3286
+ let last = traced.get(ease);
3287
+ if (last?.[0] !== samples) {
3288
+ last = [
3289
+ samples,
3290
+ "linear(" +
3291
+ defaultOffset(Array(samples + 1)).map((p) => round(ease(p)) + " " + round(p * 100) + "%") +
3292
+ ")",
3293
+ ];
3294
+ traced.set(ease, last);
3295
+ }
3296
+ return last[1];
3297
+ };
3298
+ /**
3299
+ * How many samples trace an easing between two timestamps.
3300
+ */
3301
+ const countSamples = (from, to) => Math.min(maxSamples, Math.max(2, Math.ceil((to - from) / sampleDelta)));
3207
3302
  /**
3208
3303
  * Whether two eased progresses match. False if either is NaN.
3209
3304
  */
@@ -3264,6 +3359,54 @@ function canAccelerateTransform(options) {
3264
3359
  */
3265
3360
  !needsMixer(options));
3266
3361
  }
3362
+ /**
3363
+ * Starting or stopping tells the group to update its WAAPI animation.
3364
+ * The frame loop driver is only made once the group is on the main
3365
+ * thread, as accelerated animations never tick.
3366
+ */
3367
+ class TransformDriver {
3368
+ constructor(element, update, makeDriver, animation) {
3369
+ this.element = element;
3370
+ this.update = update;
3371
+ this.makeDriver = makeDriver;
3372
+ this.animation = animation;
3373
+ }
3374
+ get js() {
3375
+ return (this.driver || (this.driver = this.makeDriver(this.update)));
3376
+ }
3377
+ now() {
3378
+ return this.driver || this.makeDriver !== frameloopDriver
3379
+ ? this.js.now()
3380
+ : frameData.isProcessing
3381
+ ? frameData.timestamp
3382
+ : time.now();
3383
+ }
3384
+ /**
3385
+ * keepAlive is false when seeking. Seeking the WAAPI animation is
3386
+ * free, but if a seek needs a rebuild and keeps happening, the group
3387
+ * moves to the main thread.
3388
+ */
3389
+ start(keepAlive = true) {
3390
+ const group = getGroup(this.element);
3391
+ !group || group.isJS
3392
+ ? this.js.start(keepAlive)
3393
+ : group.schedule(false, !keepAlive);
3394
+ }
3395
+ stopJS() {
3396
+ this.driver?.stop();
3397
+ }
3398
+ stop() {
3399
+ this.stopJS();
3400
+ const group = getGroup(this.element);
3401
+ group && !group.isFinishing && group.release(this.animation);
3402
+ }
3403
+ }
3404
+ /**
3405
+ * JSAnimation's time setter, looked up on first use rather than at module
3406
+ * load, so the module has no top-level side effects and stays
3407
+ * tree-shakeable in flattened bundles.
3408
+ */
3409
+ let setTime;
3267
3410
  class TransformAnimation extends JSAnimation {
3268
3411
  constructor(options) {
3269
3412
  const element = getOwner(options).current;
@@ -3275,35 +3418,16 @@ class TransformAnimation extends JSAnimation {
3275
3418
  const canAccelerate = canAccelerateTransform(options);
3276
3419
  /**
3277
3420
  * The driver ticks on the main thread only once the group has
3278
- * moved there. Until then, starting or stopping tells the group to
3279
- * update its WAAPI animation.
3421
+ * moved there, so its frame loop driver is made then.
3280
3422
  */
3281
- options.driver = (update) => {
3282
- const js = driver(update);
3283
- return {
3284
- js,
3285
- now: js.now,
3286
- start: (keepAlive = true) => {
3287
- const group = getGroup(element);
3288
- const isJS = !group || group.isJS;
3289
- /**
3290
- * keepAlive is false when seeking. Seeking the WAAPI
3291
- * animation is free, but if a seek needs a rebuild and
3292
- * keeps happening, the group moves to the main thread.
3293
- */
3294
- isJS
3295
- ? js.start(keepAlive)
3296
- : group.schedule(false, !keepAlive);
3297
- },
3298
- stop: () => {
3299
- js.stop();
3300
- const group = getGroup(element);
3301
- group && !group.isFinishing && group.release(animation);
3302
- },
3303
- };
3304
- };
3423
+ options.driver = (update) => new TransformDriver(element, update, driver, animation);
3305
3424
  super(options);
3306
3425
  animation = this;
3426
+ /**
3427
+ * The first driver is made in super(), before this was assigned.
3428
+ */
3429
+ const firstDriver = this.driver;
3430
+ firstDriver && (firstDriver.animation = this);
3307
3431
  this.canAccelerate = canAccelerate;
3308
3432
  /**
3309
3433
  * stop is bound in JSAnimation, so wrap it rather than override.
@@ -3317,12 +3441,29 @@ class TransformAnimation extends JSAnimation {
3317
3441
  stop();
3318
3442
  };
3319
3443
  }
3444
+ /**
3445
+ * Each keyframe's offset, made once for the keyframes rather than on
3446
+ * every build.
3447
+ */
3448
+ offsets() {
3449
+ const { keyframes, times } = this.options;
3450
+ if (times)
3451
+ return times;
3452
+ if (this.offsetsOf !== keyframes) {
3453
+ this.offsetsOf = keyframes;
3454
+ this.cachedOffsets = defaultOffset(keyframes);
3455
+ }
3456
+ return this.cachedOffsets;
3457
+ }
3320
3458
  get group() {
3321
3459
  return getGroup(getOwner(this.options).current);
3322
3460
  }
3323
3461
  get js() {
3324
3462
  return this.driver?.js;
3325
3463
  }
3464
+ stopJS() {
3465
+ this.driver?.stopJS();
3466
+ }
3326
3467
  get name() {
3327
3468
  return this.options.name;
3328
3469
  }
@@ -3362,22 +3503,48 @@ class TransformAnimation extends JSAnimation {
3362
3503
  return this.isAccelerated() ? this.sampleAt(time.now()) : undefined;
3363
3504
  }
3364
3505
  /**
3365
- * If this is a two-keyframe tween whose easing WAAPI runs exactly,
3366
- * when it starts and stops moving, and that easing.
3506
+ * If this moves between two keyframes only, holding still either side
3507
+ * of them, as each value of a sequence segment does, when it starts
3508
+ * and stops moving, and its easing: as a string if WAAPI runs it
3509
+ * exactly, otherwise its function, to trace.
3367
3510
  */
3368
3511
  tween() {
3369
- const { keyframes: keyframes$1, type, ease, times, repeat, delay = 0 } = this.options;
3370
- const easing = motionUtils.isBezierDefinition(ease)
3371
- ? cubicBezierAsString(ease)
3372
- : isNativeEasing(ease) && supportedWaapiEasing[ease];
3373
- if (easing &&
3374
- !repeat &&
3375
- !times &&
3376
- keyframes$1.length === 2 &&
3377
- type === keyframes &&
3378
- this.holdTime === null) {
3379
- const start = this.startTime + delay / this.speed;
3380
- return [start, start + this.resolvedDuration / this.speed, easing];
3512
+ const { keyframes: keyframes$1, type, repeat, delay = 0 } = this.options;
3513
+ let span = -1;
3514
+ if (repeat || type !== keyframes || this.holdTime !== null) {
3515
+ return;
3516
+ }
3517
+ for (let i = 1; i < keyframes$1.length; i++) {
3518
+ if (keyframes$1[i] !== keyframes$1[i - 1]) {
3519
+ if (span >= 0)
3520
+ return;
3521
+ span = i - 1;
3522
+ }
3523
+ }
3524
+ let { ease } = this.options;
3525
+ if (motionUtils.isEasingArray(ease))
3526
+ ease = ease[span];
3527
+ const offsets = this.offsets();
3528
+ const at = (i) => this.startTime +
3529
+ (delay + offsets[i] * this.totalDuration) / this.speed;
3530
+ if (span >= 0) {
3531
+ const easing = motionUtils.isBezierDefinition(ease)
3532
+ ? cubicBezierAsString(ease)
3533
+ : isNativeEasing(ease)
3534
+ ? supportedWaapiEasing[ease]
3535
+ : motionUtils.easingDefinitionToFunction(ease);
3536
+ /**
3537
+ * An easing that doesn't run from 0 to 1 doesn't move between
3538
+ * the keyframes, so is traced from the values it gives instead.
3539
+ */
3540
+ return [
3541
+ at(span),
3542
+ at(span + 1),
3543
+ typeof easing === "string" ||
3544
+ (isNear$1(easing(0), 0) && isNear$1(easing(1), 1))
3545
+ ? easing
3546
+ : undefined,
3547
+ ];
3381
3548
  }
3382
3549
  }
3383
3550
  /**
@@ -3386,9 +3553,9 @@ class TransformAnimation extends JSAnimation {
3386
3553
  */
3387
3554
  boundaries(from, to) {
3388
3555
  const { startTime, speed, resolvedDuration, options } = this;
3389
- const { delay = 0, repeat = 0, repeatDelay = 0, repeatType, times, keyframes: keyframes$1, type, } = options;
3556
+ const { delay = 0, repeat = 0, repeatDelay = 0, repeatType, type, } = options;
3390
3557
  const offsets = (type || keyframes) === keyframes
3391
- ? times || defaultOffset(keyframes$1)
3558
+ ? this.offsets()
3392
3559
  : [0, 1];
3393
3560
  const start = startTime + delay / speed;
3394
3561
  const result = [];
@@ -3421,7 +3588,14 @@ class TransformAnimation extends JSAnimation {
3421
3588
  */
3422
3589
  sync() {
3423
3590
  const now = time.now();
3424
- this.options.motionValue.setWithVelocity(this.sampleAt(now - sampleDelta, true), this.sampleAt(now, true), sampleDelta);
3591
+ const value = this.sampleAt(now, true);
3592
+ /**
3593
+ * A held value doesn't move, so there's no need to sample it
3594
+ * twice.
3595
+ */
3596
+ this.options.motionValue.setWithVelocity(this.holdTime === null
3597
+ ? this.sampleAt(now - sampleDelta, true)
3598
+ : value, value, sampleDelta);
3425
3599
  }
3426
3600
  play() {
3427
3601
  /**
@@ -3435,10 +3609,7 @@ class TransformAnimation extends JSAnimation {
3435
3609
  }
3436
3610
  pause() {
3437
3611
  super.pause();
3438
- if (this.isAccelerated()) {
3439
- this.sync();
3440
- this.group.schedule(false);
3441
- }
3612
+ this.isAccelerated() && this.group.schedule(false);
3442
3613
  }
3443
3614
  /**
3444
3615
  * JSAnimation finishes on its next tick, which only happens once the
@@ -3462,13 +3633,11 @@ class TransformAnimation extends JSAnimation {
3462
3633
  return super.time;
3463
3634
  }
3464
3635
  /**
3465
- * A JS animation sets its motion value from a seek on its next tick.
3466
- * This doesn't tick, so set it now, rather than leave it to be set
3467
- * when this next stops.
3636
+ * Calls JSAnimation's setter directly, as `super.time =` is a slow
3637
+ * path in V8 and this runs for every animation of a seeked sequence.
3468
3638
  */
3469
3639
  set time(newTime) {
3470
- super.time = newTime;
3471
- this.isAccelerated() && this.sync();
3640
+ (setTime ?? (setTime = Object.getOwnPropertyDescriptor(JSAnimation.prototype, "time").set)).call(this, newTime);
3472
3641
  }
3473
3642
  /**
3474
3643
  * Scroll timelines set time every frame, so run these on the main
@@ -3480,6 +3649,20 @@ class TransformAnimation extends JSAnimation {
3480
3649
  return super.attachTimeline(timeline);
3481
3650
  }
3482
3651
  }
3652
+ /**
3653
+ * Groups that build straight after the current task build in one
3654
+ * microtask, rather than one each.
3655
+ */
3656
+ let builds;
3657
+ const buildSoon = (build) => {
3658
+ builds ||
3659
+ queueMicrotask(() => {
3660
+ const queue = builds;
3661
+ builds = undefined;
3662
+ queue.forEach((build) => build());
3663
+ });
3664
+ (builds || (builds = [])).push(build);
3665
+ };
3483
3666
  function createGroup(owner) {
3484
3667
  const element = owner.current;
3485
3668
  const tracks = new Set();
@@ -3499,6 +3682,13 @@ function createGroup(owner) {
3499
3682
  let isEnded = false;
3500
3683
  let hasChurned = false;
3501
3684
  let lastChurn = -Infinity;
3685
+ let wake;
3686
+ let wakeAt = Infinity;
3687
+ /**
3688
+ * While waiting to build a tween that starts later, how long after
3689
+ * the last build to build it.
3690
+ */
3691
+ let buildAt;
3502
3692
  const has = (key) => {
3503
3693
  for (const track of tracks)
3504
3694
  if (track.name === key)
@@ -3566,6 +3756,9 @@ function createGroup(owner) {
3566
3756
  * transform. The renderer writes its own version on its next render.
3567
3757
  */
3568
3758
  const stop = (shouldCommit = true) => {
3759
+ clearTimeout(wake);
3760
+ wakeAt = Infinity;
3761
+ buildAt = undefined;
3569
3762
  shouldCommit && commit();
3570
3763
  segments.forEach(({ animation }) => cancel(animation));
3571
3764
  segments = [];
@@ -3619,12 +3812,31 @@ function createGroup(owner) {
3619
3812
  * two timestamps, the easing that describes it.
3620
3813
  */
3621
3814
  const getEasing = (moving, from, to, bounds) => {
3622
- const samples = Math.min(maxSamples, Math.max(2, Math.ceil((to - from) / sampleDelta)));
3815
+ const samples = countSamples(from, to);
3623
3816
  /**
3624
3817
  * Too many keyframes or repeats to follow with this many samples.
3625
3818
  */
3626
3819
  if (bounds.length * 4 > samples)
3627
3820
  return;
3821
+ /**
3822
+ * First check half way, where values with different easings
3823
+ * usually differ, before sampling every value many times.
3824
+ */
3825
+ let quick;
3826
+ for (const track of moving) {
3827
+ const first = track.numberAt(from);
3828
+ const p = (track.numberAt((from + to) / 2) - first) /
3829
+ (track.numberAt(to) - first);
3830
+ /**
3831
+ * NaN if it doesn't move.
3832
+ */
3833
+ if (p !== p)
3834
+ continue;
3835
+ if (quick === undefined)
3836
+ quick = p;
3837
+ else if (!isNear$1(p, quick))
3838
+ return;
3839
+ }
3628
3840
  const at = spread(from, to, samples).concat(bounds).sort(byTime);
3629
3841
  const position = (t) => motionUtils.progress(from, to, t);
3630
3842
  let shared;
@@ -3681,11 +3893,30 @@ function createGroup(owner) {
3681
3893
  */
3682
3894
  const sample = (moving, from, to, bounds) => {
3683
3895
  const times = [from];
3896
+ /**
3897
+ * A linear tween is straight between its keyframes, so only the
3898
+ * other values can curve, and a tween only while it moves.
3899
+ */
3900
+ const curved = [];
3901
+ let curveFrom = to;
3902
+ let curveTo = from;
3903
+ for (const track of moving) {
3904
+ const tween = track.tween();
3905
+ if (tween?.[2] !== "linear") {
3906
+ const [trackEnd, cycle] = track.timing();
3907
+ const [a, b] = tween || [from, cycle ? to : trackEnd];
3908
+ curveFrom = Math.min(curveFrom, a);
3909
+ curveTo = Math.max(curveTo, b);
3910
+ curved.push(track);
3911
+ }
3912
+ }
3913
+ curveFrom = Math.max(from, curveFrom);
3914
+ curveTo = Math.min(to, curveTo);
3684
3915
  /**
3685
3916
  * Values that aren't numbers, like calc(), are left to the
3686
3917
  * browser to interpolate.
3687
3918
  */
3688
- const isStraight = (a, b) => moving.every((track) => !(Math.abs(track.numberAt((a + b) / 2) -
3919
+ const isStraight = (a, b) => curved.every((track) => !(Math.abs(track.numberAt((a + b) / 2) -
3689
3920
  (track.numberAt(a) + track.numberAt(b)) / 2) >
3690
3921
  (track.name.startsWith("scale")
3691
3922
  ? scaleTolerance
@@ -3710,10 +3941,13 @@ function createGroup(owner) {
3710
3941
  }
3711
3942
  };
3712
3943
  /**
3713
- * Split at least every 100ms, and at every keyframe and repeat,
3714
- * either side of where a value can jump.
3944
+ * Split at least every 100ms where a value can curve, and at every
3945
+ * keyframe and repeat, either side of where a value can jump.
3715
3946
  */
3716
- const ends = spread(from, to, Math.ceil((to - from) / 100));
3947
+ const ends = curveTo > curveFrom
3948
+ ? spread(curveFrom, curveTo, Math.ceil((curveTo - curveFrom) / 100))
3949
+ : [];
3950
+ ends.push(to);
3717
3951
  for (const t of bounds)
3718
3952
  ends.push(t, Math.min(t + 0.01, to));
3719
3953
  let start = from;
@@ -3733,12 +3967,20 @@ function createGroup(owner) {
3733
3967
  for (const track of moving) {
3734
3968
  const tween = track.tween();
3735
3969
  if (!tween ||
3736
- shared?.some((v, i) => i < 2
3737
- ? Math.abs(tween[i] - v) > 1
3738
- : tween[i] !== v)) {
3970
+ (shared &&
3971
+ (Math.abs(tween[0] - shared[0]) > 1 ||
3972
+ Math.abs(tween[1] - shared[1]) > 1))) {
3739
3973
  return;
3740
3974
  }
3741
- shared = tween;
3975
+ /**
3976
+ * Easings that differ, like the springs a sequence makes for
3977
+ * each value, can still be the same curve.
3978
+ */
3979
+ shared = [
3980
+ tween[0],
3981
+ tween[1],
3982
+ !shared || tween[2] === shared[2] ? tween[2] : undefined,
3983
+ ];
3742
3984
  }
3743
3985
  return shared;
3744
3986
  };
@@ -3746,7 +3988,13 @@ function createGroup(owner) {
3746
3988
  * A WAAPI animation of the composed transform between two timestamps.
3747
3989
  */
3748
3990
  const run = (moving, from, to, nativeEasing, options = { fill: "both" }, settled) => {
3749
- const bounds = moving.flatMap((track) => track.boundaries(from, to));
3991
+ /**
3992
+ * With an easing given, there's nothing to sample, so no need
3993
+ * for the boundaries.
3994
+ */
3995
+ const bounds = nativeEasing
3996
+ ? []
3997
+ : moving.flatMap((track) => track.boundaries(from, to));
3750
3998
  const easing = nativeEasing || getEasing(moving, from, to, bounds);
3751
3999
  const times = easing ? [from, to] : sample(moving, from, to, bounds);
3752
4000
  const transform = times.map((t) => compose(t, settled));
@@ -3769,6 +4017,23 @@ function createGroup(owner) {
3769
4017
  easing: easing || "linear",
3770
4018
  });
3771
4019
  };
4020
+ /**
4021
+ * Check whether it's time to build in this long. A check that's due
4022
+ * sooner is kept, and checks again if it's early, so pausing and
4023
+ * playing don't each replace a timer. One due later, after a seek or
4024
+ * speed change while held, is replaced.
4025
+ */
4026
+ const wakeIn = (delay) => {
4027
+ const at = time.now() + delay;
4028
+ if (at < wakeAt) {
4029
+ clearTimeout(wake);
4030
+ wakeAt = at;
4031
+ wake = setTimeout(() => {
4032
+ wakeAt = Infinity;
4033
+ group.schedule(false);
4034
+ }, delay);
4035
+ }
4036
+ };
3772
4037
  /**
3773
4038
  * Replace the WAAPI animations with ones built from now. Returns
3774
4039
  * undefined if the animations can't be composed.
@@ -3793,14 +4058,8 @@ function createGroup(owner) {
3793
4058
  const [trackEnd, trackCycle] = track.timing();
3794
4059
  const isHeld = trackEnd === Infinity;
3795
4060
  built.set(track, [track.at(now), track.speed, isHeld]);
3796
- /**
3797
- * Held animations don't move, so keep their motion values up
3798
- * to date, as a JSAnimation would on a seek.
3799
- */
3800
- if (isHeld) {
3801
- track.sync();
4061
+ if (isHeld)
3802
4062
  continue;
3803
- }
3804
4063
  if (track.speed < 0)
3805
4064
  return;
3806
4065
  if (trackCycle) {
@@ -3840,12 +4099,35 @@ function createGroup(owner) {
3840
4099
  */
3841
4100
  const tween = !cycle && getTween(moving);
3842
4101
  try {
3843
- if (tween && tween[1] > now) {
3844
- const [from, to, easing] = tween;
3845
- add(run(moving, from, to, easing), from - now, to - from);
3846
- }
3847
- else if (end > now) {
3848
- add(run(moving, now, end), 0, end - now);
4102
+ if (end > now) {
4103
+ let easing;
4104
+ if (tween && tween[1] > now) {
4105
+ const [from, to, ease] = tween;
4106
+ /**
4107
+ * Until it's built, the motion values hold where it
4108
+ * starts, for the renderer to write.
4109
+ */
4110
+ if (from - now > buildAhead) {
4111
+ moving.forEach((track) => track.sync());
4112
+ wakeIn((buildAt = from - now - buildAhead));
4113
+ return true;
4114
+ }
4115
+ easing =
4116
+ typeof ease === "string"
4117
+ ? ease
4118
+ : ease
4119
+ ? trace(ease, countSamples(from, to))
4120
+ : getEasing(moving, from, to, []);
4121
+ /**
4122
+ * It holds its last keyframe until the animations end.
4123
+ */
4124
+ easing &&
4125
+ add(run(moving, from, to, easing, {
4126
+ fill: "both",
4127
+ endDelay: end - to,
4128
+ }), from - now, end - from);
4129
+ }
4130
+ easing || add(run(moving, now, end), 0, end - now);
3849
4131
  /**
3850
4132
  * Animations that end sooner finish on the events of
3851
4133
  * empty animations that end with them.
@@ -3882,9 +4164,11 @@ function createGroup(owner) {
3882
4164
  /**
3883
4165
  * If every animation has been paused, played, seeked or sped up
3884
4166
  * together since the WAAPI animation was built, do the same to it.
3885
- * Returns false if it needs rebuilding instead.
4167
+ * Returns false if it needs rebuilding instead. Seeking to before a
4168
+ * tween starts rebuilds, so a running group seeked every frame still
4169
+ * moves to the main thread.
3886
4170
  */
3887
- const retime = (now) => {
4171
+ const retime = (now, isSeek) => {
3888
4172
  let elapsed;
3889
4173
  let rate = 0;
3890
4174
  for (const track of tracks) {
@@ -3894,9 +4178,14 @@ function createGroup(owner) {
3894
4178
  const [builtTime, builtSpeed, wasHeld] = state;
3895
4179
  const trackTime = track.at(now);
3896
4180
  const isHeld = track.timing()[0] === Infinity;
4181
+ /**
4182
+ * With nothing on the compositor, a held animation is set
4183
+ * where it's held, so it can be seeked as often as needed.
4184
+ */
3897
4185
  if (wasHeld) {
3898
- if (isHeld && trackTime === builtTime)
4186
+ if (isHeld && (trackTime === builtTime || !segments.length)) {
3899
4187
  continue;
4188
+ }
3900
4189
  return false;
3901
4190
  }
3902
4191
  const trackElapsed = (trackTime - builtTime) / builtSpeed;
@@ -3912,12 +4201,33 @@ function createGroup(owner) {
3912
4201
  }
3913
4202
  if (elapsed === undefined)
3914
4203
  return true;
3915
- if (!segments.length)
3916
- return false;
4204
+ /**
4205
+ * Waiting to build a tween that starts later. Until then the
4206
+ * values hold where they start, so only when to build changes.
4207
+ * Held, it has nothing on the compositor, so it can be seeked.
4208
+ */
4209
+ if (!segments.length) {
4210
+ if (buildAt === undefined || (isSeek && rate))
4211
+ return false;
4212
+ if (rate) {
4213
+ const delay = (buildAt - elapsed) / rate;
4214
+ if (delay < 1)
4215
+ return false;
4216
+ wakeIn(delay);
4217
+ }
4218
+ return true;
4219
+ }
4220
+ /**
4221
+ * Only a tween is built to start later, and it holds its first
4222
+ * keyframe until then, so it can be paused and played before it
4223
+ * starts.
4224
+ */
3917
4225
  for (const { offset, end, isDone } of segments) {
3918
4226
  const local = elapsed - offset;
3919
4227
  if (end < Infinity &&
3920
- (isDone ? local < end - 1 : local < 0 || local >= end)) {
4228
+ (isDone
4229
+ ? local < end - 1
4230
+ : (local < 0 && (isSeek || offset <= 0)) || local >= end)) {
3921
4231
  return false;
3922
4232
  }
3923
4233
  }
@@ -3938,7 +4248,8 @@ function createGroup(owner) {
3938
4248
  animation.updatePlaybackRate(rate);
3939
4249
  }
3940
4250
  else if (rate) {
3941
- animation.playbackRate = rate;
4251
+ animation.playbackRate !== rate &&
4252
+ (animation.playbackRate = rate);
3942
4253
  animation.startTime = now - local / rate;
3943
4254
  }
3944
4255
  else {
@@ -4012,12 +4323,12 @@ function createGroup(owner) {
4012
4323
  if (group.isJS) {
4013
4324
  group.isJS = false;
4014
4325
  needsBuild = true;
4015
- tracks.forEach((track) => track.js?.stop());
4326
+ tracks.forEach((track) => track.stopJS());
4016
4327
  }
4017
4328
  const shouldBuild = needsBuild;
4018
4329
  const churned = hasChurned;
4019
4330
  needsBuild = hasChurned = false;
4020
- if (shouldBuild || !retime(now)) {
4331
+ if (shouldBuild || !retime(now, churned)) {
4021
4332
  if (churned) {
4022
4333
  if (now - lastChurn < churnWindow)
4023
4334
  return group.demote();
@@ -4026,6 +4337,19 @@ function createGroup(owner) {
4026
4337
  if (!animate(now))
4027
4338
  return group.demote();
4028
4339
  }
4340
+ else if (buildAt !== undefined && !churned) {
4341
+ /**
4342
+ * Still waiting to build, so the values still hold where
4343
+ * they start.
4344
+ */
4345
+ return;
4346
+ }
4347
+ /**
4348
+ * Held animations don't move, so set their motion values to where
4349
+ * they're held, as a JSAnimation would on its next tick. Pausing
4350
+ * and seeking schedule this, so it's once however many there are.
4351
+ */
4352
+ tracks.forEach((track) => track.timing()[0] === Infinity && track.sync());
4029
4353
  };
4030
4354
  const group = {
4031
4355
  tracks,
@@ -4045,7 +4369,7 @@ function createGroup(owner) {
4045
4369
  isScheduled = true;
4046
4370
  frameData.isProcessing
4047
4371
  ? frame.render(build, false, true)
4048
- : queueMicrotask(build);
4372
+ : buildSoon(build);
4049
4373
  }
4050
4374
  },
4051
4375
  /**
@@ -4287,7 +4611,10 @@ class AsyncMotionValueAnimation extends WithPromise {
4287
4611
  class GroupAnimation {
4288
4612
  constructor(animations) {
4289
4613
  // Bound to accommodate common `return animation.stop` pattern
4290
- this.stop = () => this.runAll("stop");
4614
+ this.stop = () => {
4615
+ for (const animation of this.animations)
4616
+ animation.stop();
4617
+ };
4291
4618
  this.animations = animations.filter(Boolean);
4292
4619
  }
4293
4620
  get finished() {
@@ -4299,11 +4626,6 @@ class GroupAnimation {
4299
4626
  getAll(propName) {
4300
4627
  return this.animations[0][propName];
4301
4628
  }
4302
- setAll(propName, newValue) {
4303
- for (let i = 0; i < this.animations.length; i++) {
4304
- this.animations[i][propName] = newValue;
4305
- }
4306
- }
4307
4629
  attachTimeline(timeline) {
4308
4630
  const subscriptions = this.animations.map((animation) => animation.attachTimeline(timeline));
4309
4631
  return () => {
@@ -4316,14 +4638,21 @@ class GroupAnimation {
4316
4638
  get time() {
4317
4639
  return this.getAll("time");
4318
4640
  }
4641
+ /**
4642
+ * Setters and methods name the property directly, rather than through
4643
+ * a shared helper, so each call site stays monomorphic. Sequences
4644
+ * call these on every animation, many times a second.
4645
+ */
4319
4646
  set time(time) {
4320
- this.setAll("time", time);
4647
+ for (const animation of this.animations)
4648
+ animation.time = time;
4321
4649
  }
4322
4650
  get speed() {
4323
4651
  return this.getAll("speed");
4324
4652
  }
4325
4653
  set speed(speed) {
4326
- this.setAll("speed", speed);
4654
+ for (const animation of this.animations)
4655
+ animation.speed = speed;
4327
4656
  }
4328
4657
  get state() {
4329
4658
  return this.getAll("state");
@@ -4337,20 +4666,21 @@ class GroupAnimation {
4337
4666
  get iterationDuration() {
4338
4667
  return getMax(this.animations, "iterationDuration");
4339
4668
  }
4340
- runAll(methodName) {
4341
- this.animations.forEach((controls) => controls[methodName]());
4342
- }
4343
4669
  play() {
4344
- this.runAll("play");
4670
+ for (const animation of this.animations)
4671
+ animation.play();
4345
4672
  }
4346
4673
  pause() {
4347
- this.runAll("pause");
4674
+ for (const animation of this.animations)
4675
+ animation.pause();
4348
4676
  }
4349
4677
  cancel() {
4350
- this.runAll("cancel");
4678
+ for (const animation of this.animations)
4679
+ animation.cancel();
4351
4680
  }
4352
4681
  complete() {
4353
- this.runAll("complete");
4682
+ for (const animation of this.animations)
4683
+ animation.complete();
4354
4684
  }
4355
4685
  }
4356
4686
  function getMax(animations, propName) {
@@ -4710,28 +5040,32 @@ class MotionValue {
4710
5040
  * @param animation - A function that starts the provided animation
4711
5041
  */
4712
5042
  start(startAnimation) {
5043
+ return new Promise((resolve) => this.run(startAnimation, resolve));
5044
+ }
5045
+ /**
5046
+ * As start(), without making a promise, for animations started
5047
+ * internally, which complete through their own controls.
5048
+ */
5049
+ run(startAnimation, onComplete) {
4713
5050
  this.stop();
4714
- return new Promise((resolve) => {
4715
- this.hasAnimated = true;
4716
- /**
4717
- * Complete synchronously via the callback rather than chaining a
4718
- * second promise per animation. Guard against animations that
4719
- * complete before startAnimation has returned.
4720
- */
4721
- let isComplete = false;
4722
- let animation;
4723
- // eslint-disable-next-line prefer-const -- read by the callback before assignment when completing synchronously
4724
- animation = startAnimation(() => {
4725
- isComplete = true;
4726
- this.events.animationComplete?.notify();
4727
- if (this.animation === animation)
4728
- this.animation = undefined;
4729
- resolve();
4730
- });
4731
- if (!isComplete)
4732
- this.animation = animation;
4733
- this.events.animationStart?.notify();
5051
+ this.hasAnimated = true;
5052
+ /**
5053
+ * Guard against animations that complete before startAnimation
5054
+ * has returned.
5055
+ */
5056
+ let isComplete = false;
5057
+ let animation;
5058
+ // eslint-disable-next-line prefer-const -- read by the callback before assignment when completing synchronously
5059
+ animation = startAnimation(() => {
5060
+ isComplete = true;
5061
+ this.events.animationComplete?.notify();
5062
+ if (this.animation === animation)
5063
+ this.animation = undefined;
5064
+ onComplete?.();
4734
5065
  });
5066
+ if (!isComplete)
5067
+ this.animation = animation;
5068
+ this.events.animationStart?.notify();
4735
5069
  }
4736
5070
  /**
4737
5071
  * Stop the currently active animation.
@@ -5354,7 +5688,7 @@ function animateTarget(visualElement, targetAndTransition, { delay = 0, transiti
5354
5688
  }
5355
5689
  addValueToWillChange(visualElement, key);
5356
5690
  const shouldReduceMotion = reduceMotion ?? visualElement.shouldReduceMotion;
5357
- value.start(animateMotionValue(key, value, valueTarget, shouldReduceMotion && positionalKeys.has(key)
5691
+ value.run(animateMotionValue(key, value, valueTarget, shouldReduceMotion && positionalKeys.has(key)
5358
5692
  ? { type: false }
5359
5693
  : valueTransition, visualElement, isHandoff));
5360
5694
  const animation = value.animation;
@@ -5489,9 +5823,14 @@ function makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, n
5489
5823
  }
5490
5824
 
5491
5825
  class DOMKeyframesResolver extends KeyframeResolver {
5492
- constructor() {
5493
- super(...arguments);
5494
- this.isAsync = true;
5826
+ /**
5827
+ * Passes isAsync to the base constructor rather than setting it as a
5828
+ * class field, which would compile to a constructor that spreads
5829
+ * `arguments` into super(). That spread is slow in the interpreter,
5830
+ * and animate() constructs one resolver per value.
5831
+ */
5832
+ constructor(unresolvedKeyframes, onComplete, name, motionValue, element) {
5833
+ super(unresolvedKeyframes, onComplete, name, motionValue, element, true);
5495
5834
  }
5496
5835
  /**
5497
5836
  * Keyframes that don't need reading from the DOM, or measuring,
@@ -5791,7 +6130,7 @@ function animateValues(getValue, keyframes, transition = {}, element) {
5791
6130
  frame.update(() => value.set(target));
5792
6131
  continue;
5793
6132
  }
5794
- value.start(animateMotionValue(key, value, target, reduceMotion && positionalKeys.has(key)
6133
+ value.run(animateMotionValue(key, value, target, reduceMotion && positionalKeys.has(key)
5795
6134
  ? { type: false }
5796
6135
  : transition, element));
5797
6136
  value.animation &&
@@ -5821,8 +6160,14 @@ function animateValues(getValue, keyframes, transition = {}, element) {
5821
6160
  * measurement) via `element`.
5822
6161
  */
5823
6162
  function animateEffectSubject(effect, subject, keyframes, transition, element) {
5824
- return animateValues((key) => {
5825
- let value = effect.get(subject, key);
6163
+ /**
6164
+ * Values made for this call are bound with one effect call, after the
6165
+ * loop, rather than one each.
6166
+ */
6167
+ let created;
6168
+ let isBound = false;
6169
+ const animations = animateValues((key) => {
6170
+ let value = created?.[key] ?? effect.get(subject, key);
5826
6171
  if (!value) {
5827
6172
  let initial;
5828
6173
  if (!element) {
@@ -5834,10 +6179,15 @@ function animateEffectSubject(effect, subject, keyframes, transition, element) {
5834
6179
  motionUtils.invariant(initial !== undefined, `"${key}" can't be read from the animated subject. Provide [from, to] keyframes.`, "effect-unreadable-value");
5835
6180
  }
5836
6181
  value = motionValue(initial, { owner: element });
5837
- effect(subject, { [key]: value });
6182
+ isBound
6183
+ ? effect(subject, { [key]: value })
6184
+ : ((created || (created = {}))[key] = value);
5838
6185
  }
5839
6186
  return value;
5840
6187
  }, keyframes, transition, element);
6188
+ isBound = true;
6189
+ created && effect(subject, created);
6190
+ return animations;
5841
6191
  }
5842
6192
  function firstKeyframe(target) {
5843
6193
  const first = Array.isArray(target) ? target[0] : undefined;
@@ -6833,7 +7183,7 @@ const processFrame = (timestamp = time.now()) => {
6833
7183
 
6834
7184
  function animateSingleValue(value, keyframes, options) {
6835
7185
  const motionValue$1 = isMotionValue(value) ? value : motionValue(value);
6836
- motionValue$1.start(animateMotionValue("", motionValue$1, keyframes, options));
7186
+ motionValue$1.run(animateMotionValue("", motionValue$1, keyframes, options));
6837
7187
  return motionValue$1.animation;
6838
7188
  }
6839
7189
 
@@ -7340,13 +7690,7 @@ function buildProjectionTransform(delta, treeScale, latestTransform) {
7340
7690
  if (xTranslate || yTranslate || zTranslate) {
7341
7691
  transform = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `;
7342
7692
  }
7343
- /**
7344
- * Apply scale correction for the tree transform.
7345
- * This will apply scale to the screen-orientated axes.
7346
- */
7347
- if (treeScale.x !== 1 || treeScale.y !== 1) {
7348
- transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
7349
- }
7693
+ let angles = "";
7350
7694
  if (latestTransform) {
7351
7695
  const { transformPerspective } = latestTransform;
7352
7696
  if (transformPerspective)
@@ -7355,20 +7699,48 @@ function buildProjectionTransform(delta, treeScale, latestTransform) {
7355
7699
  const key = angleTransforms[i];
7356
7700
  const value = latestTransform[key];
7357
7701
  if (value)
7358
- transform += `${key}(${value}deg) `;
7702
+ angles += `${key}(${value}deg) `;
7359
7703
  // Additive `rotate()` so user `rotate` isn't clobbered.
7360
7704
  if (!i && latestTransform.pathRotation)
7361
- transform += `rotate(${latestTransform.pathRotation}deg) `;
7705
+ angles += `rotate(${latestTransform.pathRotation}deg) `;
7362
7706
  }
7363
7707
  }
7364
- /**
7365
- * Apply scale to match the size of the element to the size we want it.
7366
- * This will apply scale to the element-orientated axes.
7367
- */
7368
- const elementScaleX = delta.x.scale * treeScale.x;
7369
- const elementScaleY = delta.y.scale * treeScale.y;
7370
- if (elementScaleX !== 1 || elementScaleY !== 1) {
7371
- transform += `scale(${elementScaleX}, ${elementScaleY})`;
7708
+ if (angles) {
7709
+ /**
7710
+ * Apply scale correction for the tree transform.
7711
+ * This will apply scale to the screen-orientated axes.
7712
+ */
7713
+ if (treeScale.x !== 1 || treeScale.y !== 1) {
7714
+ transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
7715
+ }
7716
+ transform += angles;
7717
+ /**
7718
+ * Apply scale to match the size of the element to the size we want it.
7719
+ * This will apply scale to the element-orientated axes.
7720
+ */
7721
+ const elementScaleX = delta.x.scale * treeScale.x;
7722
+ const elementScaleY = delta.y.scale * treeScale.y;
7723
+ if (elementScaleX !== 1 || elementScaleY !== 1) {
7724
+ transform += `scale(${elementScaleX}, ${elementScaleY})`;
7725
+ }
7726
+ }
7727
+ else if (delta.x.scale !== 1 || delta.y.scale !== 1) {
7728
+ /**
7729
+ * With no rotation or skew between them, the tree scale correction
7730
+ * (1 / treeScale) and the element scale (delta.scale * treeScale)
7731
+ * combine into a single scale. A shorter transform is quicker for
7732
+ * the browser to parse, which matters when it's set every frame.
7733
+ */
7734
+ transform += `scale(${delta.x.scale}, ${delta.y.scale})`;
7735
+ }
7736
+ else if (!transform && (treeScale.x !== 1 || treeScale.y !== 1)) {
7737
+ /**
7738
+ * Inside a scaled tree the transform must never be "none", even when
7739
+ * this element's own delta is the identity: scale correction for
7740
+ * borderRadius and boxShadow is skipped for "none", and the element
7741
+ * would gain and lose its stacking context as the delta snaps.
7742
+ */
7743
+ transform = "scale(1, 1)";
7372
7744
  }
7373
7745
  return transform || "none";
7374
7746
  }
@@ -10578,7 +10950,7 @@ function distance2D(a, b) {
10578
10950
 
10579
10951
  const overflowStyles = /*#__PURE__*/ new Set(["auto", "scroll"]);
10580
10952
  class PanSession {
10581
- constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, element, } = {}) {
10953
+ constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, element, immediate, } = {}) {
10582
10954
  this.startEvent = null;
10583
10955
  this.lastMoveEvent = null;
10584
10956
  this.lastMoveEventInfo = null;
@@ -10664,7 +11036,7 @@ class PanSession {
10664
11036
  this.dragSnapToOrigin = dragSnapToOrigin;
10665
11037
  this.handlers = handlers;
10666
11038
  this.transformPagePoint = transformPagePoint;
10667
- this.distanceThreshold = distanceThreshold;
11039
+ this.distanceThreshold = immediate ? 0 : distanceThreshold;
10668
11040
  this.contextWindow = contextWindow || window;
10669
11041
  const info = extractEventInfo(event);
10670
11042
  const initialInfo = transformPoint(info, this.transformPagePoint);
@@ -10688,6 +11060,10 @@ class PanSession {
10688
11060
  if (element) {
10689
11061
  this.startScrollTracking(element);
10690
11062
  }
11063
+ if (immediate) {
11064
+ this.handlePointerMove(event, info);
11065
+ this.updatePoint();
11066
+ }
10691
11067
  }
10692
11068
  /**
10693
11069
  * Start tracking scroll on ancestors and window.
@@ -11063,14 +11439,14 @@ class VisualElementDragControls {
11063
11439
  this.visualElement = visualElement;
11064
11440
  this.readProps = readProps;
11065
11441
  }
11066
- start(originEvent, { snapToCursor = false, distanceThreshold } = {}) {
11442
+ start(originEvent, options = {}) {
11067
11443
  /**
11068
11444
  * Don't start dragging if this component is exiting
11069
11445
  */
11070
11446
  if (this.visualElement.presenceContext?.isPresent === false)
11071
11447
  return;
11072
11448
  const onSessionStart = (event) => {
11073
- if (snapToCursor)
11449
+ if (options.snapToCursor)
11074
11450
  this.snapToCursor(event);
11075
11451
  this.stopAnimation();
11076
11452
  };
@@ -11192,9 +11568,9 @@ class VisualElementDragControls {
11192
11568
  onSessionEnd,
11193
11569
  resumeAnimation,
11194
11570
  }, {
11571
+ ...options,
11195
11572
  transformPagePoint: this.visualElement.getTransformPagePoint(),
11196
11573
  dragSnapToOrigin,
11197
- distanceThreshold,
11198
11574
  contextWindow: this.visualElement.current?.ownerDocument.defaultView,
11199
11575
  element: this.visualElement.current,
11200
11576
  });
@@ -11643,8 +12019,10 @@ function expectsResolvedDragConstraints({ dragConstraints, onMeasureDragConstrai
11643
12019
  return isElementConstraints(dragConstraints) && !!onMeasureDragConstraints;
11644
12020
  }
11645
12021
 
11646
- const toProps = ({ axis, constraints, elastic, momentum, transition, snapToOrigin, directionLock, propagation, onStart, onMove, onEnd, onDirectionLock, onTransitionEnd, onMeasureConstraints, }) => ({
12022
+ const toProps = ({ axis, constraints, elastic, momentum, transition, snapToOrigin, directionLock, propagation, onStart, onMove, onEnd, onDirectionLock, onTransitionEnd, onMeasureConstraints, x, y, }) => ({
11647
12023
  drag: axis || true,
12024
+ _dragX: x || (y && motionValue(0)),
12025
+ _dragY: y || (x && motionValue(0)),
11648
12026
  dragConstraints: constraints,
11649
12027
  dragElastic: elastic,
11650
12028
  dragMomentum: momentum,
@@ -11853,7 +12231,7 @@ const enableKeyboardPress = (element, eventOptions) => {
11853
12231
  */
11854
12232
  let isKeyPressing = false;
11855
12233
  const handleKeydown = filterEvents(() => {
11856
- if (isPressing.has(element))
12234
+ if (isKeyPressing || isPressing.has(element))
11857
12235
  return;
11858
12236
  isKeyPressing = true;
11859
12237
  firePointerEvent(element, "down");
@@ -11885,6 +12263,18 @@ function isValidPressEvent(event) {
11885
12263
  return isPrimaryPointer(event) && !isDragActive();
11886
12264
  }
11887
12265
  const claimedPointerDownEvents = new WeakSet();
12266
+ /**
12267
+ * Max distance in px between consecutive presses of a `count` sequence.
12268
+ * Android's `ViewConfiguration` double tap slop is 100dp.
12269
+ */
12270
+ const sequenceSlop = 100;
12271
+ /**
12272
+ * Max distance in px a pointer can move during a held press (`hold`
12273
+ * pending, or `repeat`). Android's `ViewConfiguration` touch slop is 8dp.
12274
+ */
12275
+ const holdSlop = 8;
12276
+ const exceeds = (a, b, max) => Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY) > max;
12277
+ const preventDefault = (event) => event.preventDefault();
11888
12278
  /**
11889
12279
  * Create a press gesture.
11890
12280
  *
@@ -11902,22 +12292,110 @@ const claimedPointerDownEvents = new WeakSet();
11902
12292
  * to be focusable for this to work, whereas a press gesture will
11903
12293
  * make an element focusable by default.
11904
12294
  *
12295
+ * `onPressStart` fires on the first pointer or key down, and can return
12296
+ * a function to call when the press ends, or an object of handlers for
12297
+ * this press:
12298
+ *
12299
+ * ```js
12300
+ * press(button, () => ({
12301
+ * onHold: (progress) => {},
12302
+ * onComplete: (event, { success }) => {},
12303
+ * }), { hold: 0.5 })
12304
+ * ```
12305
+ *
11905
12306
  * @public
11906
12307
  */
11907
12308
  function press(targetOrSelector, onPressStart, options = {}) {
11908
12309
  onPressStart = bindToScope(onPressStart);
11909
12310
  const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);
12311
+ const sequences = new WeakMap();
11910
12312
  const startPress = (startEvent) => {
11911
12313
  const target = startEvent.currentTarget;
11912
12314
  if (!isValidPressEvent(startEvent))
11913
12315
  return;
11914
12316
  if (claimedPointerDownEvents.has(startEvent))
11915
12317
  return;
11916
- isPressing.add(target);
11917
12318
  if (options.stopPropagation) {
11918
12319
  claimedPointerDownEvents.add(startEvent);
11919
12320
  }
11920
- const onPressEnd = onPressStart(target, startEvent);
12321
+ /**
12322
+ * Options are read per press so they can be updated between presses.
12323
+ */
12324
+ const { count: presses = 1, countTimeout = 0.3, hold = 0, repeat, } = options;
12325
+ const downTime = time.now();
12326
+ const holdTime = motionUtils.secondsToMilliseconds(hold);
12327
+ const timeout = motionUtils.secondsToMilliseconds(countTimeout);
12328
+ let previous = sequences.get(target);
12329
+ /**
12330
+ * A press during a `count` sequence continues it. If it's too late
12331
+ * or too far away, the sequence is cancelled and this press starts
12332
+ * a new one.
12333
+ */
12334
+ if (previous?.expire(exceeds(previous.event, startEvent, sequenceSlop))) {
12335
+ previous = undefined;
12336
+ }
12337
+ else if (previous) {
12338
+ cancelFrame(previous.expire);
12339
+ sequences.delete(target);
12340
+ }
12341
+ const count = previous ? previous.count + 1 : 1;
12342
+ const isFinal = count >= presses;
12343
+ const isHeld = isFinal && (hold || repeat);
12344
+ let isActive = !hold;
12345
+ let repeats = 0;
12346
+ let handlers;
12347
+ isPressing.add(target);
12348
+ if (previous) {
12349
+ handlers = previous.handlers;
12350
+ }
12351
+ else {
12352
+ const result = onPressStart(target, startEvent);
12353
+ handlers =
12354
+ typeof result === "function"
12355
+ ? { onComplete: result }
12356
+ : result || {};
12357
+ }
12358
+ isFinal && isActive && handlers.onActive?.();
12359
+ /**
12360
+ * While held, `onHold` reports progress from 0 to 1 over `hold`,
12361
+ * then over each `repeat`. Each cycle reports exactly 1 at its end,
12362
+ * then 0 on the next frame.
12363
+ */
12364
+ const repeatTime = motionUtils.secondsToMilliseconds(repeat);
12365
+ let length = holdTime || repeatTime;
12366
+ let cycleEnd = downTime + length;
12367
+ let isCycleStart = true;
12368
+ const tick = () => {
12369
+ if (eventOptions.signal.aborted)
12370
+ return cancelFrame(tick);
12371
+ let progress = Math.min(1 - (cycleEnd - time.now()) / length, 1);
12372
+ /**
12373
+ * The frame after a boundary reports 0, so each cycle visibly
12374
+ * restarts. Boundaries are timed from `downTime`, so this
12375
+ * doesn't delay the next one. If a long frame has already
12376
+ * passed the next boundary, it reports 1 instead.
12377
+ */
12378
+ if (isCycleStart && progress < 1)
12379
+ progress = 0;
12380
+ isCycleStart = false;
12381
+ handlers.onHold?.(progress);
12382
+ if (progress < 1)
12383
+ return;
12384
+ if (isActive) {
12385
+ handlers.onRepeat?.(++repeats);
12386
+ }
12387
+ else {
12388
+ isActive = true;
12389
+ handlers.onActive?.();
12390
+ }
12391
+ if (repeat) {
12392
+ isCycleStart = true;
12393
+ cycleEnd += length = repeatTime;
12394
+ }
12395
+ else {
12396
+ cancelFrame(tick);
12397
+ }
12398
+ };
11921
12399
  /**
11922
12400
  * End listeners run in the capture phase so a descendant calling
11923
12401
  * stopPropagation() in its own pointerup handler can't prevent the
@@ -11928,14 +12406,55 @@ function press(targetOrSelector, onPressStart, options = {}) {
11928
12406
  const onPointerEnd = (endEvent, success) => {
11929
12407
  window.removeEventListener("pointerup", onPointerUp, endEventOptions);
11930
12408
  window.removeEventListener("pointercancel", onPointerCancel, endEventOptions);
11931
- if (isPressing.has(target)) {
11932
- isPressing.delete(target);
11933
- }
11934
- if (!isValidPressEvent(endEvent)) {
12409
+ window.removeEventListener("pointermove", onPointerMove, endEventOptions);
12410
+ target.removeEventListener("contextmenu", preventDefault);
12411
+ cancelFrame(tick);
12412
+ isPressing.delete(target);
12413
+ if (!isPrimaryPointer(endEvent))
11935
12414
  return;
12415
+ /**
12416
+ * A press that ends while a drag is active is a cancel.
12417
+ */
12418
+ if (isDragActive())
12419
+ success = false;
12420
+ if (success && !isFinal) {
12421
+ /**
12422
+ * Wait for the next press of the sequence, and cancel the
12423
+ * gesture if it doesn't arrive in time.
12424
+ */
12425
+ const end = time.now();
12426
+ /**
12427
+ * Cancels the sequence if it's `force`d, or the interval
12428
+ * has passed. Runs every frame, where `force` is frame
12429
+ * data, so it's checked with `=== true`.
12430
+ */
12431
+ const expire = (force) => {
12432
+ const isAborted = eventOptions.signal.aborted;
12433
+ if (isAborted ||
12434
+ force === true ||
12435
+ time.now() - end > timeout) {
12436
+ cancelFrame(expire);
12437
+ sequences.delete(target);
12438
+ isAborted ||
12439
+ handlers.onComplete?.(endEvent, { success: false });
12440
+ return true;
12441
+ }
12442
+ };
12443
+ sequences.set(target, {
12444
+ count,
12445
+ event: startEvent,
12446
+ handlers,
12447
+ expire,
12448
+ });
12449
+ frame.update(expire, true);
11936
12450
  }
11937
- if (typeof onPressEnd === "function") {
11938
- onPressEnd(endEvent, { success });
12451
+ else {
12452
+ /**
12453
+ * Releasing before `hold` is reached is a cancel.
12454
+ */
12455
+ handlers.onComplete?.(endEvent, {
12456
+ success: success && isActive,
12457
+ });
11939
12458
  }
11940
12459
  };
11941
12460
  const onPointerUp = (upEvent) => {
@@ -11947,8 +12466,35 @@ function press(targetOrSelector, onPressStart, options = {}) {
11947
12466
  const onPointerCancel = (cancelEvent) => {
11948
12467
  onPointerEnd(cancelEvent, false);
11949
12468
  };
12469
+ /**
12470
+ * Moving during a pending long press, or a repeating press, cancels
12471
+ * it, so scrolling on touch devices doesn't trigger it. A drag
12472
+ * starting during a `count` sequence cancels it.
12473
+ */
12474
+ const onPointerMove = (moveEvent) => {
12475
+ if (isPrimaryPointer(moveEvent) &&
12476
+ (((repeat || !isActive) &&
12477
+ exceeds(startEvent, moveEvent, holdSlop)) ||
12478
+ (presses > 1 && isDragActive()))) {
12479
+ onPointerCancel(moveEvent);
12480
+ }
12481
+ };
11950
12482
  window.addEventListener("pointerup", onPointerUp, endEventOptions);
11951
12483
  window.addEventListener("pointercancel", onPointerCancel, endEventOptions);
12484
+ if (isHeld || presses > 1) {
12485
+ window.addEventListener("pointermove", onPointerMove, endEventOptions);
12486
+ }
12487
+ if (isHeld) {
12488
+ frame.update(tick, true);
12489
+ /**
12490
+ * Touch devices open a context menu or callout on long press,
12491
+ * which would cancel the gesture.
12492
+ */
12493
+ target.addEventListener("contextmenu", preventDefault, {
12494
+ ...eventOptions,
12495
+ passive: false,
12496
+ });
12497
+ }
11952
12498
  };
11953
12499
  targets.forEach((target) => {
11954
12500
  const pointerDownTarget = options.useGlobalTarget ? window : target;