motion-dom 14.9.1 → 14.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -1886,6 +1886,12 @@ class JSAnimation extends WithPromise {
1886
1886
  return motionUtils.millisecondsToSeconds(this.currentTime);
1887
1887
  }
1888
1888
  set time(newTime) {
1889
+ /**
1890
+ * Seeking out of "finished" leaves the animation paused, so play()
1891
+ * won't renew finished. Renew it here.
1892
+ */
1893
+ if (this.state === "finished")
1894
+ this.updateFinished();
1889
1895
  newTime = motionUtils.secondsToMilliseconds(newTime);
1890
1896
  this.currentTime = newTime;
1891
1897
  if (this.startTime === null ||
@@ -2771,8 +2777,13 @@ class NativeAnimation extends WithPromise {
2771
2777
  this.manualStartTime = null;
2772
2778
  this.finishedTime = null;
2773
2779
  this.animation.currentTime = motionUtils.secondsToMilliseconds(newTime);
2780
+ /**
2781
+ * Seeking out of "finished" leaves the animation paused, so play()
2782
+ * won't renew finished. Renew it here.
2783
+ */
2774
2784
  if (wasFinished) {
2775
2785
  this.animation.pause();
2786
+ this.updateFinished();
2776
2787
  }
2777
2788
  }
2778
2789
  /**
@@ -3200,10 +3211,39 @@ const scaleTolerance = 0.001;
3200
3211
  * rebuilding the WAAPI animation every frame.
3201
3212
  */
3202
3213
  const churnWindow = 100;
3214
+ /**
3215
+ * A WAAPI animation that starts moving later than this, as most segments
3216
+ * of a long sequence do, is built this long before it starts, rather than
3217
+ * all at once at the start.
3218
+ */
3219
+ const buildAhead = 100;
3203
3220
  /**
3204
3221
  * Named easings that are the same cubic-bezier in JS and CSS.
3205
3222
  */
3206
3223
  const isNativeEasing = (ease) => /^(linear|ease(In|Out|InOut))$/.test(ease);
3224
+ /**
3225
+ * The last trace of each easing WAAPI can't run into linear(), with its
3226
+ * number of samples, so the elements of a sequence that share an easing
3227
+ * and duration trace it once.
3228
+ */
3229
+ const traced = new WeakMap();
3230
+ const trace = (ease, samples) => {
3231
+ let last = traced.get(ease);
3232
+ if (last?.[0] !== samples) {
3233
+ last = [
3234
+ samples,
3235
+ "linear(" +
3236
+ defaultOffset(Array(samples + 1)).map((p) => round(ease(p)) + " " + round(p * 100) + "%") +
3237
+ ")",
3238
+ ];
3239
+ traced.set(ease, last);
3240
+ }
3241
+ return last[1];
3242
+ };
3243
+ /**
3244
+ * How many samples trace an easing between two timestamps.
3245
+ */
3246
+ const countSamples = (from, to) => Math.min(maxSamples, Math.max(2, Math.ceil((to - from) / sampleDelta)));
3207
3247
  /**
3208
3248
  * Whether two eased progresses match. False if either is NaN.
3209
3249
  */
@@ -3362,22 +3402,48 @@ class TransformAnimation extends JSAnimation {
3362
3402
  return this.isAccelerated() ? this.sampleAt(time.now()) : undefined;
3363
3403
  }
3364
3404
  /**
3365
- * If this is a two-keyframe tween whose easing WAAPI runs exactly,
3366
- * when it starts and stops moving, and that easing.
3405
+ * If this moves between two keyframes only, holding still either side
3406
+ * of them, as each value of a sequence segment does, when it starts
3407
+ * and stops moving, and its easing: as a string if WAAPI runs it
3408
+ * exactly, otherwise its function, to trace.
3367
3409
  */
3368
3410
  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];
3411
+ const { keyframes: keyframes$1, type, times, repeat, delay = 0 } = this.options;
3412
+ let span = -1;
3413
+ if (repeat || type !== keyframes || this.holdTime !== null) {
3414
+ return;
3415
+ }
3416
+ for (let i = 1; i < keyframes$1.length; i++) {
3417
+ if (keyframes$1[i] !== keyframes$1[i - 1]) {
3418
+ if (span >= 0)
3419
+ return;
3420
+ span = i - 1;
3421
+ }
3422
+ }
3423
+ let { ease } = this.options;
3424
+ if (motionUtils.isEasingArray(ease))
3425
+ ease = ease[span];
3426
+ const offsets = times || defaultOffset(keyframes$1);
3427
+ const at = (i) => this.startTime +
3428
+ (delay + offsets[i] * this.totalDuration) / this.speed;
3429
+ if (span >= 0) {
3430
+ const easing = motionUtils.isBezierDefinition(ease)
3431
+ ? cubicBezierAsString(ease)
3432
+ : isNativeEasing(ease)
3433
+ ? supportedWaapiEasing[ease]
3434
+ : motionUtils.easingDefinitionToFunction(ease);
3435
+ /**
3436
+ * An easing that doesn't run from 0 to 1 doesn't move between
3437
+ * the keyframes, so is traced from the values it gives instead.
3438
+ */
3439
+ return [
3440
+ at(span),
3441
+ at(span + 1),
3442
+ typeof easing === "string" ||
3443
+ (isNear$1(easing(0), 0) && isNear$1(easing(1), 1))
3444
+ ? easing
3445
+ : undefined,
3446
+ ];
3381
3447
  }
3382
3448
  }
3383
3449
  /**
@@ -3421,7 +3487,14 @@ class TransformAnimation extends JSAnimation {
3421
3487
  */
3422
3488
  sync() {
3423
3489
  const now = time.now();
3424
- this.options.motionValue.setWithVelocity(this.sampleAt(now - sampleDelta, true), this.sampleAt(now, true), sampleDelta);
3490
+ const value = this.sampleAt(now, true);
3491
+ /**
3492
+ * A held value doesn't move, so there's no need to sample it
3493
+ * twice.
3494
+ */
3495
+ this.options.motionValue.setWithVelocity(this.holdTime === null
3496
+ ? this.sampleAt(now - sampleDelta, true)
3497
+ : value, value, sampleDelta);
3425
3498
  }
3426
3499
  play() {
3427
3500
  /**
@@ -3435,10 +3508,7 @@ class TransformAnimation extends JSAnimation {
3435
3508
  }
3436
3509
  pause() {
3437
3510
  super.pause();
3438
- if (this.isAccelerated()) {
3439
- this.sync();
3440
- this.group.schedule(false);
3441
- }
3511
+ this.isAccelerated() && this.group.schedule(false);
3442
3512
  }
3443
3513
  /**
3444
3514
  * JSAnimation finishes on its next tick, which only happens once the
@@ -3461,14 +3531,8 @@ class TransformAnimation extends JSAnimation {
3461
3531
  }
3462
3532
  return super.time;
3463
3533
  }
3464
- /**
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.
3468
- */
3469
3534
  set time(newTime) {
3470
3535
  super.time = newTime;
3471
- this.isAccelerated() && this.sync();
3472
3536
  }
3473
3537
  /**
3474
3538
  * Scroll timelines set time every frame, so run these on the main
@@ -3480,6 +3544,20 @@ class TransformAnimation extends JSAnimation {
3480
3544
  return super.attachTimeline(timeline);
3481
3545
  }
3482
3546
  }
3547
+ /**
3548
+ * Groups that build straight after the current task build in one
3549
+ * microtask, rather than one each.
3550
+ */
3551
+ let builds;
3552
+ const buildSoon = (build) => {
3553
+ builds ||
3554
+ queueMicrotask(() => {
3555
+ const queue = builds;
3556
+ builds = undefined;
3557
+ queue.forEach((build) => build());
3558
+ });
3559
+ (builds || (builds = [])).push(build);
3560
+ };
3483
3561
  function createGroup(owner) {
3484
3562
  const element = owner.current;
3485
3563
  const tracks = new Set();
@@ -3499,6 +3577,7 @@ function createGroup(owner) {
3499
3577
  let isEnded = false;
3500
3578
  let hasChurned = false;
3501
3579
  let lastChurn = -Infinity;
3580
+ let wake;
3502
3581
  const has = (key) => {
3503
3582
  for (const track of tracks)
3504
3583
  if (track.name === key)
@@ -3566,6 +3645,7 @@ function createGroup(owner) {
3566
3645
  * transform. The renderer writes its own version on its next render.
3567
3646
  */
3568
3647
  const stop = (shouldCommit = true) => {
3648
+ clearTimeout(wake);
3569
3649
  shouldCommit && commit();
3570
3650
  segments.forEach(({ animation }) => cancel(animation));
3571
3651
  segments = [];
@@ -3619,12 +3699,31 @@ function createGroup(owner) {
3619
3699
  * two timestamps, the easing that describes it.
3620
3700
  */
3621
3701
  const getEasing = (moving, from, to, bounds) => {
3622
- const samples = Math.min(maxSamples, Math.max(2, Math.ceil((to - from) / sampleDelta)));
3702
+ const samples = countSamples(from, to);
3623
3703
  /**
3624
3704
  * Too many keyframes or repeats to follow with this many samples.
3625
3705
  */
3626
3706
  if (bounds.length * 4 > samples)
3627
3707
  return;
3708
+ /**
3709
+ * First check half way, where values with different easings
3710
+ * usually differ, before sampling every value many times.
3711
+ */
3712
+ let quick;
3713
+ for (const track of moving) {
3714
+ const first = track.numberAt(from);
3715
+ const p = (track.numberAt((from + to) / 2) - first) /
3716
+ (track.numberAt(to) - first);
3717
+ /**
3718
+ * NaN if it doesn't move.
3719
+ */
3720
+ if (p !== p)
3721
+ continue;
3722
+ if (quick === undefined)
3723
+ quick = p;
3724
+ else if (!isNear$1(p, quick))
3725
+ return;
3726
+ }
3628
3727
  const at = spread(from, to, samples).concat(bounds).sort(byTime);
3629
3728
  const position = (t) => motionUtils.progress(from, to, t);
3630
3729
  let shared;
@@ -3681,11 +3780,30 @@ function createGroup(owner) {
3681
3780
  */
3682
3781
  const sample = (moving, from, to, bounds) => {
3683
3782
  const times = [from];
3783
+ /**
3784
+ * A linear tween is straight between its keyframes, so only the
3785
+ * other values can curve, and a tween only while it moves.
3786
+ */
3787
+ const curved = [];
3788
+ let curveFrom = to;
3789
+ let curveTo = from;
3790
+ for (const track of moving) {
3791
+ const tween = track.tween();
3792
+ if (tween?.[2] !== "linear") {
3793
+ const [trackEnd, cycle] = track.timing();
3794
+ const [a, b] = tween || [from, cycle ? to : trackEnd];
3795
+ curveFrom = Math.min(curveFrom, a);
3796
+ curveTo = Math.max(curveTo, b);
3797
+ curved.push(track);
3798
+ }
3799
+ }
3800
+ curveFrom = Math.max(from, curveFrom);
3801
+ curveTo = Math.min(to, curveTo);
3684
3802
  /**
3685
3803
  * Values that aren't numbers, like calc(), are left to the
3686
3804
  * browser to interpolate.
3687
3805
  */
3688
- const isStraight = (a, b) => moving.every((track) => !(Math.abs(track.numberAt((a + b) / 2) -
3806
+ const isStraight = (a, b) => curved.every((track) => !(Math.abs(track.numberAt((a + b) / 2) -
3689
3807
  (track.numberAt(a) + track.numberAt(b)) / 2) >
3690
3808
  (track.name.startsWith("scale")
3691
3809
  ? scaleTolerance
@@ -3710,10 +3828,13 @@ function createGroup(owner) {
3710
3828
  }
3711
3829
  };
3712
3830
  /**
3713
- * Split at least every 100ms, and at every keyframe and repeat,
3714
- * either side of where a value can jump.
3831
+ * Split at least every 100ms where a value can curve, and at every
3832
+ * keyframe and repeat, either side of where a value can jump.
3715
3833
  */
3716
- const ends = spread(from, to, Math.ceil((to - from) / 100));
3834
+ const ends = curveTo > curveFrom
3835
+ ? spread(curveFrom, curveTo, Math.ceil((curveTo - curveFrom) / 100))
3836
+ : [];
3837
+ ends.push(to);
3717
3838
  for (const t of bounds)
3718
3839
  ends.push(t, Math.min(t + 0.01, to));
3719
3840
  let start = from;
@@ -3733,12 +3854,20 @@ function createGroup(owner) {
3733
3854
  for (const track of moving) {
3734
3855
  const tween = track.tween();
3735
3856
  if (!tween ||
3736
- shared?.some((v, i) => i < 2
3737
- ? Math.abs(tween[i] - v) > 1
3738
- : tween[i] !== v)) {
3857
+ (shared &&
3858
+ (Math.abs(tween[0] - shared[0]) > 1 ||
3859
+ Math.abs(tween[1] - shared[1]) > 1))) {
3739
3860
  return;
3740
3861
  }
3741
- shared = tween;
3862
+ /**
3863
+ * Easings that differ, like the springs a sequence makes for
3864
+ * each value, can still be the same curve.
3865
+ */
3866
+ shared = [
3867
+ tween[0],
3868
+ tween[1],
3869
+ !shared || tween[2] === shared[2] ? tween[2] : undefined,
3870
+ ];
3742
3871
  }
3743
3872
  return shared;
3744
3873
  };
@@ -3793,14 +3922,8 @@ function createGroup(owner) {
3793
3922
  const [trackEnd, trackCycle] = track.timing();
3794
3923
  const isHeld = trackEnd === Infinity;
3795
3924
  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();
3925
+ if (isHeld)
3802
3926
  continue;
3803
- }
3804
3927
  if (track.speed < 0)
3805
3928
  return;
3806
3929
  if (trackCycle) {
@@ -3840,12 +3963,35 @@ function createGroup(owner) {
3840
3963
  */
3841
3964
  const tween = !cycle && getTween(moving);
3842
3965
  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);
3966
+ if (end > now) {
3967
+ let easing;
3968
+ if (tween && tween[1] > now) {
3969
+ const [from, to, ease] = tween;
3970
+ /**
3971
+ * Until it's built, the motion values hold where it
3972
+ * starts, for the renderer to write.
3973
+ */
3974
+ if (from - now > buildAhead) {
3975
+ moving.forEach((track) => track.sync());
3976
+ wake = setTimeout(() => group.schedule(true), from - now - buildAhead);
3977
+ return true;
3978
+ }
3979
+ easing =
3980
+ typeof ease === "string"
3981
+ ? ease
3982
+ : ease
3983
+ ? trace(ease, countSamples(from, to))
3984
+ : getEasing(moving, from, to, []);
3985
+ /**
3986
+ * It holds its last keyframe until the animations end.
3987
+ */
3988
+ easing &&
3989
+ add(run(moving, from, to, easing, {
3990
+ fill: "both",
3991
+ endDelay: end - to,
3992
+ }), from - now, end - from);
3993
+ }
3994
+ easing || add(run(moving, now, end), 0, end - now);
3849
3995
  /**
3850
3996
  * Animations that end sooner finish on the events of
3851
3997
  * empty animations that end with them.
@@ -3894,9 +4040,14 @@ function createGroup(owner) {
3894
4040
  const [builtTime, builtSpeed, wasHeld] = state;
3895
4041
  const trackTime = track.at(now);
3896
4042
  const isHeld = track.timing()[0] === Infinity;
4043
+ /**
4044
+ * With nothing on the compositor, a held animation is set
4045
+ * where it's held, so it can be seeked as often as needed.
4046
+ */
3897
4047
  if (wasHeld) {
3898
- if (isHeld && trackTime === builtTime)
4048
+ if (isHeld && (trackTime === builtTime || !segments.length)) {
3899
4049
  continue;
4050
+ }
3900
4051
  return false;
3901
4052
  }
3902
4053
  const trackElapsed = (trackTime - builtTime) / builtSpeed;
@@ -4026,6 +4177,12 @@ function createGroup(owner) {
4026
4177
  if (!animate(now))
4027
4178
  return group.demote();
4028
4179
  }
4180
+ /**
4181
+ * Held animations don't move, so set their motion values to where
4182
+ * they're held, as a JSAnimation would on its next tick. Pausing
4183
+ * and seeking schedule this, so it's once however many there are.
4184
+ */
4185
+ tracks.forEach((track) => track.timing()[0] === Infinity && track.sync());
4029
4186
  };
4030
4187
  const group = {
4031
4188
  tracks,
@@ -4045,7 +4202,7 @@ function createGroup(owner) {
4045
4202
  isScheduled = true;
4046
4203
  frameData.isProcessing
4047
4204
  ? frame.render(build, false, true)
4048
- : queueMicrotask(build);
4205
+ : buildSoon(build);
4049
4206
  }
4050
4207
  },
4051
4208
  /**
@@ -10578,7 +10735,7 @@ function distance2D(a, b) {
10578
10735
 
10579
10736
  const overflowStyles = /*#__PURE__*/ new Set(["auto", "scroll"]);
10580
10737
  class PanSession {
10581
- constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, element, } = {}) {
10738
+ constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, element, immediate, } = {}) {
10582
10739
  this.startEvent = null;
10583
10740
  this.lastMoveEvent = null;
10584
10741
  this.lastMoveEventInfo = null;
@@ -10664,7 +10821,7 @@ class PanSession {
10664
10821
  this.dragSnapToOrigin = dragSnapToOrigin;
10665
10822
  this.handlers = handlers;
10666
10823
  this.transformPagePoint = transformPagePoint;
10667
- this.distanceThreshold = distanceThreshold;
10824
+ this.distanceThreshold = immediate ? 0 : distanceThreshold;
10668
10825
  this.contextWindow = contextWindow || window;
10669
10826
  const info = extractEventInfo(event);
10670
10827
  const initialInfo = transformPoint(info, this.transformPagePoint);
@@ -10688,6 +10845,10 @@ class PanSession {
10688
10845
  if (element) {
10689
10846
  this.startScrollTracking(element);
10690
10847
  }
10848
+ if (immediate) {
10849
+ this.handlePointerMove(event, info);
10850
+ this.updatePoint();
10851
+ }
10691
10852
  }
10692
10853
  /**
10693
10854
  * Start tracking scroll on ancestors and window.
@@ -11063,14 +11224,14 @@ class VisualElementDragControls {
11063
11224
  this.visualElement = visualElement;
11064
11225
  this.readProps = readProps;
11065
11226
  }
11066
- start(originEvent, { snapToCursor = false, distanceThreshold } = {}) {
11227
+ start(originEvent, options = {}) {
11067
11228
  /**
11068
11229
  * Don't start dragging if this component is exiting
11069
11230
  */
11070
11231
  if (this.visualElement.presenceContext?.isPresent === false)
11071
11232
  return;
11072
11233
  const onSessionStart = (event) => {
11073
- if (snapToCursor)
11234
+ if (options.snapToCursor)
11074
11235
  this.snapToCursor(event);
11075
11236
  this.stopAnimation();
11076
11237
  };
@@ -11192,9 +11353,9 @@ class VisualElementDragControls {
11192
11353
  onSessionEnd,
11193
11354
  resumeAnimation,
11194
11355
  }, {
11356
+ ...options,
11195
11357
  transformPagePoint: this.visualElement.getTransformPagePoint(),
11196
11358
  dragSnapToOrigin,
11197
- distanceThreshold,
11198
11359
  contextWindow: this.visualElement.current?.ownerDocument.defaultView,
11199
11360
  element: this.visualElement.current,
11200
11361
  });
@@ -11643,8 +11804,10 @@ function expectsResolvedDragConstraints({ dragConstraints, onMeasureDragConstrai
11643
11804
  return isElementConstraints(dragConstraints) && !!onMeasureDragConstraints;
11644
11805
  }
11645
11806
 
11646
- const toProps = ({ axis, constraints, elastic, momentum, transition, snapToOrigin, directionLock, propagation, onStart, onMove, onEnd, onDirectionLock, onTransitionEnd, onMeasureConstraints, }) => ({
11807
+ const toProps = ({ axis, constraints, elastic, momentum, transition, snapToOrigin, directionLock, propagation, onStart, onMove, onEnd, onDirectionLock, onTransitionEnd, onMeasureConstraints, x, y, }) => ({
11647
11808
  drag: axis || true,
11809
+ _dragX: x || (y && motionValue(0)),
11810
+ _dragY: y || (x && motionValue(0)),
11648
11811
  dragConstraints: constraints,
11649
11812
  dragElastic: elastic,
11650
11813
  dragMomentum: momentum,
@@ -11853,7 +12016,7 @@ const enableKeyboardPress = (element, eventOptions) => {
11853
12016
  */
11854
12017
  let isKeyPressing = false;
11855
12018
  const handleKeydown = filterEvents(() => {
11856
- if (isPressing.has(element))
12019
+ if (isKeyPressing || isPressing.has(element))
11857
12020
  return;
11858
12021
  isKeyPressing = true;
11859
12022
  firePointerEvent(element, "down");
@@ -11885,6 +12048,18 @@ function isValidPressEvent(event) {
11885
12048
  return isPrimaryPointer(event) && !isDragActive();
11886
12049
  }
11887
12050
  const claimedPointerDownEvents = new WeakSet();
12051
+ /**
12052
+ * Max distance in px between consecutive presses of a `count` sequence.
12053
+ * Android's `ViewConfiguration` double tap slop is 100dp.
12054
+ */
12055
+ const sequenceSlop = 100;
12056
+ /**
12057
+ * Max distance in px a pointer can move during a held press (`hold`
12058
+ * pending, or `repeat`). Android's `ViewConfiguration` touch slop is 8dp.
12059
+ */
12060
+ const holdSlop = 8;
12061
+ const exceeds = (a, b, max) => Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY) > max;
12062
+ const preventDefault = (event) => event.preventDefault();
11888
12063
  /**
11889
12064
  * Create a press gesture.
11890
12065
  *
@@ -11902,22 +12077,110 @@ const claimedPointerDownEvents = new WeakSet();
11902
12077
  * to be focusable for this to work, whereas a press gesture will
11903
12078
  * make an element focusable by default.
11904
12079
  *
12080
+ * `onPressStart` fires on the first pointer or key down, and can return
12081
+ * a function to call when the press ends, or an object of handlers for
12082
+ * this press:
12083
+ *
12084
+ * ```js
12085
+ * press(button, () => ({
12086
+ * onHold: (progress) => {},
12087
+ * onComplete: (event, { success }) => {},
12088
+ * }), { hold: 0.5 })
12089
+ * ```
12090
+ *
11905
12091
  * @public
11906
12092
  */
11907
12093
  function press(targetOrSelector, onPressStart, options = {}) {
11908
12094
  onPressStart = bindToScope(onPressStart);
11909
12095
  const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);
12096
+ const sequences = new WeakMap();
11910
12097
  const startPress = (startEvent) => {
11911
12098
  const target = startEvent.currentTarget;
11912
12099
  if (!isValidPressEvent(startEvent))
11913
12100
  return;
11914
12101
  if (claimedPointerDownEvents.has(startEvent))
11915
12102
  return;
11916
- isPressing.add(target);
11917
12103
  if (options.stopPropagation) {
11918
12104
  claimedPointerDownEvents.add(startEvent);
11919
12105
  }
11920
- const onPressEnd = onPressStart(target, startEvent);
12106
+ /**
12107
+ * Options are read per press so they can be updated between presses.
12108
+ */
12109
+ const { count: presses = 1, countTimeout = 0.3, hold = 0, repeat, } = options;
12110
+ const downTime = time.now();
12111
+ const holdTime = motionUtils.secondsToMilliseconds(hold);
12112
+ const timeout = motionUtils.secondsToMilliseconds(countTimeout);
12113
+ let previous = sequences.get(target);
12114
+ /**
12115
+ * A press during a `count` sequence continues it. If it's too late
12116
+ * or too far away, the sequence is cancelled and this press starts
12117
+ * a new one.
12118
+ */
12119
+ if (previous?.expire(exceeds(previous.event, startEvent, sequenceSlop))) {
12120
+ previous = undefined;
12121
+ }
12122
+ else if (previous) {
12123
+ cancelFrame(previous.expire);
12124
+ sequences.delete(target);
12125
+ }
12126
+ const count = previous ? previous.count + 1 : 1;
12127
+ const isFinal = count >= presses;
12128
+ const isHeld = isFinal && (hold || repeat);
12129
+ let isActive = !hold;
12130
+ let repeats = 0;
12131
+ let handlers;
12132
+ isPressing.add(target);
12133
+ if (previous) {
12134
+ handlers = previous.handlers;
12135
+ }
12136
+ else {
12137
+ const result = onPressStart(target, startEvent);
12138
+ handlers =
12139
+ typeof result === "function"
12140
+ ? { onComplete: result }
12141
+ : result || {};
12142
+ }
12143
+ isFinal && isActive && handlers.onActive?.();
12144
+ /**
12145
+ * While held, `onHold` reports progress from 0 to 1 over `hold`,
12146
+ * then over each `repeat`. Each cycle reports exactly 1 at its end,
12147
+ * then 0 on the next frame.
12148
+ */
12149
+ const repeatTime = motionUtils.secondsToMilliseconds(repeat);
12150
+ let length = holdTime || repeatTime;
12151
+ let cycleEnd = downTime + length;
12152
+ let isCycleStart = true;
12153
+ const tick = () => {
12154
+ if (eventOptions.signal.aborted)
12155
+ return cancelFrame(tick);
12156
+ let progress = Math.min(1 - (cycleEnd - time.now()) / length, 1);
12157
+ /**
12158
+ * The frame after a boundary reports 0, so each cycle visibly
12159
+ * restarts. Boundaries are timed from `downTime`, so this
12160
+ * doesn't delay the next one. If a long frame has already
12161
+ * passed the next boundary, it reports 1 instead.
12162
+ */
12163
+ if (isCycleStart && progress < 1)
12164
+ progress = 0;
12165
+ isCycleStart = false;
12166
+ handlers.onHold?.(progress);
12167
+ if (progress < 1)
12168
+ return;
12169
+ if (isActive) {
12170
+ handlers.onRepeat?.(++repeats);
12171
+ }
12172
+ else {
12173
+ isActive = true;
12174
+ handlers.onActive?.();
12175
+ }
12176
+ if (repeat) {
12177
+ isCycleStart = true;
12178
+ cycleEnd += length = repeatTime;
12179
+ }
12180
+ else {
12181
+ cancelFrame(tick);
12182
+ }
12183
+ };
11921
12184
  /**
11922
12185
  * End listeners run in the capture phase so a descendant calling
11923
12186
  * stopPropagation() in its own pointerup handler can't prevent the
@@ -11928,14 +12191,55 @@ function press(targetOrSelector, onPressStart, options = {}) {
11928
12191
  const onPointerEnd = (endEvent, success) => {
11929
12192
  window.removeEventListener("pointerup", onPointerUp, endEventOptions);
11930
12193
  window.removeEventListener("pointercancel", onPointerCancel, endEventOptions);
11931
- if (isPressing.has(target)) {
11932
- isPressing.delete(target);
11933
- }
11934
- if (!isValidPressEvent(endEvent)) {
12194
+ window.removeEventListener("pointermove", onPointerMove, endEventOptions);
12195
+ target.removeEventListener("contextmenu", preventDefault);
12196
+ cancelFrame(tick);
12197
+ isPressing.delete(target);
12198
+ if (!isPrimaryPointer(endEvent))
11935
12199
  return;
12200
+ /**
12201
+ * A press that ends while a drag is active is a cancel.
12202
+ */
12203
+ if (isDragActive())
12204
+ success = false;
12205
+ if (success && !isFinal) {
12206
+ /**
12207
+ * Wait for the next press of the sequence, and cancel the
12208
+ * gesture if it doesn't arrive in time.
12209
+ */
12210
+ const end = time.now();
12211
+ /**
12212
+ * Cancels the sequence if it's `force`d, or the interval
12213
+ * has passed. Runs every frame, where `force` is frame
12214
+ * data, so it's checked with `=== true`.
12215
+ */
12216
+ const expire = (force) => {
12217
+ const isAborted = eventOptions.signal.aborted;
12218
+ if (isAborted ||
12219
+ force === true ||
12220
+ time.now() - end > timeout) {
12221
+ cancelFrame(expire);
12222
+ sequences.delete(target);
12223
+ isAborted ||
12224
+ handlers.onComplete?.(endEvent, { success: false });
12225
+ return true;
12226
+ }
12227
+ };
12228
+ sequences.set(target, {
12229
+ count,
12230
+ event: startEvent,
12231
+ handlers,
12232
+ expire,
12233
+ });
12234
+ frame.update(expire, true);
11936
12235
  }
11937
- if (typeof onPressEnd === "function") {
11938
- onPressEnd(endEvent, { success });
12236
+ else {
12237
+ /**
12238
+ * Releasing before `hold` is reached is a cancel.
12239
+ */
12240
+ handlers.onComplete?.(endEvent, {
12241
+ success: success && isActive,
12242
+ });
11939
12243
  }
11940
12244
  };
11941
12245
  const onPointerUp = (upEvent) => {
@@ -11947,8 +12251,35 @@ function press(targetOrSelector, onPressStart, options = {}) {
11947
12251
  const onPointerCancel = (cancelEvent) => {
11948
12252
  onPointerEnd(cancelEvent, false);
11949
12253
  };
12254
+ /**
12255
+ * Moving during a pending long press, or a repeating press, cancels
12256
+ * it, so scrolling on touch devices doesn't trigger it. A drag
12257
+ * starting during a `count` sequence cancels it.
12258
+ */
12259
+ const onPointerMove = (moveEvent) => {
12260
+ if (isPrimaryPointer(moveEvent) &&
12261
+ (((repeat || !isActive) &&
12262
+ exceeds(startEvent, moveEvent, holdSlop)) ||
12263
+ (presses > 1 && isDragActive()))) {
12264
+ onPointerCancel(moveEvent);
12265
+ }
12266
+ };
11950
12267
  window.addEventListener("pointerup", onPointerUp, endEventOptions);
11951
12268
  window.addEventListener("pointercancel", onPointerCancel, endEventOptions);
12269
+ if (isHeld || presses > 1) {
12270
+ window.addEventListener("pointermove", onPointerMove, endEventOptions);
12271
+ }
12272
+ if (isHeld) {
12273
+ frame.update(tick, true);
12274
+ /**
12275
+ * Touch devices open a context menu or callout on long press,
12276
+ * which would cancel the gesture.
12277
+ */
12278
+ target.addEventListener("contextmenu", preventDefault, {
12279
+ ...eventOptions,
12280
+ passive: false,
12281
+ });
12282
+ }
11952
12283
  };
11953
12284
  targets.forEach((target) => {
11954
12285
  const pointerDownTarget = options.useGlobalTarget ? window : target;