motion 14.10.0 → 14.11.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.
@@ -1732,25 +1732,53 @@
1732
1732
  value: keyframeValues[0],
1733
1733
  };
1734
1734
  /**
1735
- * Fast setup path for two keyframes one easing. interpolate() handles
1736
- * a custom mixer, and falls back to the usual one where it declines.
1735
+ * Two keyframes, or keyframes that hold, move once, then hold, as each
1736
+ * value of a sequence does, ease and mix only the pair that moves.
1737
1737
  */
1738
- if (!customMixer &&
1739
- keyframeValues.length === 2 &&
1740
- !Array.isArray(easingFunctions) &&
1741
- (!times ||
1742
- times.length !== 2 ||
1743
- (times[0] === 0 && times[1] === 1))) {
1744
- const [origin, target] = keyframeValues;
1745
- const mixer = origin === target
1746
- ? undefined
1747
- : (MotionGlobalConfig.mix || mix)(origin, target);
1738
+ let span = -1;
1739
+ if (!customMixer) {
1740
+ for (let i = 1; i < keyframeValues.length; i++) {
1741
+ if (keyframeValues[i] !== keyframeValues[i - 1]) {
1742
+ if (span >= 0) {
1743
+ span = -2;
1744
+ break;
1745
+ }
1746
+ span = i - 1;
1747
+ }
1748
+ }
1749
+ }
1750
+ if (span >= 0) {
1751
+ const offsets = times && times.length === keyframeValues.length
1752
+ ? times
1753
+ : defaultOffset$1(keyframeValues);
1754
+ const from = offsets[span] * duration;
1755
+ const to = offsets[span + 1] * duration;
1756
+ const origin = keyframeValues[span];
1757
+ const target = keyframeValues[span + 1];
1758
+ const ease = Array.isArray(easingFunctions)
1759
+ ? easingFunctions[span]
1760
+ : easingFunctions;
1761
+ const mixer = (MotionGlobalConfig.mix || mix)(origin, target);
1762
+ const last = keyframeValues.length - 2;
1748
1763
  return {
1749
1764
  calculatedDuration: duration,
1750
1765
  next: (t) => {
1751
- state.value = mixer
1752
- ? mixer(easingFunctions(duration > 0 ? clamp(0, 1, t / duration) : 1))
1753
- : target;
1766
+ /**
1767
+ * Held keyframes either side of the move are mixed as
1768
+ * interpolate() mixes them, so colours keep its format.
1769
+ */
1770
+ state.value =
1771
+ span && t < from
1772
+ ? mixer(0)
1773
+ : span < last && (t >= to || !duration)
1774
+ ? typeof target === "number"
1775
+ ? target
1776
+ : mixer(1)
1777
+ : mixer(ease(t >= to || !duration
1778
+ ? 1
1779
+ : t <= from
1780
+ ? 0
1781
+ : (t - from) / (to - from)));
1754
1782
  state.done = t >= duration;
1755
1783
  return state;
1756
1784
  },
@@ -1799,13 +1827,27 @@
1799
1827
  : getGeneratorVelocity((s) => generator.next(s).value, t, generator.next(t).value);
1800
1828
  }
1801
1829
 
1802
- const isNotNull = (value) => value !== null;
1803
1830
  function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe, speed = 1) {
1804
- const resolvedKeyframes = keyframes.filter(isNotNull);
1831
+ /**
1832
+ * The first and last keyframes that aren't null, and how many there
1833
+ * are. Found in one pass rather than filtering into a new array, as
1834
+ * this runs for every value of every animation.
1835
+ */
1836
+ let first;
1837
+ let last;
1838
+ let numResolved = 0;
1839
+ for (let i = 0; i < keyframes.length; i++) {
1840
+ const keyframe = keyframes[i];
1841
+ if (keyframe !== null) {
1842
+ if (!numResolved++)
1843
+ first = keyframe;
1844
+ last = keyframe;
1845
+ }
1846
+ }
1805
1847
  const useFirstKeyframe = speed < 0 || (repeat && repeatType !== "loop" && repeat % 2 === 1);
1806
- const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1;
1848
+ const index = useFirstKeyframe ? 0 : numResolved - 1;
1807
1849
  return !index || finalKeyframe === undefined
1808
- ? resolvedKeyframes[index]
1850
+ ? (index ? last : first)
1809
1851
  : finalKeyframe;
1810
1852
  }
1811
1853
 
@@ -2484,14 +2526,26 @@
2484
2526
  const getDefaultValueType = (key) => defaultValueTypes[key];
2485
2527
 
2486
2528
  const customTypes = /*@__PURE__*/ new Set([filter, mask]);
2529
+ /**
2530
+ * The last call and its result. animate() on many elements asks for the
2531
+ * same none for each one, and parsing the value is the slow part.
2532
+ */
2533
+ let lastKey;
2534
+ let lastValue;
2535
+ let lastNone;
2487
2536
  function getAnimatableNone(key, value) {
2537
+ if (key === lastKey && value === lastValue)
2538
+ return lastNone;
2488
2539
  let defaultValueType = getDefaultValueType(key);
2489
2540
  if (!customTypes.has(defaultValueType))
2490
2541
  defaultValueType = complex;
2491
2542
  // If value is not recognised as animatable, ie "none", create an animatable version origin based on the target
2492
- return defaultValueType.getAnimatableNone
2543
+ lastNone = defaultValueType.getAnimatableNone
2493
2544
  ? defaultValueType.getAnimatableNone(value)
2494
2545
  : undefined;
2546
+ lastKey = key;
2547
+ lastValue = value;
2548
+ return lastNone;
2495
2549
  }
2496
2550
 
2497
2551
  function fillWildcards(keyframes) {
@@ -3526,7 +3580,8 @@
3526
3580
  /**
3527
3581
  * Named easings that are the same cubic-bezier in JS and CSS.
3528
3582
  */
3529
- const isNativeEasing = (ease) => /^(linear|ease(In|Out|InOut))$/.test(ease);
3583
+ const nativeEasings = new Set(["linear", "easeIn", "easeOut", "easeInOut"]);
3584
+ const isNativeEasing = (ease) => nativeEasings.has(ease);
3530
3585
  /**
3531
3586
  * The last trace of each easing WAAPI can't run into linear(), with its
3532
3587
  * number of samples, so the elements of a sequence that share an easing
@@ -3610,6 +3665,54 @@
3610
3665
  */
3611
3666
  !needsMixer(options));
3612
3667
  }
3668
+ /**
3669
+ * Starting or stopping tells the group to update its WAAPI animation.
3670
+ * The frame loop driver is only made once the group is on the main
3671
+ * thread, as accelerated animations never tick.
3672
+ */
3673
+ class TransformDriver {
3674
+ constructor(element, update, makeDriver, animation) {
3675
+ this.element = element;
3676
+ this.update = update;
3677
+ this.makeDriver = makeDriver;
3678
+ this.animation = animation;
3679
+ }
3680
+ get js() {
3681
+ return (this.driver || (this.driver = this.makeDriver(this.update)));
3682
+ }
3683
+ now() {
3684
+ return this.driver || this.makeDriver !== frameloopDriver
3685
+ ? this.js.now()
3686
+ : frameData.isProcessing
3687
+ ? frameData.timestamp
3688
+ : time.now();
3689
+ }
3690
+ /**
3691
+ * keepAlive is false when seeking. Seeking the WAAPI animation is
3692
+ * free, but if a seek needs a rebuild and keeps happening, the group
3693
+ * moves to the main thread.
3694
+ */
3695
+ start(keepAlive = true) {
3696
+ const group = getGroup(this.element);
3697
+ !group || group.isJS
3698
+ ? this.js.start(keepAlive)
3699
+ : group.schedule(false, !keepAlive);
3700
+ }
3701
+ stopJS() {
3702
+ this.driver?.stop();
3703
+ }
3704
+ stop() {
3705
+ this.stopJS();
3706
+ const group = getGroup(this.element);
3707
+ group && !group.isFinishing && group.release(this.animation);
3708
+ }
3709
+ }
3710
+ /**
3711
+ * JSAnimation's time setter, looked up on first use rather than at module
3712
+ * load, so the module has no top-level side effects and stays
3713
+ * tree-shakeable in flattened bundles.
3714
+ */
3715
+ let setTime;
3613
3716
  class TransformAnimation extends JSAnimation {
3614
3717
  constructor(options) {
3615
3718
  const element = getOwner(options).current;
@@ -3621,35 +3724,16 @@
3621
3724
  const canAccelerate = canAccelerateTransform(options);
3622
3725
  /**
3623
3726
  * The driver ticks on the main thread only once the group has
3624
- * moved there. Until then, starting or stopping tells the group to
3625
- * update its WAAPI animation.
3727
+ * moved there, so its frame loop driver is made then.
3626
3728
  */
3627
- options.driver = (update) => {
3628
- const js = driver(update);
3629
- return {
3630
- js,
3631
- now: js.now,
3632
- start: (keepAlive = true) => {
3633
- const group = getGroup(element);
3634
- const isJS = !group || group.isJS;
3635
- /**
3636
- * keepAlive is false when seeking. Seeking the WAAPI
3637
- * animation is free, but if a seek needs a rebuild and
3638
- * keeps happening, the group moves to the main thread.
3639
- */
3640
- isJS
3641
- ? js.start(keepAlive)
3642
- : group.schedule(false, !keepAlive);
3643
- },
3644
- stop: () => {
3645
- js.stop();
3646
- const group = getGroup(element);
3647
- group && !group.isFinishing && group.release(animation);
3648
- },
3649
- };
3650
- };
3729
+ options.driver = (update) => new TransformDriver(element, update, driver, animation);
3651
3730
  super(options);
3652
3731
  animation = this;
3732
+ /**
3733
+ * The first driver is made in super(), before this was assigned.
3734
+ */
3735
+ const firstDriver = this.driver;
3736
+ firstDriver && (firstDriver.animation = this);
3653
3737
  this.canAccelerate = canAccelerate;
3654
3738
  /**
3655
3739
  * stop is bound in JSAnimation, so wrap it rather than override.
@@ -3663,12 +3747,29 @@
3663
3747
  stop();
3664
3748
  };
3665
3749
  }
3750
+ /**
3751
+ * Each keyframe's offset, made once for the keyframes rather than on
3752
+ * every build.
3753
+ */
3754
+ offsets() {
3755
+ const { keyframes, times } = this.options;
3756
+ if (times)
3757
+ return times;
3758
+ if (this.offsetsOf !== keyframes) {
3759
+ this.offsetsOf = keyframes;
3760
+ this.cachedOffsets = defaultOffset$1(keyframes);
3761
+ }
3762
+ return this.cachedOffsets;
3763
+ }
3666
3764
  get group() {
3667
3765
  return getGroup(getOwner(this.options).current);
3668
3766
  }
3669
3767
  get js() {
3670
3768
  return this.driver?.js;
3671
3769
  }
3770
+ stopJS() {
3771
+ this.driver?.stopJS();
3772
+ }
3672
3773
  get name() {
3673
3774
  return this.options.name;
3674
3775
  }
@@ -3714,7 +3815,7 @@
3714
3815
  * exactly, otherwise its function, to trace.
3715
3816
  */
3716
3817
  tween() {
3717
- const { keyframes: keyframes$1, type, times, repeat, delay = 0 } = this.options;
3818
+ const { keyframes: keyframes$1, type, repeat, delay = 0 } = this.options;
3718
3819
  let span = -1;
3719
3820
  if (repeat || type !== keyframes || this.holdTime !== null) {
3720
3821
  return;
@@ -3729,7 +3830,7 @@
3729
3830
  let { ease } = this.options;
3730
3831
  if (isEasingArray(ease))
3731
3832
  ease = ease[span];
3732
- const offsets = times || defaultOffset$1(keyframes$1);
3833
+ const offsets = this.offsets();
3733
3834
  const at = (i) => this.startTime +
3734
3835
  (delay + offsets[i] * this.totalDuration) / this.speed;
3735
3836
  if (span >= 0) {
@@ -3758,9 +3859,9 @@
3758
3859
  */
3759
3860
  boundaries(from, to) {
3760
3861
  const { startTime, speed, resolvedDuration, options } = this;
3761
- const { delay = 0, repeat = 0, repeatDelay = 0, repeatType, times, keyframes: keyframes$1, type, } = options;
3862
+ const { delay = 0, repeat = 0, repeatDelay = 0, repeatType, type, } = options;
3762
3863
  const offsets = (type || keyframes) === keyframes
3763
- ? times || defaultOffset$1(keyframes$1)
3864
+ ? this.offsets()
3764
3865
  : [0, 1];
3765
3866
  const start = startTime + delay / speed;
3766
3867
  const result = [];
@@ -3837,8 +3938,12 @@
3837
3938
  }
3838
3939
  return super.time;
3839
3940
  }
3941
+ /**
3942
+ * Calls JSAnimation's setter directly, as `super.time =` is a slow
3943
+ * path in V8 and this runs for every animation of a seeked sequence.
3944
+ */
3840
3945
  set time(newTime) {
3841
- super.time = newTime;
3946
+ (setTime ?? (setTime = Object.getOwnPropertyDescriptor(JSAnimation.prototype, "time").set)).call(this, newTime);
3842
3947
  }
3843
3948
  /**
3844
3949
  * Scroll timelines set time every frame, so run these on the main
@@ -3884,6 +3989,12 @@
3884
3989
  let hasChurned = false;
3885
3990
  let lastChurn = -Infinity;
3886
3991
  let wake;
3992
+ let wakeAt = Infinity;
3993
+ /**
3994
+ * While waiting to build a tween that starts later, how long after
3995
+ * the last build to build it.
3996
+ */
3997
+ let buildAt;
3887
3998
  const has = (key) => {
3888
3999
  for (const track of tracks)
3889
4000
  if (track.name === key)
@@ -3952,6 +4063,8 @@
3952
4063
  */
3953
4064
  const stop = (shouldCommit = true) => {
3954
4065
  clearTimeout(wake);
4066
+ wakeAt = Infinity;
4067
+ buildAt = undefined;
3955
4068
  shouldCommit && commit();
3956
4069
  segments.forEach(({ animation }) => cancel(animation));
3957
4070
  segments = [];
@@ -4181,7 +4294,13 @@
4181
4294
  * A WAAPI animation of the composed transform between two timestamps.
4182
4295
  */
4183
4296
  const run = (moving, from, to, nativeEasing, options = { fill: "both" }, settled) => {
4184
- const bounds = moving.flatMap((track) => track.boundaries(from, to));
4297
+ /**
4298
+ * With an easing given, there's nothing to sample, so no need
4299
+ * for the boundaries.
4300
+ */
4301
+ const bounds = nativeEasing
4302
+ ? []
4303
+ : moving.flatMap((track) => track.boundaries(from, to));
4185
4304
  const easing = nativeEasing || getEasing(moving, from, to, bounds);
4186
4305
  const times = easing ? [from, to] : sample(moving, from, to, bounds);
4187
4306
  const transform = times.map((t) => compose(t, settled));
@@ -4204,6 +4323,23 @@
4204
4323
  easing: easing || "linear",
4205
4324
  });
4206
4325
  };
4326
+ /**
4327
+ * Check whether it's time to build in this long. A check that's due
4328
+ * sooner is kept, and checks again if it's early, so pausing and
4329
+ * playing don't each replace a timer. One due later, after a seek or
4330
+ * speed change while held, is replaced.
4331
+ */
4332
+ const wakeIn = (delay) => {
4333
+ const at = time.now() + delay;
4334
+ if (at < wakeAt) {
4335
+ clearTimeout(wake);
4336
+ wakeAt = at;
4337
+ wake = setTimeout(() => {
4338
+ wakeAt = Infinity;
4339
+ group.schedule(false);
4340
+ }, delay);
4341
+ }
4342
+ };
4207
4343
  /**
4208
4344
  * Replace the WAAPI animations with ones built from now. Returns
4209
4345
  * undefined if the animations can't be composed.
@@ -4279,7 +4415,7 @@
4279
4415
  */
4280
4416
  if (from - now > buildAhead) {
4281
4417
  moving.forEach((track) => track.sync());
4282
- wake = setTimeout(() => group.schedule(true), from - now - buildAhead);
4418
+ wakeIn((buildAt = from - now - buildAhead));
4283
4419
  return true;
4284
4420
  }
4285
4421
  easing =
@@ -4334,9 +4470,11 @@
4334
4470
  /**
4335
4471
  * If every animation has been paused, played, seeked or sped up
4336
4472
  * together since the WAAPI animation was built, do the same to it.
4337
- * Returns false if it needs rebuilding instead.
4473
+ * Returns false if it needs rebuilding instead. Seeking to before a
4474
+ * tween starts rebuilds, so a running group seeked every frame still
4475
+ * moves to the main thread.
4338
4476
  */
4339
- const retime = (now) => {
4477
+ const retime = (now, isSeek) => {
4340
4478
  let elapsed;
4341
4479
  let rate = 0;
4342
4480
  for (const track of tracks) {
@@ -4369,12 +4507,33 @@
4369
4507
  }
4370
4508
  if (elapsed === undefined)
4371
4509
  return true;
4372
- if (!segments.length)
4373
- return false;
4510
+ /**
4511
+ * Waiting to build a tween that starts later. Until then the
4512
+ * values hold where they start, so only when to build changes.
4513
+ * Held, it has nothing on the compositor, so it can be seeked.
4514
+ */
4515
+ if (!segments.length) {
4516
+ if (buildAt === undefined || (isSeek && rate))
4517
+ return false;
4518
+ if (rate) {
4519
+ const delay = (buildAt - elapsed) / rate;
4520
+ if (delay < 1)
4521
+ return false;
4522
+ wakeIn(delay);
4523
+ }
4524
+ return true;
4525
+ }
4526
+ /**
4527
+ * Only a tween is built to start later, and it holds its first
4528
+ * keyframe until then, so it can be paused and played before it
4529
+ * starts.
4530
+ */
4374
4531
  for (const { offset, end, isDone } of segments) {
4375
4532
  const local = elapsed - offset;
4376
4533
  if (end < Infinity &&
4377
- (isDone ? local < end - 1 : local < 0 || local >= end)) {
4534
+ (isDone
4535
+ ? local < end - 1
4536
+ : (local < 0 && (isSeek || offset <= 0)) || local >= end)) {
4378
4537
  return false;
4379
4538
  }
4380
4539
  }
@@ -4395,7 +4554,8 @@
4395
4554
  animation.updatePlaybackRate(rate);
4396
4555
  }
4397
4556
  else if (rate) {
4398
- animation.playbackRate = rate;
4557
+ animation.playbackRate !== rate &&
4558
+ (animation.playbackRate = rate);
4399
4559
  animation.startTime = now - local / rate;
4400
4560
  }
4401
4561
  else {
@@ -4469,12 +4629,12 @@
4469
4629
  if (group.isJS) {
4470
4630
  group.isJS = false;
4471
4631
  needsBuild = true;
4472
- tracks.forEach((track) => track.js?.stop());
4632
+ tracks.forEach((track) => track.stopJS());
4473
4633
  }
4474
4634
  const shouldBuild = needsBuild;
4475
4635
  const churned = hasChurned;
4476
4636
  needsBuild = hasChurned = false;
4477
- if (shouldBuild || !retime(now)) {
4637
+ if (shouldBuild || !retime(now, churned)) {
4478
4638
  if (churned) {
4479
4639
  if (now - lastChurn < churnWindow)
4480
4640
  return group.demote();
@@ -4483,6 +4643,13 @@
4483
4643
  if (!animate(now))
4484
4644
  return group.demote();
4485
4645
  }
4646
+ else if (buildAt !== undefined && !churned) {
4647
+ /**
4648
+ * Still waiting to build, so the values still hold where
4649
+ * they start.
4650
+ */
4651
+ return;
4652
+ }
4486
4653
  /**
4487
4654
  * Held animations don't move, so set their motion values to where
4488
4655
  * they're held, as a JSAnimation would on its next tick. Pausing
@@ -4750,7 +4917,10 @@
4750
4917
  class GroupAnimation {
4751
4918
  constructor(animations) {
4752
4919
  // Bound to accommodate common `return animation.stop` pattern
4753
- this.stop = () => this.runAll("stop");
4920
+ this.stop = () => {
4921
+ for (const animation of this.animations)
4922
+ animation.stop();
4923
+ };
4754
4924
  this.animations = animations.filter(Boolean);
4755
4925
  }
4756
4926
  get finished() {
@@ -4762,11 +4932,6 @@
4762
4932
  getAll(propName) {
4763
4933
  return this.animations[0][propName];
4764
4934
  }
4765
- setAll(propName, newValue) {
4766
- for (let i = 0; i < this.animations.length; i++) {
4767
- this.animations[i][propName] = newValue;
4768
- }
4769
- }
4770
4935
  attachTimeline(timeline) {
4771
4936
  const subscriptions = this.animations.map((animation) => animation.attachTimeline(timeline));
4772
4937
  return () => {
@@ -4779,14 +4944,21 @@
4779
4944
  get time() {
4780
4945
  return this.getAll("time");
4781
4946
  }
4947
+ /**
4948
+ * Setters and methods name the property directly, rather than through
4949
+ * a shared helper, so each call site stays monomorphic. Sequences
4950
+ * call these on every animation, many times a second.
4951
+ */
4782
4952
  set time(time) {
4783
- this.setAll("time", time);
4953
+ for (const animation of this.animations)
4954
+ animation.time = time;
4784
4955
  }
4785
4956
  get speed() {
4786
4957
  return this.getAll("speed");
4787
4958
  }
4788
4959
  set speed(speed) {
4789
- this.setAll("speed", speed);
4960
+ for (const animation of this.animations)
4961
+ animation.speed = speed;
4790
4962
  }
4791
4963
  get state() {
4792
4964
  return this.getAll("state");
@@ -4800,20 +4972,21 @@
4800
4972
  get iterationDuration() {
4801
4973
  return getMax(this.animations, "iterationDuration");
4802
4974
  }
4803
- runAll(methodName) {
4804
- this.animations.forEach((controls) => controls[methodName]());
4805
- }
4806
4975
  play() {
4807
- this.runAll("play");
4976
+ for (const animation of this.animations)
4977
+ animation.play();
4808
4978
  }
4809
4979
  pause() {
4810
- this.runAll("pause");
4980
+ for (const animation of this.animations)
4981
+ animation.pause();
4811
4982
  }
4812
4983
  cancel() {
4813
- this.runAll("cancel");
4984
+ for (const animation of this.animations)
4985
+ animation.cancel();
4814
4986
  }
4815
4987
  complete() {
4816
- this.runAll("complete");
4988
+ for (const animation of this.animations)
4989
+ animation.complete();
4817
4990
  }
4818
4991
  }
4819
4992
  function getMax(animations, propName) {
@@ -5173,28 +5346,32 @@
5173
5346
  * @param animation - A function that starts the provided animation
5174
5347
  */
5175
5348
  start(startAnimation) {
5349
+ return new Promise((resolve) => this.run(startAnimation, resolve));
5350
+ }
5351
+ /**
5352
+ * As start(), without making a promise, for animations started
5353
+ * internally, which complete through their own controls.
5354
+ */
5355
+ run(startAnimation, onComplete) {
5176
5356
  this.stop();
5177
- return new Promise((resolve) => {
5178
- this.hasAnimated = true;
5179
- /**
5180
- * Complete synchronously via the callback rather than chaining a
5181
- * second promise per animation. Guard against animations that
5182
- * complete before startAnimation has returned.
5183
- */
5184
- let isComplete = false;
5185
- let animation;
5186
- // eslint-disable-next-line prefer-const -- read by the callback before assignment when completing synchronously
5187
- animation = startAnimation(() => {
5188
- isComplete = true;
5189
- this.events.animationComplete?.notify();
5190
- if (this.animation === animation)
5191
- this.animation = undefined;
5192
- resolve();
5193
- });
5194
- if (!isComplete)
5195
- this.animation = animation;
5196
- this.events.animationStart?.notify();
5357
+ this.hasAnimated = true;
5358
+ /**
5359
+ * Guard against animations that complete before startAnimation
5360
+ * has returned.
5361
+ */
5362
+ let isComplete = false;
5363
+ let animation;
5364
+ // eslint-disable-next-line prefer-const -- read by the callback before assignment when completing synchronously
5365
+ animation = startAnimation(() => {
5366
+ isComplete = true;
5367
+ this.events.animationComplete?.notify();
5368
+ if (this.animation === animation)
5369
+ this.animation = undefined;
5370
+ onComplete?.();
5197
5371
  });
5372
+ if (!isComplete)
5373
+ this.animation = animation;
5374
+ this.events.animationStart?.notify();
5198
5375
  }
5199
5376
  /**
5200
5377
  * Stop the currently active animation.
@@ -5816,7 +5993,7 @@
5816
5993
  }
5817
5994
  addValueToWillChange(visualElement, key);
5818
5995
  const shouldReduceMotion = reduceMotion ?? visualElement.shouldReduceMotion;
5819
- value.start(animateMotionValue(key, value, valueTarget, shouldReduceMotion && positionalKeys.has(key)
5996
+ value.run(animateMotionValue(key, value, valueTarget, shouldReduceMotion && positionalKeys.has(key)
5820
5997
  ? { type: false }
5821
5998
  : valueTransition, visualElement, isHandoff));
5822
5999
  const animation = value.animation;
@@ -5951,9 +6128,14 @@
5951
6128
  }
5952
6129
 
5953
6130
  class DOMKeyframesResolver extends KeyframeResolver {
5954
- constructor() {
5955
- super(...arguments);
5956
- this.isAsync = true;
6131
+ /**
6132
+ * Passes isAsync to the base constructor rather than setting it as a
6133
+ * class field, which would compile to a constructor that spreads
6134
+ * `arguments` into super(). That spread is slow in the interpreter,
6135
+ * and animate() constructs one resolver per value.
6136
+ */
6137
+ constructor(unresolvedKeyframes, onComplete, name, motionValue, element) {
6138
+ super(unresolvedKeyframes, onComplete, name, motionValue, element, true);
5957
6139
  }
5958
6140
  /**
5959
6141
  * Keyframes that don't need reading from the DOM, or measuring,
@@ -6252,7 +6434,7 @@
6252
6434
  frame.update(() => value.set(target));
6253
6435
  continue;
6254
6436
  }
6255
- value.start(animateMotionValue(key, value, target, reduceMotion && positionalKeys.has(key)
6437
+ value.run(animateMotionValue(key, value, target, reduceMotion && positionalKeys.has(key)
6256
6438
  ? { type: false }
6257
6439
  : transition, element));
6258
6440
  value.animation &&
@@ -6282,8 +6464,14 @@
6282
6464
  * measurement) via `element`.
6283
6465
  */
6284
6466
  function animateEffectSubject(effect, subject, keyframes, transition, element) {
6285
- return animateValues((key) => {
6286
- let value = effect.get(subject, key);
6467
+ /**
6468
+ * Values made for this call are bound with one effect call, after the
6469
+ * loop, rather than one each.
6470
+ */
6471
+ let created;
6472
+ let isBound = false;
6473
+ const animations = animateValues((key) => {
6474
+ let value = created?.[key] ?? effect.get(subject, key);
6287
6475
  if (!value) {
6288
6476
  let initial;
6289
6477
  if (!element) {
@@ -6294,10 +6482,15 @@
6294
6482
  exports.invariant(initial !== undefined, `"${key}" can't be read from the animated subject. Provide [from, to] keyframes.`, "effect-unreadable-value");
6295
6483
  }
6296
6484
  value = motionValue(initial, { owner: element });
6297
- effect(subject, { [key]: value });
6485
+ isBound
6486
+ ? effect(subject, { [key]: value })
6487
+ : ((created || (created = {}))[key] = value);
6298
6488
  }
6299
6489
  return value;
6300
6490
  }, keyframes, transition, element);
6491
+ isBound = true;
6492
+ created && effect(subject, created);
6493
+ return animations;
6301
6494
  }
6302
6495
  function firstKeyframe(target) {
6303
6496
  const first = Array.isArray(target) ? target[0] : undefined;
@@ -7293,7 +7486,7 @@
7293
7486
 
7294
7487
  function animateSingleValue(value, keyframes, options) {
7295
7488
  const motionValue$1 = isMotionValue(value) ? value : motionValue(value);
7296
- motionValue$1.start(animateMotionValue("", motionValue$1, keyframes, options));
7489
+ motionValue$1.run(animateMotionValue("", motionValue$1, keyframes, options));
7297
7490
  return motionValue$1.animation;
7298
7491
  }
7299
7492
 
@@ -7793,13 +7986,7 @@
7793
7986
  if (xTranslate || yTranslate || zTranslate) {
7794
7987
  transform = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `;
7795
7988
  }
7796
- /**
7797
- * Apply scale correction for the tree transform.
7798
- * This will apply scale to the screen-orientated axes.
7799
- */
7800
- if (treeScale.x !== 1 || treeScale.y !== 1) {
7801
- transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
7802
- }
7989
+ let angles = "";
7803
7990
  if (latestTransform) {
7804
7991
  const { transformPerspective } = latestTransform;
7805
7992
  if (transformPerspective)
@@ -7808,20 +7995,48 @@
7808
7995
  const key = angleTransforms[i];
7809
7996
  const value = latestTransform[key];
7810
7997
  if (value)
7811
- transform += `${key}(${value}deg) `;
7998
+ angles += `${key}(${value}deg) `;
7812
7999
  // Additive `rotate()` so user `rotate` isn't clobbered.
7813
8000
  if (!i && latestTransform.pathRotation)
7814
- transform += `rotate(${latestTransform.pathRotation}deg) `;
8001
+ angles += `rotate(${latestTransform.pathRotation}deg) `;
7815
8002
  }
7816
8003
  }
7817
- /**
7818
- * Apply scale to match the size of the element to the size we want it.
7819
- * This will apply scale to the element-orientated axes.
7820
- */
7821
- const elementScaleX = delta.x.scale * treeScale.x;
7822
- const elementScaleY = delta.y.scale * treeScale.y;
7823
- if (elementScaleX !== 1 || elementScaleY !== 1) {
7824
- transform += `scale(${elementScaleX}, ${elementScaleY})`;
8004
+ if (angles) {
8005
+ /**
8006
+ * Apply scale correction for the tree transform.
8007
+ * This will apply scale to the screen-orientated axes.
8008
+ */
8009
+ if (treeScale.x !== 1 || treeScale.y !== 1) {
8010
+ transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
8011
+ }
8012
+ transform += angles;
8013
+ /**
8014
+ * Apply scale to match the size of the element to the size we want it.
8015
+ * This will apply scale to the element-orientated axes.
8016
+ */
8017
+ const elementScaleX = delta.x.scale * treeScale.x;
8018
+ const elementScaleY = delta.y.scale * treeScale.y;
8019
+ if (elementScaleX !== 1 || elementScaleY !== 1) {
8020
+ transform += `scale(${elementScaleX}, ${elementScaleY})`;
8021
+ }
8022
+ }
8023
+ else if (delta.x.scale !== 1 || delta.y.scale !== 1) {
8024
+ /**
8025
+ * With no rotation or skew between them, the tree scale correction
8026
+ * (1 / treeScale) and the element scale (delta.scale * treeScale)
8027
+ * combine into a single scale. A shorter transform is quicker for
8028
+ * the browser to parse, which matters when it's set every frame.
8029
+ */
8030
+ transform += `scale(${delta.x.scale}, ${delta.y.scale})`;
8031
+ }
8032
+ else if (!transform && (treeScale.x !== 1 || treeScale.y !== 1)) {
8033
+ /**
8034
+ * Inside a scaled tree the transform must never be "none", even when
8035
+ * this element's own delta is the identity: scale correction for
8036
+ * borderRadius and boxShadow is skipped for "none", and the element
8037
+ * would gain and lose its stacking context as the delta snaps.
8038
+ */
8039
+ transform = "scale(1, 1)";
7825
8040
  }
7826
8041
  return transform || "none";
7827
8042
  }
@@ -9706,6 +9921,7 @@
9706
9921
  "whileHover",
9707
9922
  "whileTap",
9708
9923
  "whileDrag",
9924
+ "whilePinch",
9709
9925
  "exit",
9710
9926
  ];
9711
9927
  const variantProps = /* @__PURE__ */ ["initial"].concat(variantPriorityOrder);
@@ -11505,6 +11721,10 @@
11505
11721
  this.openDragLock = null;
11506
11722
  this.isDragging = false;
11507
11723
  this.currentDirection = null;
11724
+ /**
11725
+ * Where the drag started, which pointer offsets are added to. Public
11726
+ * so pinch() can restart a drag from where it leaves the element.
11727
+ */
11508
11728
  this.originPoint = { x: 0, y: 0 };
11509
11729
  /**
11510
11730
  * The permitted boundaries of travel, in pixels.
@@ -12275,6 +12495,540 @@
12275
12495
  return cancel;
12276
12496
  }
12277
12497
 
12498
+ /**
12499
+ * A trackpad pinch arrives as a stream of `wheel` events with no end
12500
+ * event, so it ends once none have arrived for this long.
12501
+ */
12502
+ const wheelTimeout = 150;
12503
+ /**
12504
+ * Convert an `x`/`y` set in other units (e.g. `"-50%"` to centre an
12505
+ * element) to pixels, so the gesture can add to it.
12506
+ */
12507
+ const toPixels = (value, size) => {
12508
+ const latest = value.get();
12509
+ if (typeof latest === "string") {
12510
+ value.set(parseFloat(latest) * (latest.endsWith("%") ? size / 100 : 1));
12511
+ }
12512
+ };
12513
+ const limitsOf = (option) => typeof option === "object" ? option : {};
12514
+ /**
12515
+ * Resolve `elastic` to a resistance for each side, as for `dragElastic`.
12516
+ */
12517
+ const resolveElastic = (elastic = defaultElastic) => {
12518
+ const side = (value) => value === true ? defaultElastic : +(value || 0);
12519
+ return typeof elastic === "object"
12520
+ ? { min: side(elastic.min), max: side(elastic.max) }
12521
+ : { min: side(elastic), max: side(elastic) };
12522
+ };
12523
+ const clampTo = (value, { min = -Infinity, max = Infinity }) => clamp(min, max, value);
12524
+ /**
12525
+ * The raw gesture value that elastic shows as `value`. A pinch that starts
12526
+ * while a value is still past its limit (like during a spring back) carries
12527
+ * on from it, rather than jumping.
12528
+ */
12529
+ const unconstrain = (value, option, resistance) => {
12530
+ const limit = clampTo(value, limitsOf(option));
12531
+ const elastic = resistance[value < limit ? "min" : "max"];
12532
+ return elastic ? limit + (value - limit) / elastic : value;
12533
+ };
12534
+ /**
12535
+ * Listen for pinch gestures on `element`: two touches (or pens), a trackpad
12536
+ * pinch (`wheel` with `ctrlKey`, as Chrome, Edge and Firefox report it),
12537
+ * and Safari's `gesture*` events.
12538
+ *
12539
+ * `getValues` is called each time a gesture starts, in the frame's read
12540
+ * step, for the scale/rotate/x/y values to write to. It runs alongside the
12541
+ * element measurement so neither forces a layout.
12542
+ *
12543
+ * `getOptions` is read whenever it's needed, so options can change while
12544
+ * listening. Return `false` to disable the gesture, which also ends one in
12545
+ * progress.
12546
+ *
12547
+ * `onPinchStart` is called once as each gesture starts, with the gesture's
12548
+ * info as a third argument. It can return the gesture's handlers, as for
12549
+ * `pinch()`.
12550
+ */
12551
+ function addPinchListeners(element, getValues, getEnabledOptions, onPinchStart) {
12552
+ const pointers = new Map();
12553
+ /**
12554
+ * The gesture as last reported: focal point, log of a distance and an
12555
+ * angle. Only changes in distance and angle matter, so trackpad and
12556
+ * Safari input write a virtual distance (the scale) here. Logs keep
12557
+ * a long trackpad pinch from overflowing.
12558
+ */
12559
+ const current = { x: 0, y: 0, l: 0, a: 0 };
12560
+ const start = { ...current };
12561
+ const prev = { ...current };
12562
+ let source;
12563
+ let lastEvent;
12564
+ let values;
12565
+ let originX = 0;
12566
+ let originY = 0;
12567
+ let lastX = 0;
12568
+ let lastY = 0;
12569
+ let hasMoved = false;
12570
+ let wheelTime = 0;
12571
+ let handlers = {};
12572
+ let unlock;
12573
+ /**
12574
+ * The gesture's scale and rotation before limits and elastic apply.
12575
+ */
12576
+ let rawScale = 1;
12577
+ let rawRotate = 0;
12578
+ let stopSnap = () => { };
12579
+ /**
12580
+ * The latest enabled options, so a gesture disabled mid-way can still
12581
+ * report its end.
12582
+ */
12583
+ let options = {};
12584
+ const getOptions = () => (options = getEnabledOptions() || options);
12585
+ const info = () => ({
12586
+ point: { x: current.x, y: current.y },
12587
+ offset: { x: current.x - start.x, y: current.y - start.y },
12588
+ scale: Math.exp(current.l - start.l),
12589
+ rotate: current.a - start.a,
12590
+ });
12591
+ /**
12592
+ * Read the element's box and values, and find its layout origin: its
12593
+ * centre without `x`/`y`. Scale and rotate are applied around the
12594
+ * centre (the default transform origin), so they don't move it.
12595
+ */
12596
+ const measure = () => {
12597
+ const { left, top, width, height } = element.getBoundingClientRect();
12598
+ const { scale, rotate, pan, elastic } = getOptions();
12599
+ const [s, r, x, y] = (values = getValues());
12600
+ const resistance = resolveElastic(elastic);
12601
+ /**
12602
+ * Stop animations on values this gesture writes, and leave the
12603
+ * rest running.
12604
+ */
12605
+ scale !== false && s.stop();
12606
+ rotate !== false && r.stop();
12607
+ rawScale = unconstrain(s.get(), scale, resistance);
12608
+ rawRotate = unconstrain(r.get(), rotate, resistance);
12609
+ if (pan !== false) {
12610
+ x.stop();
12611
+ y.stop();
12612
+ toPixels(x, element.offsetWidth ?? width);
12613
+ toPixels(y, element.offsetHeight ?? height);
12614
+ }
12615
+ lastX = x.get();
12616
+ lastY = y.get();
12617
+ originX = left + width / 2 - lastX;
12618
+ originY = top + height / 2 - lastY;
12619
+ };
12620
+ const dragControls = () => elementDragControls.get(visualElementStore.get(element));
12621
+ /**
12622
+ * On release, spring scale and rotation back inside their limits (or
12623
+ * to a `snap` angle), keeping the focal point in place, or everything
12624
+ * back to its origin with `snapToOrigin`.
12625
+ */
12626
+ const snap = () => {
12627
+ const { scale: scaleOption, rotate: rotateOption, pan, snapToOrigin, transition, } = options;
12628
+ const [scale, rotate, x, y] = values;
12629
+ const s0 = scale.get();
12630
+ const r0 = rotate.get();
12631
+ const x0 = x.get();
12632
+ const y0 = y.get();
12633
+ const { snap: step } = limitsOf(rotateOption);
12634
+ let s1 = clampTo(s0, limitsOf(scaleOption));
12635
+ let r1 = clampTo(step ? Math.round(r0 / step) * step : r0, limitsOf(rotateOption));
12636
+ if (snapToOrigin) {
12637
+ s1 = 1;
12638
+ // The nearest upright angle, so it turns the shortest way
12639
+ r1 = Math.round(r0 / 360) * 360;
12640
+ }
12641
+ /**
12642
+ * Keep the focal point in place, unless the element doesn't move
12643
+ * with it, or a drag carries on and owns x/y.
12644
+ */
12645
+ const moves = pan !== false && !dragControls()?.isDragging;
12646
+ const vx = originX + x0 - current.x;
12647
+ const vy = originY + y0 - current.y;
12648
+ if (!s0 ||
12649
+ (s1 === s0 && r1 === r0 && !(snapToOrigin && moves && (x0 || y0)))) {
12650
+ return;
12651
+ }
12652
+ const generator = spring({
12653
+ keyframes: [0, 1],
12654
+ stiffness: 200,
12655
+ damping: 40,
12656
+ ...transition,
12657
+ });
12658
+ const startTime = time.now();
12659
+ /**
12660
+ * Drive the values from one spring, from 0 to 1, so they stay in
12661
+ * step and the focal point stays in place.
12662
+ */
12663
+ const tick = () => {
12664
+ if (dragControls()?.isDragging)
12665
+ return stopSnap();
12666
+ const { value: p, done } = generator.next(time.now() - startTime);
12667
+ if (done)
12668
+ stopSnap();
12669
+ const k = mixNumber$1(s0, s1, p);
12670
+ const r = mixNumber$1(r0, r1, p);
12671
+ const angle = ((r - r0) * Math.PI) / 180;
12672
+ const cos = (Math.cos(angle) * k) / s0;
12673
+ const sin = (Math.sin(angle) * k) / s0;
12674
+ scaleOption !== false && scale.set(k);
12675
+ rotateOption !== false && rotate.set(r);
12676
+ if (moves) {
12677
+ x.set(snapToOrigin
12678
+ ? mixNumber$1(x0, 0, p)
12679
+ : x0 + cos * vx - sin * vy - vx);
12680
+ y.set(snapToOrigin
12681
+ ? mixNumber$1(y0, 0, p)
12682
+ : y0 + sin * vx + cos * vy - vy);
12683
+ }
12684
+ };
12685
+ stopSnap = () => cancelFrame(tick);
12686
+ frame.update(tick, true);
12687
+ };
12688
+ /**
12689
+ * Apply the change in the gesture since the last frame as an
12690
+ * incremental scale and rotation around the previous focal point,
12691
+ * plus the focal point's movement.
12692
+ */
12693
+ const apply = () => {
12694
+ if (!values || !hasMoved)
12695
+ return;
12696
+ hasMoved = false;
12697
+ const { rotate: rotateOption, scale: scaleOption, pan, elastic, } = getOptions();
12698
+ const [scale, rotate, x, y] = values;
12699
+ const resistance = resolveElastic(elastic);
12700
+ const latest = scale.get();
12701
+ let theta = 0;
12702
+ let k = 1;
12703
+ /**
12704
+ * Apply limits and elastic to the gesture's raw scale and rotation.
12705
+ * At a hard limit, the raw value stops too, so moving back responds
12706
+ * straight away.
12707
+ */
12708
+ const constrain = (raw, option) => {
12709
+ const limits = limitsOf(option);
12710
+ const limit = clampTo(raw, limits);
12711
+ return resistance[raw < limit ? "min" : "max"]
12712
+ ? [applyConstraints(raw, limits, resistance), raw]
12713
+ : [limit, limit];
12714
+ };
12715
+ if (scaleOption !== false && latest) {
12716
+ const [next, raw] = constrain(clamp(1e-9, 1e9, rawScale * Math.exp(current.l - prev.l)), scaleOption);
12717
+ rawScale = raw;
12718
+ k = next / latest;
12719
+ scale.set(next);
12720
+ }
12721
+ if (rotateOption !== false) {
12722
+ const [next, raw] = constrain(rawRotate + current.a - prev.a, rotateOption);
12723
+ rawRotate = raw;
12724
+ theta = next - rotate.get();
12725
+ if (theta)
12726
+ rotate.set(next);
12727
+ }
12728
+ if (pan !== false) {
12729
+ /**
12730
+ * Pinch owns x/y while it runs, so stop any animation started
12731
+ * on them since (like a drag's snap back) taking over after.
12732
+ */
12733
+ x.stop();
12734
+ y.stop();
12735
+ /**
12736
+ * If drag() or the drag prop is dragging this element with one
12737
+ * of the touches, it has set x/y this frame to where it started
12738
+ * plus the touch's offset. Carry on from our own values instead,
12739
+ * and restart the drag from them and the touch's latest point.
12740
+ * That way it continues from wherever the pinch leaves the
12741
+ * element, and its release velocity only counts movement after
12742
+ * the pinch, so a zoom doesn't end in a fling.
12743
+ */
12744
+ const drag = dragControls();
12745
+ const isDragging = drag?.isDragging;
12746
+ if (!isDragging) {
12747
+ lastX = x.get();
12748
+ lastY = y.get();
12749
+ }
12750
+ const angle = (theta * Math.PI) / 180;
12751
+ const cos = Math.cos(angle) * k;
12752
+ const sin = Math.sin(angle) * k;
12753
+ const dx = prev.x - originX - lastX;
12754
+ const dy = prev.y - originY - lastY;
12755
+ /**
12756
+ * Move the centre so the previous focal point, scaled and
12757
+ * rotated around the centre, lands on the current focal point.
12758
+ */
12759
+ lastX += dx + current.x - prev.x - (cos * dx - sin * dy);
12760
+ lastY += dy + current.y - prev.y - (sin * dx + cos * dy);
12761
+ if (isDragging) {
12762
+ const history = drag.panSession.history;
12763
+ history.splice(0, history.length - 1);
12764
+ /**
12765
+ * Date the point long ago, so drag only measures release
12766
+ * velocity from moves after the pinch. A move that drag
12767
+ * processes as the touch lifts is part of the pinch.
12768
+ */
12769
+ history[0].timestamp = -Infinity;
12770
+ drag.originPoint.x = lastX;
12771
+ drag.originPoint.y = lastY;
12772
+ }
12773
+ x.set(lastX);
12774
+ y.set(lastY);
12775
+ }
12776
+ Object.assign(prev, current);
12777
+ handlers.onPinch?.(lastEvent, info());
12778
+ };
12779
+ /**
12780
+ * Runs after the update step, where drag sets x/y, so it has the final
12781
+ * say on them each frame.
12782
+ */
12783
+ const update = () => {
12784
+ if (!getEnabledOptions())
12785
+ return end(lastEvent);
12786
+ apply();
12787
+ if (source === "wheel" && time.now() - wheelTime > wheelTimeout) {
12788
+ end(lastEvent);
12789
+ }
12790
+ };
12791
+ const begin = (event, from) => {
12792
+ if (!getEnabledOptions())
12793
+ return;
12794
+ stopSnap();
12795
+ source = from;
12796
+ lastEvent = event;
12797
+ hasMoved = false;
12798
+ values = undefined;
12799
+ handlers = {};
12800
+ Object.assign(start, current);
12801
+ Object.assign(prev, current);
12802
+ frame.read(measure);
12803
+ frame.preRender(update, true);
12804
+ const result = onPinchStart(element, event, info());
12805
+ handlers =
12806
+ typeof result === "function" ? { onComplete: result } : result || {};
12807
+ };
12808
+ const end = (event) => {
12809
+ if (!source)
12810
+ return;
12811
+ cancelFrame(measure);
12812
+ cancelFrame(update);
12813
+ if (getEnabledOptions()) {
12814
+ apply();
12815
+ values && snap();
12816
+ }
12817
+ source = undefined;
12818
+ handlers.onComplete?.(event, info());
12819
+ };
12820
+ const moved = (event) => {
12821
+ lastEvent = event;
12822
+ hasMoved = true;
12823
+ };
12824
+ const readPointers = () => {
12825
+ const [a, b] = pointers.values();
12826
+ const angle = (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
12827
+ const delta = angle - current.a;
12828
+ current.x = (a.x + b.x) / 2;
12829
+ current.y = (a.y + b.y) / 2;
12830
+ current.l = Math.log(Math.hypot(b.x - a.x, b.y - a.y) || 1);
12831
+ /**
12832
+ * Take the shortest way round, so rotation keeps counting past
12833
+ * 180deg rather than flipping to -180deg.
12834
+ */
12835
+ current.a += delta - 360 * Math.round(delta / 360);
12836
+ };
12837
+ const setPointer = (event) => pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
12838
+ const onPointerMove = (event) => {
12839
+ if (!pointers.has(event.pointerId))
12840
+ return;
12841
+ setPointer(event);
12842
+ if (source === "pointer") {
12843
+ readPointers();
12844
+ moved(event);
12845
+ }
12846
+ };
12847
+ const onPointerUp = (event) => {
12848
+ if (!pointers.delete(event.pointerId))
12849
+ return;
12850
+ if (source === "pointer")
12851
+ end(event);
12852
+ if (!pointers.size) {
12853
+ toggleWindowListeners();
12854
+ release();
12855
+ }
12856
+ };
12857
+ /**
12858
+ * Once a touch is down on the element, listen on the window too, so
12859
+ * the second touch can land beside it (for instance on a small image).
12860
+ */
12861
+ const onPointerDown = (event) => {
12862
+ if (source ||
12863
+ pointers.size > 1 ||
12864
+ pointers.has(event.pointerId) ||
12865
+ event.pointerType === "mouse") {
12866
+ return;
12867
+ }
12868
+ if (!pointers.size)
12869
+ toggleWindowListeners(true);
12870
+ setPointer(event);
12871
+ if (pointers.size === 2) {
12872
+ readPointers();
12873
+ begin(event, "pointer");
12874
+ /**
12875
+ * Unless this element drags, hold the drag lock until every
12876
+ * touch lifts. A press on it then ends as a cancel, rather than
12877
+ * a tap, and a draggable parent doesn't drag.
12878
+ */
12879
+ if (source &&
12880
+ !unlock &&
12881
+ !elementDragControls.get(visualElementStore.get(element))) {
12882
+ unlock = setDragLock(true);
12883
+ }
12884
+ }
12885
+ };
12886
+ /**
12887
+ * Release the drag lock a frame later, so a press ending on this same
12888
+ * pointerup still sees it.
12889
+ */
12890
+ const release = () => {
12891
+ const done = unlock;
12892
+ unlock = undefined;
12893
+ done && frame.postRender(done);
12894
+ };
12895
+ const toggleWindowListeners = (add) => {
12896
+ const method = add ? "addEventListener" : "removeEventListener";
12897
+ window[method]("pointerdown", onPointerDown);
12898
+ window[method]("pointermove", onPointerMove);
12899
+ window[method]("pointerup", onPointerUp);
12900
+ window[method]("pointercancel", onPointerUp);
12901
+ };
12902
+ const onWheel = (event) => {
12903
+ if (!event.ctrlKey || (source && source !== "wheel"))
12904
+ return;
12905
+ current.x = event.clientX;
12906
+ current.y = event.clientY;
12907
+ if (!source) {
12908
+ current.l = 0;
12909
+ begin(event, "wheel");
12910
+ if (!source)
12911
+ return;
12912
+ }
12913
+ event.preventDefault();
12914
+ /**
12915
+ * Lines (Firefox's mouse wheel) to pixels, and cap each event so a
12916
+ * mouse wheel notch with ctrl held (about 100px) zooms a step.
12917
+ */
12918
+ current.l -=
12919
+ clamp(-50, 50, event.deltaY * (event.deltaMode ? 16 : 1)) / 100;
12920
+ wheelTime = time.now();
12921
+ moved(event);
12922
+ };
12923
+ /**
12924
+ * Safari reports trackpad pinches as `gesture*` events. iOS Safari
12925
+ * fires them for touches too, alongside the pointer events we track.
12926
+ */
12927
+ const onGesture = (event) => {
12928
+ if (!pointers.size && (!source || source === "gesture")) {
12929
+ const { scale, rotation, clientX, clientY } = event;
12930
+ current.x = clientX;
12931
+ current.y = clientY;
12932
+ current.l = Math.log(scale);
12933
+ current.a = rotation;
12934
+ if (source) {
12935
+ moved(event);
12936
+ if (event.type === "gestureend")
12937
+ end(event);
12938
+ }
12939
+ else if (event.type === "gesturestart") {
12940
+ begin(event, "gesture");
12941
+ }
12942
+ }
12943
+ if (source)
12944
+ event.preventDefault();
12945
+ };
12946
+ const listeners = {
12947
+ pointerdown: onPointerDown,
12948
+ wheel: onWheel,
12949
+ gesturestart: onGesture,
12950
+ gesturechange: onGesture,
12951
+ gestureend: onGesture,
12952
+ };
12953
+ for (const name in listeners) {
12954
+ element.addEventListener(name, listeners[name], { passive: false });
12955
+ }
12956
+ return () => {
12957
+ for (const name in listeners) {
12958
+ element.removeEventListener(name, listeners[name]);
12959
+ }
12960
+ toggleWindowListeners();
12961
+ end(lastEvent);
12962
+ stopSnap();
12963
+ pointers.clear();
12964
+ release();
12965
+ };
12966
+ }
12967
+ const valueKeys = ["scale", "rotate", "x", "y"];
12968
+ /**
12969
+ * The element's scale/rotate/x/y motion values: those of its
12970
+ * VisualElement if it has one (it's a <motion.*> component, or drag() or
12971
+ * animateLayout() own it), otherwise those animate() binds to it, created
12972
+ * from its current style if this is the first time.
12973
+ */
12974
+ const getElementValues = (element) => {
12975
+ const visualElement = visualElementStore.get(element);
12976
+ const effect = isSVGElement(element) ? svgSubjectEffect : styleSubjectEffect;
12977
+ return valueKeys.map((key) => {
12978
+ if (visualElement) {
12979
+ return visualElement.getValue(key, key === "scale" ? 1 : 0);
12980
+ }
12981
+ let value = effect.get(element, key);
12982
+ if (!value) {
12983
+ value = motionValue(readStyleValue(element, key));
12984
+ effect(element, { [key]: value });
12985
+ }
12986
+ return value;
12987
+ });
12988
+ };
12989
+ function pinch(elementOrSelector, startOrOptions, options = {}) {
12990
+ let onPinchStart = () => { };
12991
+ if (typeof startOrOptions === "function") {
12992
+ onPinchStart = startOrOptions;
12993
+ }
12994
+ else if (startOrOptions) {
12995
+ options = startOrOptions;
12996
+ }
12997
+ const scope = activeScope.current;
12998
+ /**
12999
+ * Run the start callback and the handlers it returns in the active
13000
+ * scope, so work they start is collected. A returned function is
13001
+ * bound by `scope.bind` itself.
13002
+ */
13003
+ if (scope) {
13004
+ const start = scope.bind(onPinchStart);
13005
+ onPinchStart = (element, event) => {
13006
+ const result = start(element, event);
13007
+ if (typeof result !== "object")
13008
+ return result;
13009
+ const handlers = {};
13010
+ for (const key in result) {
13011
+ const name = key;
13012
+ const handler = result[name];
13013
+ handlers[name] = handler && scope.bind(handler);
13014
+ }
13015
+ return handlers;
13016
+ };
13017
+ }
13018
+ const cleanups = resolveElements(elementOrSelector).map((element) => {
13019
+ scope?.track(element);
13020
+ const { style } = element;
13021
+ const touchAction = style.touchAction;
13022
+ style.touchAction = "none";
13023
+ const remove = addPinchListeners(element, () => getElementValues(element), () => options, onPinchStart);
13024
+ return () => {
13025
+ remove();
13026
+ style.touchAction = touchAction;
13027
+ };
13028
+ });
13029
+ return addToScope(() => cleanups.forEach((cleanup) => cleanup()));
13030
+ }
13031
+
12278
13032
  /**
12279
13033
  * Recursively traverse up the tree to check whether the provided child node
12280
13034
  * is the parent or a descendant of it.
@@ -12490,14 +13244,18 @@
12490
13244
  */
12491
13245
  const endEventOptions = { ...eventOptions, capture: true };
12492
13246
  const onPointerEnd = (endEvent, success) => {
13247
+ /**
13248
+ * Another touch lifting (for instance after a pinch) doesn't
13249
+ * end the press.
13250
+ */
13251
+ if (!isPrimaryPointer(endEvent))
13252
+ return;
12493
13253
  window.removeEventListener("pointerup", onPointerUp, endEventOptions);
12494
13254
  window.removeEventListener("pointercancel", onPointerCancel, endEventOptions);
12495
13255
  window.removeEventListener("pointermove", onPointerMove, endEventOptions);
12496
13256
  target.removeEventListener("contextmenu", preventDefault);
12497
13257
  cancelFrame(tick);
12498
13258
  isPressing.delete(target);
12499
- if (!isPrimaryPointer(endEvent))
12500
- return;
12501
13259
  /**
12502
13260
  * A press that ends while a drag is active is a cancel.
12503
13261
  */
@@ -15345,6 +16103,13 @@
15345
16103
  info.duration = totalDuration;
15346
16104
  info.labels = timeLabels;
15347
16105
  }
16106
+ /**
16107
+ * Exclude `type` from defaultTransition since springs have been
16108
+ * converted to duration-based easing functions in resolveValueSequence.
16109
+ * Including `type: "spring"` would cause JSAnimation to error when
16110
+ * the merged keyframes array has more than 2 keyframes.
16111
+ */
16112
+ const { type: _type, ...remainingDefaultTransition } = defaultTransition;
15348
16113
  /**
15349
16114
  * For every element and value combination create a new animation.
15350
16115
  */
@@ -15395,13 +16160,6 @@
15395
16160
  }
15396
16161
  const definition = animationDefinitions.get(element);
15397
16162
  definition.keyframes[key] = keyframes;
15398
- /**
15399
- * Exclude `type` from defaultTransition since springs have been
15400
- * converted to duration-based easing functions in resolveValueSequence.
15401
- * Including `type: "spring"` would cause JSAnimation to error when
15402
- * the merged keyframes array has more than 2 keyframes.
15403
- */
15404
- const { type: _type, ...remainingDefaultTransition } = defaultTransition;
15405
16163
  definition.transition[key] = {
15406
16164
  ...remainingDefaultTransition,
15407
16165
  duration: totalDuration,
@@ -16105,8 +16863,13 @@
16105
16863
  }
16106
16864
  }
16107
16865
 
16866
+ /**
16867
+ * A sequence has at least one segment or nested sequence. Labels alone
16868
+ * are never a sequence, as an array of strings isn't a subject either.
16869
+ */
16108
16870
  function isSequence(value) {
16109
- return Array.isArray(value) && value.some(Array.isArray);
16871
+ return (Array.isArray(value) &&
16872
+ value.some((item) => Array.isArray(item) || item?.sequence));
16110
16873
  }
16111
16874
  /**
16112
16875
  * Creates an animation function that is optionally scoped
@@ -16194,33 +16957,41 @@
16194
16957
  });
16195
16958
 
16196
16959
  function animateElements(elementOrSelector, keyframes, options, scope) {
16960
+ const animationDefinitions = [];
16961
+ addAnimationDefinitions(animationDefinitions, elementOrSelector, keyframes, options, scope);
16962
+ return startAnimationDefinitions(animationDefinitions);
16963
+ }
16964
+ /**
16965
+ * WAAPI doesn't support interrupting animations.
16966
+ *
16967
+ * Therefore, starting animations requires a three-step process:
16968
+ * 1. Stop existing animations (write styles to DOM)
16969
+ * 2. Resolve keyframes (read styles from DOM)
16970
+ * 3. Create new animations (write styles to DOM)
16971
+ *
16972
+ * The hybrid `animate()` function uses AsyncAnimation to resolve
16973
+ * keyframes before creating new animations, which removes style
16974
+ * thrashing. Here, we have much stricter filesize constraints.
16975
+ * Therefore we do this in a synchronous way that ensures that
16976
+ * at least within `animate()` calls there is no style thrashing.
16977
+ *
16978
+ * In the motion-native-animate-mini-interrupt benchmark this
16979
+ * was 80% faster than a single loop.
16980
+ *
16981
+ * Step 1, here, can run for many `animate()`-style calls (as for each
16982
+ * element of a sequence) before steps 2 and 3 start them all together.
16983
+ * Otherwise each call's read would force a style recalc after the last
16984
+ * call's write.
16985
+ */
16986
+ function addAnimationDefinitions(animationDefinitions, elementOrSelector, keyframes, options, scope) {
16197
16987
  // Gracefully handle null/undefined elements (e.g., from querySelector returning null)
16198
- if (elementOrSelector == null) {
16199
- return [];
16200
- }
16988
+ if (elementOrSelector == null)
16989
+ return;
16201
16990
  const elements = resolveElements(elementOrSelector, scope);
16202
16991
  const numElements = elements.length;
16203
16992
  typeof process !== "undefined" &&
16204
16993
  "development" !== "production" &&
16205
16994
  exports.invariant(Boolean(numElements), "No valid elements provided.", "no-valid-elements");
16206
- /**
16207
- * WAAPI doesn't support interrupting animations.
16208
- *
16209
- * Therefore, starting animations requires a three-step process:
16210
- * 1. Stop existing animations (write styles to DOM)
16211
- * 2. Resolve keyframes (read styles from DOM)
16212
- * 3. Create new animations (write styles to DOM)
16213
- *
16214
- * The hybrid `animate()` function uses AsyncAnimation to resolve
16215
- * keyframes before creating new animations, which removes style
16216
- * thrashing. Here, we have much stricter filesize constraints.
16217
- * Therefore we do this in a synchronous way that ensures that
16218
- * at least within `animate()` calls there is no style thrashing.
16219
- *
16220
- * In the motion-native-animate-mini-interrupt benchmark this
16221
- * was 80% faster than a single loop.
16222
- */
16223
- const animationDefinitions = [];
16224
16995
  /**
16225
16996
  * Step 1: Build options and stop existing animations (write)
16226
16997
  */
@@ -16264,6 +17035,8 @@
16264
17035
  });
16265
17036
  }
16266
17037
  }
17038
+ }
17039
+ function startAnimationDefinitions(animationDefinitions) {
16267
17040
  /**
16268
17041
  * Step 2: Resolve keyframes (read)
16269
17042
  */
@@ -16987,6 +17760,7 @@
16987
17760
  exports.addBuilderToScope = addBuilderToScope;
16988
17761
  exports.addDomEvent = addDomEvent;
16989
17762
  exports.addEffect = addEffect;
17763
+ exports.addPinchListeners = addPinchListeners;
16990
17764
  exports.addPointerEvent = addPointerEvent;
16991
17765
  exports.addPointerInfo = addPointerInfo;
16992
17766
  exports.addSVGValue = addSVGValue;
@@ -17212,6 +17986,7 @@
17212
17986
  exports.parseCSSVariable = parseCSSVariable;
17213
17987
  exports.parseValueFromTransform = parseValueFromTransform;
17214
17988
  exports.percent = percent;
17989
+ exports.pinch = pinch;
17215
17990
  exports.pipe = pipe;
17216
17991
  exports.pixelsToPercent = pixelsToPercent;
17217
17992
  exports.positionalKeys = positionalKeys;