motion 12.9.7 → 12.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.
@@ -3367,420 +3367,6 @@
3367
3367
  return Array.from(elementOrSelector);
3368
3368
  }
3369
3369
 
3370
- function styleEffect(subject, values) {
3371
- const elements = resolveElements(subject);
3372
- const subscriptions = [];
3373
- for (let i = 0; i < elements.length; i++) {
3374
- const element = elements[i];
3375
- for (const key in values) {
3376
- const value = values[key];
3377
- /**
3378
- * TODO: Get specific setters for combined props (like x)
3379
- * or values with default types (like color)
3380
- *
3381
- * TODO: CSS variable support
3382
- */
3383
- const updateStyle = () => {
3384
- element.style[key] = value.get();
3385
- };
3386
- const scheduleUpdate = () => frame.render(updateStyle);
3387
- const cancel = value.on("change", scheduleUpdate);
3388
- scheduleUpdate();
3389
- subscriptions.push(() => {
3390
- cancel();
3391
- cancelFrame(updateStyle);
3392
- });
3393
- }
3394
- }
3395
- return () => {
3396
- for (const cancel of subscriptions) {
3397
- cancel();
3398
- }
3399
- };
3400
- }
3401
-
3402
- const { schedule: microtask, cancel: cancelMicrotask } =
3403
- /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
3404
-
3405
- const isDragging = {
3406
- x: false,
3407
- y: false,
3408
- };
3409
- function isDragActive() {
3410
- return isDragging.x || isDragging.y;
3411
- }
3412
-
3413
- function setDragLock(axis) {
3414
- if (axis === "x" || axis === "y") {
3415
- if (isDragging[axis]) {
3416
- return null;
3417
- }
3418
- else {
3419
- isDragging[axis] = true;
3420
- return () => {
3421
- isDragging[axis] = false;
3422
- };
3423
- }
3424
- }
3425
- else {
3426
- if (isDragging.x || isDragging.y) {
3427
- return null;
3428
- }
3429
- else {
3430
- isDragging.x = isDragging.y = true;
3431
- return () => {
3432
- isDragging.x = isDragging.y = false;
3433
- };
3434
- }
3435
- }
3436
- }
3437
-
3438
- function setupGesture(elementOrSelector, options) {
3439
- const elements = resolveElements(elementOrSelector);
3440
- const gestureAbortController = new AbortController();
3441
- const eventOptions = {
3442
- passive: true,
3443
- ...options,
3444
- signal: gestureAbortController.signal,
3445
- };
3446
- const cancel = () => gestureAbortController.abort();
3447
- return [elements, eventOptions, cancel];
3448
- }
3449
-
3450
- function isValidHover(event) {
3451
- return !(event.pointerType === "touch" || isDragActive());
3452
- }
3453
- /**
3454
- * Create a hover gesture. hover() is different to .addEventListener("pointerenter")
3455
- * in that it has an easier syntax, filters out polyfilled touch events, interoperates
3456
- * with drag gestures, and automatically removes the "pointerennd" event listener when the hover ends.
3457
- *
3458
- * @public
3459
- */
3460
- function hover(elementOrSelector, onHoverStart, options = {}) {
3461
- const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options);
3462
- const onPointerEnter = (enterEvent) => {
3463
- if (!isValidHover(enterEvent))
3464
- return;
3465
- const { target } = enterEvent;
3466
- const onHoverEnd = onHoverStart(target, enterEvent);
3467
- if (typeof onHoverEnd !== "function" || !target)
3468
- return;
3469
- const onPointerLeave = (leaveEvent) => {
3470
- if (!isValidHover(leaveEvent))
3471
- return;
3472
- onHoverEnd(leaveEvent);
3473
- target.removeEventListener("pointerleave", onPointerLeave);
3474
- };
3475
- target.addEventListener("pointerleave", onPointerLeave, eventOptions);
3476
- };
3477
- elements.forEach((element) => {
3478
- element.addEventListener("pointerenter", onPointerEnter, eventOptions);
3479
- });
3480
- return cancel;
3481
- }
3482
-
3483
- /**
3484
- * Recursively traverse up the tree to check whether the provided child node
3485
- * is the parent or a descendant of it.
3486
- *
3487
- * @param parent - Element to find
3488
- * @param child - Element to test against parent
3489
- */
3490
- const isNodeOrChild = (parent, child) => {
3491
- if (!child) {
3492
- return false;
3493
- }
3494
- else if (parent === child) {
3495
- return true;
3496
- }
3497
- else {
3498
- return isNodeOrChild(parent, child.parentElement);
3499
- }
3500
- };
3501
-
3502
- const isPrimaryPointer = (event) => {
3503
- if (event.pointerType === "mouse") {
3504
- return typeof event.button !== "number" || event.button <= 0;
3505
- }
3506
- else {
3507
- /**
3508
- * isPrimary is true for all mice buttons, whereas every touch point
3509
- * is regarded as its own input. So subsequent concurrent touch points
3510
- * will be false.
3511
- *
3512
- * Specifically match against false here as incomplete versions of
3513
- * PointerEvents in very old browser might have it set as undefined.
3514
- */
3515
- return event.isPrimary !== false;
3516
- }
3517
- };
3518
-
3519
- const focusableElements = new Set([
3520
- "BUTTON",
3521
- "INPUT",
3522
- "SELECT",
3523
- "TEXTAREA",
3524
- "A",
3525
- ]);
3526
- function isElementKeyboardAccessible(element) {
3527
- return (focusableElements.has(element.tagName) ||
3528
- element.tabIndex !== -1);
3529
- }
3530
-
3531
- const isPressing = new WeakSet();
3532
-
3533
- /**
3534
- * Filter out events that are not "Enter" keys.
3535
- */
3536
- function filterEvents(callback) {
3537
- return (event) => {
3538
- if (event.key !== "Enter")
3539
- return;
3540
- callback(event);
3541
- };
3542
- }
3543
- function firePointerEvent(target, type) {
3544
- target.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true }));
3545
- }
3546
- const enableKeyboardPress = (focusEvent, eventOptions) => {
3547
- const element = focusEvent.currentTarget;
3548
- if (!element)
3549
- return;
3550
- const handleKeydown = filterEvents(() => {
3551
- if (isPressing.has(element))
3552
- return;
3553
- firePointerEvent(element, "down");
3554
- const handleKeyup = filterEvents(() => {
3555
- firePointerEvent(element, "up");
3556
- });
3557
- const handleBlur = () => firePointerEvent(element, "cancel");
3558
- element.addEventListener("keyup", handleKeyup, eventOptions);
3559
- element.addEventListener("blur", handleBlur, eventOptions);
3560
- });
3561
- element.addEventListener("keydown", handleKeydown, eventOptions);
3562
- /**
3563
- * Add an event listener that fires on blur to remove the keydown events.
3564
- */
3565
- element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions);
3566
- };
3567
-
3568
- /**
3569
- * Filter out events that are not primary pointer events, or are triggering
3570
- * while a Motion gesture is active.
3571
- */
3572
- function isValidPressEvent(event) {
3573
- return isPrimaryPointer(event) && !isDragActive();
3574
- }
3575
- /**
3576
- * Create a press gesture.
3577
- *
3578
- * Press is different to `"pointerdown"`, `"pointerup"` in that it
3579
- * automatically filters out secondary pointer events like right
3580
- * click and multitouch.
3581
- *
3582
- * It also adds accessibility support for keyboards, where
3583
- * an element with a press gesture will receive focus and
3584
- * trigger on Enter `"keydown"` and `"keyup"` events.
3585
- *
3586
- * This is different to a browser's `"click"` event, which does
3587
- * respond to keyboards but only for the `"click"` itself, rather
3588
- * than the press start and end/cancel. The element also needs
3589
- * to be focusable for this to work, whereas a press gesture will
3590
- * make an element focusable by default.
3591
- *
3592
- * @public
3593
- */
3594
- function press(targetOrSelector, onPressStart, options = {}) {
3595
- const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);
3596
- const startPress = (startEvent) => {
3597
- const target = startEvent.currentTarget;
3598
- if (!isValidPressEvent(startEvent) || isPressing.has(target))
3599
- return;
3600
- isPressing.add(target);
3601
- const onPressEnd = onPressStart(target, startEvent);
3602
- const onPointerEnd = (endEvent, success) => {
3603
- window.removeEventListener("pointerup", onPointerUp);
3604
- window.removeEventListener("pointercancel", onPointerCancel);
3605
- if (!isValidPressEvent(endEvent) || !isPressing.has(target)) {
3606
- return;
3607
- }
3608
- isPressing.delete(target);
3609
- if (typeof onPressEnd === "function") {
3610
- onPressEnd(endEvent, { success });
3611
- }
3612
- };
3613
- const onPointerUp = (upEvent) => {
3614
- onPointerEnd(upEvent, target === window ||
3615
- target === document ||
3616
- options.useGlobalTarget ||
3617
- isNodeOrChild(target, upEvent.target));
3618
- };
3619
- const onPointerCancel = (cancelEvent) => {
3620
- onPointerEnd(cancelEvent, false);
3621
- };
3622
- window.addEventListener("pointerup", onPointerUp, eventOptions);
3623
- window.addEventListener("pointercancel", onPointerCancel, eventOptions);
3624
- };
3625
- targets.forEach((target) => {
3626
- const pointerDownTarget = options.useGlobalTarget ? window : target;
3627
- pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions);
3628
- if (target instanceof HTMLElement) {
3629
- target.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions));
3630
- if (!isElementKeyboardAccessible(target) &&
3631
- !target.hasAttribute("tabindex")) {
3632
- target.tabIndex = 0;
3633
- }
3634
- }
3635
- });
3636
- return cancelEvents;
3637
- }
3638
-
3639
- function getComputedStyle$2(element, name) {
3640
- const computedStyle = window.getComputedStyle(element);
3641
- return isCSSVar(name)
3642
- ? computedStyle.getPropertyValue(name)
3643
- : computedStyle[name];
3644
- }
3645
-
3646
- function observeTimeline(update, timeline) {
3647
- let prevProgress;
3648
- const onFrame = () => {
3649
- const { currentTime } = timeline;
3650
- const percentage = currentTime === null ? 0 : currentTime.value;
3651
- const progress = percentage / 100;
3652
- if (prevProgress !== progress) {
3653
- update(progress);
3654
- }
3655
- prevProgress = progress;
3656
- };
3657
- frame.preUpdate(onFrame, true);
3658
- return () => cancelFrame(onFrame);
3659
- }
3660
-
3661
- function record() {
3662
- const { value } = statsBuffer;
3663
- if (value === null) {
3664
- cancelFrame(record);
3665
- return;
3666
- }
3667
- value.frameloop.rate.push(frameData.delta);
3668
- value.animations.mainThread.push(activeAnimations.mainThread);
3669
- value.animations.waapi.push(activeAnimations.waapi);
3670
- value.animations.layout.push(activeAnimations.layout);
3671
- }
3672
- function mean(values) {
3673
- return values.reduce((acc, value) => acc + value, 0) / values.length;
3674
- }
3675
- function summarise(values, calcAverage = mean) {
3676
- if (values.length === 0) {
3677
- return {
3678
- min: 0,
3679
- max: 0,
3680
- avg: 0,
3681
- };
3682
- }
3683
- return {
3684
- min: Math.min(...values),
3685
- max: Math.max(...values),
3686
- avg: calcAverage(values),
3687
- };
3688
- }
3689
- const msToFps = (ms) => Math.round(1000 / ms);
3690
- function clearStatsBuffer() {
3691
- statsBuffer.value = null;
3692
- statsBuffer.addProjectionMetrics = null;
3693
- }
3694
- function reportStats() {
3695
- const { value } = statsBuffer;
3696
- if (!value) {
3697
- throw new Error("Stats are not being measured");
3698
- }
3699
- clearStatsBuffer();
3700
- cancelFrame(record);
3701
- const summary = {
3702
- frameloop: {
3703
- setup: summarise(value.frameloop.setup),
3704
- rate: summarise(value.frameloop.rate),
3705
- read: summarise(value.frameloop.read),
3706
- resolveKeyframes: summarise(value.frameloop.resolveKeyframes),
3707
- preUpdate: summarise(value.frameloop.preUpdate),
3708
- update: summarise(value.frameloop.update),
3709
- preRender: summarise(value.frameloop.preRender),
3710
- render: summarise(value.frameloop.render),
3711
- postRender: summarise(value.frameloop.postRender),
3712
- },
3713
- animations: {
3714
- mainThread: summarise(value.animations.mainThread),
3715
- waapi: summarise(value.animations.waapi),
3716
- layout: summarise(value.animations.layout),
3717
- },
3718
- layoutProjection: {
3719
- nodes: summarise(value.layoutProjection.nodes),
3720
- calculatedTargetDeltas: summarise(value.layoutProjection.calculatedTargetDeltas),
3721
- calculatedProjections: summarise(value.layoutProjection.calculatedProjections),
3722
- },
3723
- };
3724
- /**
3725
- * Convert the rate to FPS
3726
- */
3727
- const { rate } = summary.frameloop;
3728
- rate.min = msToFps(rate.min);
3729
- rate.max = msToFps(rate.max);
3730
- rate.avg = msToFps(rate.avg);
3731
- [rate.min, rate.max] = [rate.max, rate.min];
3732
- return summary;
3733
- }
3734
- function recordStats() {
3735
- if (statsBuffer.value) {
3736
- clearStatsBuffer();
3737
- throw new Error("Stats are already being measured");
3738
- }
3739
- const newStatsBuffer = statsBuffer;
3740
- newStatsBuffer.value = {
3741
- frameloop: {
3742
- setup: [],
3743
- rate: [],
3744
- read: [],
3745
- resolveKeyframes: [],
3746
- preUpdate: [],
3747
- update: [],
3748
- preRender: [],
3749
- render: [],
3750
- postRender: [],
3751
- },
3752
- animations: {
3753
- mainThread: [],
3754
- waapi: [],
3755
- layout: [],
3756
- },
3757
- layoutProjection: {
3758
- nodes: [],
3759
- calculatedTargetDeltas: [],
3760
- calculatedProjections: [],
3761
- },
3762
- };
3763
- newStatsBuffer.addProjectionMetrics = (metrics) => {
3764
- const { layoutProjection } = newStatsBuffer.value;
3765
- layoutProjection.nodes.push(metrics.nodes);
3766
- layoutProjection.calculatedTargetDeltas.push(metrics.calculatedTargetDeltas);
3767
- layoutProjection.calculatedProjections.push(metrics.calculatedProjections);
3768
- };
3769
- frame.postRender(record, true);
3770
- return reportStats;
3771
- }
3772
-
3773
- function transform(...args) {
3774
- const useImmediate = !Array.isArray(args[0]);
3775
- const argOffset = useImmediate ? 0 : -1;
3776
- const inputValue = args[0 + argOffset];
3777
- const inputRange = args[1 + argOffset];
3778
- const outputRange = args[2 + argOffset];
3779
- const options = args[3 + argOffset];
3780
- const interpolator = interpolate(inputRange, outputRange, options);
3781
- return useImmediate ? interpolator(inputValue) : interpolator;
3782
- }
3783
-
3784
3370
  /**
3785
3371
  * Maximum time between the value of two frames, beyond which we
3786
3372
  * assume the velocity has since been 0.
@@ -3799,293 +3385,820 @@
3799
3385
  */
3800
3386
  class MotionValue {
3801
3387
  /**
3802
- * @param init - The initiating value
3803
- * @param config - Optional configuration options
3388
+ * @param init - The initiating value
3389
+ * @param config - Optional configuration options
3390
+ *
3391
+ * - `transformer`: A function to transform incoming values with.
3392
+ */
3393
+ constructor(init, options = {}) {
3394
+ /**
3395
+ * This will be replaced by the build step with the latest version number.
3396
+ * When MotionValues are provided to motion components, warn if versions are mixed.
3397
+ */
3398
+ this.version = "__VERSION__";
3399
+ /**
3400
+ * Tracks whether this value can output a velocity. Currently this is only true
3401
+ * if the value is numerical, but we might be able to widen the scope here and support
3402
+ * other value types.
3403
+ *
3404
+ * @internal
3405
+ */
3406
+ this.canTrackVelocity = null;
3407
+ /**
3408
+ * An object containing a SubscriptionManager for each active event.
3409
+ */
3410
+ this.events = {};
3411
+ this.updateAndNotify = (v, render = true) => {
3412
+ const currentTime = time.now();
3413
+ /**
3414
+ * If we're updating the value during another frame or eventloop
3415
+ * than the previous frame, then the we set the previous frame value
3416
+ * to current.
3417
+ */
3418
+ if (this.updatedAt !== currentTime) {
3419
+ this.setPrevFrameValue();
3420
+ }
3421
+ this.prev = this.current;
3422
+ this.setCurrent(v);
3423
+ // Update update subscribers
3424
+ if (this.current !== this.prev) {
3425
+ this.events.change?.notify(this.current);
3426
+ if (this.dependents) {
3427
+ for (const dependent of this.dependents) {
3428
+ dependent.dirty();
3429
+ }
3430
+ }
3431
+ }
3432
+ // Update render subscribers
3433
+ if (render) {
3434
+ this.events.renderRequest?.notify(this.current);
3435
+ }
3436
+ };
3437
+ this.hasAnimated = false;
3438
+ this.setCurrent(init);
3439
+ this.owner = options.owner;
3440
+ }
3441
+ setCurrent(current) {
3442
+ this.current = current;
3443
+ this.updatedAt = time.now();
3444
+ if (this.canTrackVelocity === null && current !== undefined) {
3445
+ this.canTrackVelocity = isFloat(this.current);
3446
+ }
3447
+ }
3448
+ setPrevFrameValue(prevFrameValue = this.current) {
3449
+ this.prevFrameValue = prevFrameValue;
3450
+ this.prevUpdatedAt = this.updatedAt;
3451
+ }
3452
+ /**
3453
+ * Adds a function that will be notified when the `MotionValue` is updated.
3454
+ *
3455
+ * It returns a function that, when called, will cancel the subscription.
3456
+ *
3457
+ * When calling `onChange` inside a React component, it should be wrapped with the
3458
+ * `useEffect` hook. As it returns an unsubscribe function, this should be returned
3459
+ * from the `useEffect` function to ensure you don't add duplicate subscribers..
3460
+ *
3461
+ * ```jsx
3462
+ * export const MyComponent = () => {
3463
+ * const x = useMotionValue(0)
3464
+ * const y = useMotionValue(0)
3465
+ * const opacity = useMotionValue(1)
3466
+ *
3467
+ * useEffect(() => {
3468
+ * function updateOpacity() {
3469
+ * const maxXY = Math.max(x.get(), y.get())
3470
+ * const newOpacity = transform(maxXY, [0, 100], [1, 0])
3471
+ * opacity.set(newOpacity)
3472
+ * }
3473
+ *
3474
+ * const unsubscribeX = x.on("change", updateOpacity)
3475
+ * const unsubscribeY = y.on("change", updateOpacity)
3476
+ *
3477
+ * return () => {
3478
+ * unsubscribeX()
3479
+ * unsubscribeY()
3480
+ * }
3481
+ * }, [])
3482
+ *
3483
+ * return <motion.div style={{ x }} />
3484
+ * }
3485
+ * ```
3486
+ *
3487
+ * @param subscriber - A function that receives the latest value.
3488
+ * @returns A function that, when called, will cancel this subscription.
3489
+ *
3490
+ * @deprecated
3491
+ */
3492
+ onChange(subscription) {
3493
+ {
3494
+ warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on("change", callback).`);
3495
+ }
3496
+ return this.on("change", subscription);
3497
+ }
3498
+ on(eventName, callback) {
3499
+ if (!this.events[eventName]) {
3500
+ this.events[eventName] = new SubscriptionManager();
3501
+ }
3502
+ const unsubscribe = this.events[eventName].add(callback);
3503
+ if (eventName === "change") {
3504
+ return () => {
3505
+ unsubscribe();
3506
+ /**
3507
+ * If we have no more change listeners by the start
3508
+ * of the next frame, stop active animations.
3509
+ */
3510
+ frame.read(() => {
3511
+ if (!this.events.change.getSize()) {
3512
+ this.stop();
3513
+ }
3514
+ });
3515
+ };
3516
+ }
3517
+ return unsubscribe;
3518
+ }
3519
+ clearListeners() {
3520
+ for (const eventManagers in this.events) {
3521
+ this.events[eventManagers].clear();
3522
+ }
3523
+ }
3524
+ /**
3525
+ * Attaches a passive effect to the `MotionValue`.
3526
+ */
3527
+ attach(passiveEffect, stopPassiveEffect) {
3528
+ this.passiveEffect = passiveEffect;
3529
+ this.stopPassiveEffect = stopPassiveEffect;
3530
+ }
3531
+ /**
3532
+ * Sets the state of the `MotionValue`.
3533
+ *
3534
+ * @remarks
3535
+ *
3536
+ * ```jsx
3537
+ * const x = useMotionValue(0)
3538
+ * x.set(10)
3539
+ * ```
3540
+ *
3541
+ * @param latest - Latest value to set.
3542
+ * @param render - Whether to notify render subscribers. Defaults to `true`
3543
+ *
3544
+ * @public
3545
+ */
3546
+ set(v, render = true) {
3547
+ if (!render || !this.passiveEffect) {
3548
+ this.updateAndNotify(v, render);
3549
+ }
3550
+ else {
3551
+ this.passiveEffect(v, this.updateAndNotify);
3552
+ }
3553
+ }
3554
+ setWithVelocity(prev, current, delta) {
3555
+ this.set(current);
3556
+ this.prev = undefined;
3557
+ this.prevFrameValue = prev;
3558
+ this.prevUpdatedAt = this.updatedAt - delta;
3559
+ }
3560
+ /**
3561
+ * Set the state of the `MotionValue`, stopping any active animations,
3562
+ * effects, and resets velocity to `0`.
3563
+ */
3564
+ jump(v, endAnimation = true) {
3565
+ this.updateAndNotify(v);
3566
+ this.prev = v;
3567
+ this.prevUpdatedAt = this.prevFrameValue = undefined;
3568
+ endAnimation && this.stop();
3569
+ if (this.stopPassiveEffect)
3570
+ this.stopPassiveEffect();
3571
+ }
3572
+ dirty() {
3573
+ this.events.change?.notify(this.current);
3574
+ }
3575
+ addDependent(dependent) {
3576
+ if (!this.dependents) {
3577
+ this.dependents = new Set();
3578
+ }
3579
+ this.dependents.add(dependent);
3580
+ }
3581
+ removeDependent(dependent) {
3582
+ if (this.dependents) {
3583
+ this.dependents.delete(dependent);
3584
+ }
3585
+ }
3586
+ /**
3587
+ * Returns the latest state of `MotionValue`
3804
3588
  *
3805
- * - `transformer`: A function to transform incoming values with.
3589
+ * @returns - The latest state of `MotionValue`
3590
+ *
3591
+ * @public
3806
3592
  */
3807
- constructor(init, options = {}) {
3808
- /**
3809
- * This will be replaced by the build step with the latest version number.
3810
- * When MotionValues are provided to motion components, warn if versions are mixed.
3811
- */
3812
- this.version = "__VERSION__";
3813
- /**
3814
- * Tracks whether this value can output a velocity. Currently this is only true
3815
- * if the value is numerical, but we might be able to widen the scope here and support
3816
- * other value types.
3817
- *
3818
- * @internal
3819
- */
3820
- this.canTrackVelocity = null;
3821
- /**
3822
- * An object containing a SubscriptionManager for each active event.
3823
- */
3824
- this.events = {};
3825
- this.updateAndNotify = (v, render = true) => {
3826
- const currentTime = time.now();
3827
- /**
3828
- * If we're updating the value during another frame or eventloop
3829
- * than the previous frame, then the we set the previous frame value
3830
- * to current.
3831
- */
3832
- if (this.updatedAt !== currentTime) {
3833
- this.setPrevFrameValue();
3834
- }
3835
- this.prev = this.current;
3836
- this.setCurrent(v);
3837
- // Update update subscribers
3838
- if (this.current !== this.prev) {
3839
- this.events.change?.notify(this.current);
3840
- }
3841
- // Update render subscribers
3842
- if (render) {
3843
- this.events.renderRequest?.notify(this.current);
3844
- }
3845
- };
3846
- this.hasAnimated = false;
3847
- this.setCurrent(init);
3848
- this.owner = options.owner;
3849
- }
3850
- setCurrent(current) {
3851
- this.current = current;
3852
- this.updatedAt = time.now();
3853
- if (this.canTrackVelocity === null && current !== undefined) {
3854
- this.canTrackVelocity = isFloat(this.current);
3593
+ get() {
3594
+ if (collectMotionValues.current) {
3595
+ collectMotionValues.current.push(this);
3855
3596
  }
3597
+ return this.current;
3856
3598
  }
3857
- setPrevFrameValue(prevFrameValue = this.current) {
3858
- this.prevFrameValue = prevFrameValue;
3859
- this.prevUpdatedAt = this.updatedAt;
3599
+ /**
3600
+ * @public
3601
+ */
3602
+ getPrevious() {
3603
+ return this.prev;
3860
3604
  }
3861
3605
  /**
3862
- * Adds a function that will be notified when the `MotionValue` is updated.
3606
+ * Returns the latest velocity of `MotionValue`
3863
3607
  *
3864
- * It returns a function that, when called, will cancel the subscription.
3608
+ * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.
3865
3609
  *
3866
- * When calling `onChange` inside a React component, it should be wrapped with the
3867
- * `useEffect` hook. As it returns an unsubscribe function, this should be returned
3868
- * from the `useEffect` function to ensure you don't add duplicate subscribers..
3610
+ * @public
3611
+ */
3612
+ getVelocity() {
3613
+ const currentTime = time.now();
3614
+ if (!this.canTrackVelocity ||
3615
+ this.prevFrameValue === undefined ||
3616
+ currentTime - this.updatedAt > MAX_VELOCITY_DELTA) {
3617
+ return 0;
3618
+ }
3619
+ const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA);
3620
+ // Casts because of parseFloat's poor typing
3621
+ return velocityPerSecond(parseFloat(this.current) -
3622
+ parseFloat(this.prevFrameValue), delta);
3623
+ }
3624
+ /**
3625
+ * Registers a new animation to control this `MotionValue`. Only one
3626
+ * animation can drive a `MotionValue` at one time.
3869
3627
  *
3870
3628
  * ```jsx
3871
- * export const MyComponent = () => {
3872
- * const x = useMotionValue(0)
3873
- * const y = useMotionValue(0)
3874
- * const opacity = useMotionValue(1)
3875
- *
3876
- * useEffect(() => {
3877
- * function updateOpacity() {
3878
- * const maxXY = Math.max(x.get(), y.get())
3879
- * const newOpacity = transform(maxXY, [0, 100], [1, 0])
3880
- * opacity.set(newOpacity)
3881
- * }
3629
+ * value.start()
3630
+ * ```
3882
3631
  *
3883
- * const unsubscribeX = x.on("change", updateOpacity)
3884
- * const unsubscribeY = y.on("change", updateOpacity)
3632
+ * @param animation - A function that starts the provided animation
3633
+ */
3634
+ start(startAnimation) {
3635
+ this.stop();
3636
+ return new Promise((resolve) => {
3637
+ this.hasAnimated = true;
3638
+ this.animation = startAnimation(resolve);
3639
+ if (this.events.animationStart) {
3640
+ this.events.animationStart.notify();
3641
+ }
3642
+ }).then(() => {
3643
+ if (this.events.animationComplete) {
3644
+ this.events.animationComplete.notify();
3645
+ }
3646
+ this.clearAnimation();
3647
+ });
3648
+ }
3649
+ /**
3650
+ * Stop the currently active animation.
3885
3651
  *
3886
- * return () => {
3887
- * unsubscribeX()
3888
- * unsubscribeY()
3889
- * }
3890
- * }, [])
3652
+ * @public
3653
+ */
3654
+ stop() {
3655
+ if (this.animation) {
3656
+ this.animation.stop();
3657
+ if (this.events.animationCancel) {
3658
+ this.events.animationCancel.notify();
3659
+ }
3660
+ }
3661
+ this.clearAnimation();
3662
+ }
3663
+ /**
3664
+ * Returns `true` if this value is currently animating.
3891
3665
  *
3892
- * return <motion.div style={{ x }} />
3893
- * }
3894
- * ```
3666
+ * @public
3667
+ */
3668
+ isAnimating() {
3669
+ return !!this.animation;
3670
+ }
3671
+ clearAnimation() {
3672
+ delete this.animation;
3673
+ }
3674
+ /**
3675
+ * Destroy and clean up subscribers to this `MotionValue`.
3895
3676
  *
3896
- * @param subscriber - A function that receives the latest value.
3897
- * @returns A function that, when called, will cancel this subscription.
3677
+ * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
3678
+ * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
3679
+ * created a `MotionValue` via the `motionValue` function.
3898
3680
  *
3899
- * @deprecated
3681
+ * @public
3900
3682
  */
3901
- onChange(subscription) {
3902
- {
3903
- warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on("change", callback).`);
3683
+ destroy() {
3684
+ this.dependents?.clear();
3685
+ this.events.destroy?.notify();
3686
+ this.clearListeners();
3687
+ this.stop();
3688
+ if (this.stopPassiveEffect) {
3689
+ this.stopPassiveEffect();
3904
3690
  }
3905
- return this.on("change", subscription);
3906
3691
  }
3907
- on(eventName, callback) {
3908
- if (!this.events[eventName]) {
3909
- this.events[eventName] = new SubscriptionManager();
3692
+ }
3693
+ function motionValue(init, options) {
3694
+ return new MotionValue(init, options);
3695
+ }
3696
+
3697
+ /**
3698
+ * Provided a value and a ValueType, returns the value as that value type.
3699
+ */
3700
+ const getValueAsType = (value, type) => {
3701
+ return type && typeof value === "number"
3702
+ ? type.transform(value)
3703
+ : value;
3704
+ };
3705
+
3706
+ class MotionValueState {
3707
+ constructor() {
3708
+ this.latest = {};
3709
+ this.values = new Map();
3710
+ }
3711
+ set(name, value, render, computed) {
3712
+ const existingValue = this.values.get(name);
3713
+ if (existingValue) {
3714
+ existingValue.onRemove();
3715
+ }
3716
+ const onChange = () => {
3717
+ this.latest[name] = getValueAsType(value.get(), numberValueTypes[name]);
3718
+ render && frame.render(render);
3719
+ };
3720
+ onChange();
3721
+ const cancelOnChange = value.on("change", onChange);
3722
+ computed && value.addDependent(computed);
3723
+ const remove = () => {
3724
+ cancelOnChange();
3725
+ render && cancelFrame(render);
3726
+ this.values.delete(name);
3727
+ computed && value.removeDependent(computed);
3728
+ };
3729
+ this.values.set(name, { value, onRemove: remove });
3730
+ return remove;
3731
+ }
3732
+ get(name) {
3733
+ return this.values.get(name)?.value;
3734
+ }
3735
+ destroy() {
3736
+ for (const value of this.values.values()) {
3737
+ value.onRemove();
3738
+ }
3739
+ }
3740
+ }
3741
+
3742
+ const translateAlias$1 = {
3743
+ x: "translateX",
3744
+ y: "translateY",
3745
+ z: "translateZ",
3746
+ transformPerspective: "perspective",
3747
+ };
3748
+ function buildTransform$1(state) {
3749
+ let transform = "";
3750
+ let transformIsDefault = true;
3751
+ /**
3752
+ * Loop over all possible transforms in order, adding the ones that
3753
+ * are present to the transform string.
3754
+ */
3755
+ for (let i = 0; i < transformPropOrder.length; i++) {
3756
+ const key = transformPropOrder[i];
3757
+ const value = state.latest[key];
3758
+ if (value === undefined)
3759
+ continue;
3760
+ let valueIsDefault = true;
3761
+ if (typeof value === "number") {
3762
+ valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
3763
+ }
3764
+ else {
3765
+ valueIsDefault = parseFloat(value) === 0;
3766
+ }
3767
+ if (!valueIsDefault) {
3768
+ transformIsDefault = false;
3769
+ const transformName = translateAlias$1[key] || key;
3770
+ const valueToRender = state.latest[key];
3771
+ transform += `${transformName}(${valueToRender}) `;
3772
+ }
3773
+ }
3774
+ return transformIsDefault ? "none" : transform.trim();
3775
+ }
3776
+
3777
+ const stateMap = new WeakMap();
3778
+ function styleEffect(subject, values) {
3779
+ const elements = resolveElements(subject);
3780
+ const subscriptions = [];
3781
+ for (let i = 0; i < elements.length; i++) {
3782
+ const element = elements[i];
3783
+ const state = stateMap.get(element) ?? new MotionValueState();
3784
+ stateMap.set(element, state);
3785
+ for (const key in values) {
3786
+ const value = values[key];
3787
+ const remove = addValue(element, state, key, value);
3788
+ subscriptions.push(remove);
3789
+ }
3790
+ }
3791
+ return () => {
3792
+ for (const cancel of subscriptions)
3793
+ cancel();
3794
+ };
3795
+ }
3796
+ function addValue(element, state, key, value) {
3797
+ let render = undefined;
3798
+ let computed = undefined;
3799
+ if (transformProps.has(key)) {
3800
+ if (!state.get("transform")) {
3801
+ state.set("transform", new MotionValue("none"), () => {
3802
+ element.style.transform = buildTransform$1(state);
3803
+ });
3804
+ }
3805
+ computed = state.get("transform");
3806
+ }
3807
+ else if (isCSSVar(key)) {
3808
+ render = () => {
3809
+ element.style.setProperty(key, state.latest[key]);
3810
+ };
3811
+ }
3812
+ else {
3813
+ render = () => {
3814
+ element.style[key] = state.latest[key];
3815
+ };
3816
+ }
3817
+ return state.set(key, value, render, computed);
3818
+ }
3819
+
3820
+ const { schedule: microtask, cancel: cancelMicrotask } =
3821
+ /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
3822
+
3823
+ const isDragging = {
3824
+ x: false,
3825
+ y: false,
3826
+ };
3827
+ function isDragActive() {
3828
+ return isDragging.x || isDragging.y;
3829
+ }
3830
+
3831
+ function setDragLock(axis) {
3832
+ if (axis === "x" || axis === "y") {
3833
+ if (isDragging[axis]) {
3834
+ return null;
3910
3835
  }
3911
- const unsubscribe = this.events[eventName].add(callback);
3912
- if (eventName === "change") {
3836
+ else {
3837
+ isDragging[axis] = true;
3913
3838
  return () => {
3914
- unsubscribe();
3915
- /**
3916
- * If we have no more change listeners by the start
3917
- * of the next frame, stop active animations.
3918
- */
3919
- frame.read(() => {
3920
- if (!this.events.change.getSize()) {
3921
- this.stop();
3922
- }
3923
- });
3839
+ isDragging[axis] = false;
3924
3840
  };
3925
3841
  }
3926
- return unsubscribe;
3927
- }
3928
- clearListeners() {
3929
- for (const eventManagers in this.events) {
3930
- this.events[eventManagers].clear();
3931
- }
3932
- }
3933
- /**
3934
- * Attaches a passive effect to the `MotionValue`.
3935
- */
3936
- attach(passiveEffect, stopPassiveEffect) {
3937
- this.passiveEffect = passiveEffect;
3938
- this.stopPassiveEffect = stopPassiveEffect;
3939
3842
  }
3940
- /**
3941
- * Sets the state of the `MotionValue`.
3942
- *
3943
- * @remarks
3944
- *
3945
- * ```jsx
3946
- * const x = useMotionValue(0)
3947
- * x.set(10)
3948
- * ```
3949
- *
3950
- * @param latest - Latest value to set.
3951
- * @param render - Whether to notify render subscribers. Defaults to `true`
3952
- *
3953
- * @public
3954
- */
3955
- set(v, render = true) {
3956
- if (!render || !this.passiveEffect) {
3957
- this.updateAndNotify(v, render);
3843
+ else {
3844
+ if (isDragging.x || isDragging.y) {
3845
+ return null;
3958
3846
  }
3959
3847
  else {
3960
- this.passiveEffect(v, this.updateAndNotify);
3848
+ isDragging.x = isDragging.y = true;
3849
+ return () => {
3850
+ isDragging.x = isDragging.y = false;
3851
+ };
3961
3852
  }
3962
3853
  }
3963
- setWithVelocity(prev, current, delta) {
3964
- this.set(current);
3965
- this.prev = undefined;
3966
- this.prevFrameValue = prev;
3967
- this.prevUpdatedAt = this.updatedAt - delta;
3854
+ }
3855
+
3856
+ function setupGesture(elementOrSelector, options) {
3857
+ const elements = resolveElements(elementOrSelector);
3858
+ const gestureAbortController = new AbortController();
3859
+ const eventOptions = {
3860
+ passive: true,
3861
+ ...options,
3862
+ signal: gestureAbortController.signal,
3863
+ };
3864
+ const cancel = () => gestureAbortController.abort();
3865
+ return [elements, eventOptions, cancel];
3866
+ }
3867
+
3868
+ function isValidHover(event) {
3869
+ return !(event.pointerType === "touch" || isDragActive());
3870
+ }
3871
+ /**
3872
+ * Create a hover gesture. hover() is different to .addEventListener("pointerenter")
3873
+ * in that it has an easier syntax, filters out polyfilled touch events, interoperates
3874
+ * with drag gestures, and automatically removes the "pointerennd" event listener when the hover ends.
3875
+ *
3876
+ * @public
3877
+ */
3878
+ function hover(elementOrSelector, onHoverStart, options = {}) {
3879
+ const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options);
3880
+ const onPointerEnter = (enterEvent) => {
3881
+ if (!isValidHover(enterEvent))
3882
+ return;
3883
+ const { target } = enterEvent;
3884
+ const onHoverEnd = onHoverStart(target, enterEvent);
3885
+ if (typeof onHoverEnd !== "function" || !target)
3886
+ return;
3887
+ const onPointerLeave = (leaveEvent) => {
3888
+ if (!isValidHover(leaveEvent))
3889
+ return;
3890
+ onHoverEnd(leaveEvent);
3891
+ target.removeEventListener("pointerleave", onPointerLeave);
3892
+ };
3893
+ target.addEventListener("pointerleave", onPointerLeave, eventOptions);
3894
+ };
3895
+ elements.forEach((element) => {
3896
+ element.addEventListener("pointerenter", onPointerEnter, eventOptions);
3897
+ });
3898
+ return cancel;
3899
+ }
3900
+
3901
+ /**
3902
+ * Recursively traverse up the tree to check whether the provided child node
3903
+ * is the parent or a descendant of it.
3904
+ *
3905
+ * @param parent - Element to find
3906
+ * @param child - Element to test against parent
3907
+ */
3908
+ const isNodeOrChild = (parent, child) => {
3909
+ if (!child) {
3910
+ return false;
3968
3911
  }
3969
- /**
3970
- * Set the state of the `MotionValue`, stopping any active animations,
3971
- * effects, and resets velocity to `0`.
3972
- */
3973
- jump(v, endAnimation = true) {
3974
- this.updateAndNotify(v);
3975
- this.prev = v;
3976
- this.prevUpdatedAt = this.prevFrameValue = undefined;
3977
- endAnimation && this.stop();
3978
- if (this.stopPassiveEffect)
3979
- this.stopPassiveEffect();
3912
+ else if (parent === child) {
3913
+ return true;
3980
3914
  }
3981
- /**
3982
- * Returns the latest state of `MotionValue`
3983
- *
3984
- * @returns - The latest state of `MotionValue`
3985
- *
3986
- * @public
3987
- */
3988
- get() {
3989
- if (collectMotionValues.current) {
3990
- collectMotionValues.current.push(this);
3991
- }
3992
- return this.current;
3915
+ else {
3916
+ return isNodeOrChild(parent, child.parentElement);
3993
3917
  }
3994
- /**
3995
- * @public
3996
- */
3997
- getPrevious() {
3998
- return this.prev;
3918
+ };
3919
+
3920
+ const isPrimaryPointer = (event) => {
3921
+ if (event.pointerType === "mouse") {
3922
+ return typeof event.button !== "number" || event.button <= 0;
3999
3923
  }
4000
- /**
4001
- * Returns the latest velocity of `MotionValue`
4002
- *
4003
- * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.
4004
- *
4005
- * @public
4006
- */
4007
- getVelocity() {
4008
- const currentTime = time.now();
4009
- if (!this.canTrackVelocity ||
4010
- this.prevFrameValue === undefined ||
4011
- currentTime - this.updatedAt > MAX_VELOCITY_DELTA) {
4012
- return 0;
4013
- }
4014
- const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA);
4015
- // Casts because of parseFloat's poor typing
4016
- return velocityPerSecond(parseFloat(this.current) -
4017
- parseFloat(this.prevFrameValue), delta);
3924
+ else {
3925
+ /**
3926
+ * isPrimary is true for all mice buttons, whereas every touch point
3927
+ * is regarded as its own input. So subsequent concurrent touch points
3928
+ * will be false.
3929
+ *
3930
+ * Specifically match against false here as incomplete versions of
3931
+ * PointerEvents in very old browser might have it set as undefined.
3932
+ */
3933
+ return event.isPrimary !== false;
4018
3934
  }
4019
- /**
4020
- * Registers a new animation to control this `MotionValue`. Only one
4021
- * animation can drive a `MotionValue` at one time.
4022
- *
4023
- * ```jsx
4024
- * value.start()
4025
- * ```
4026
- *
4027
- * @param animation - A function that starts the provided animation
4028
- */
4029
- start(startAnimation) {
4030
- this.stop();
4031
- return new Promise((resolve) => {
4032
- this.hasAnimated = true;
4033
- this.animation = startAnimation(resolve);
4034
- if (this.events.animationStart) {
4035
- this.events.animationStart.notify();
4036
- }
4037
- }).then(() => {
4038
- if (this.events.animationComplete) {
4039
- this.events.animationComplete.notify();
4040
- }
4041
- this.clearAnimation();
3935
+ };
3936
+
3937
+ const focusableElements = new Set([
3938
+ "BUTTON",
3939
+ "INPUT",
3940
+ "SELECT",
3941
+ "TEXTAREA",
3942
+ "A",
3943
+ ]);
3944
+ function isElementKeyboardAccessible(element) {
3945
+ return (focusableElements.has(element.tagName) ||
3946
+ element.tabIndex !== -1);
3947
+ }
3948
+
3949
+ const isPressing = new WeakSet();
3950
+
3951
+ /**
3952
+ * Filter out events that are not "Enter" keys.
3953
+ */
3954
+ function filterEvents(callback) {
3955
+ return (event) => {
3956
+ if (event.key !== "Enter")
3957
+ return;
3958
+ callback(event);
3959
+ };
3960
+ }
3961
+ function firePointerEvent(target, type) {
3962
+ target.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true }));
3963
+ }
3964
+ const enableKeyboardPress = (focusEvent, eventOptions) => {
3965
+ const element = focusEvent.currentTarget;
3966
+ if (!element)
3967
+ return;
3968
+ const handleKeydown = filterEvents(() => {
3969
+ if (isPressing.has(element))
3970
+ return;
3971
+ firePointerEvent(element, "down");
3972
+ const handleKeyup = filterEvents(() => {
3973
+ firePointerEvent(element, "up");
4042
3974
  });
4043
- }
3975
+ const handleBlur = () => firePointerEvent(element, "cancel");
3976
+ element.addEventListener("keyup", handleKeyup, eventOptions);
3977
+ element.addEventListener("blur", handleBlur, eventOptions);
3978
+ });
3979
+ element.addEventListener("keydown", handleKeydown, eventOptions);
4044
3980
  /**
4045
- * Stop the currently active animation.
4046
- *
4047
- * @public
3981
+ * Add an event listener that fires on blur to remove the keydown events.
4048
3982
  */
4049
- stop() {
4050
- if (this.animation) {
4051
- this.animation.stop();
4052
- if (this.events.animationCancel) {
4053
- this.events.animationCancel.notify();
3983
+ element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions);
3984
+ };
3985
+
3986
+ /**
3987
+ * Filter out events that are not primary pointer events, or are triggering
3988
+ * while a Motion gesture is active.
3989
+ */
3990
+ function isValidPressEvent(event) {
3991
+ return isPrimaryPointer(event) && !isDragActive();
3992
+ }
3993
+ /**
3994
+ * Create a press gesture.
3995
+ *
3996
+ * Press is different to `"pointerdown"`, `"pointerup"` in that it
3997
+ * automatically filters out secondary pointer events like right
3998
+ * click and multitouch.
3999
+ *
4000
+ * It also adds accessibility support for keyboards, where
4001
+ * an element with a press gesture will receive focus and
4002
+ * trigger on Enter `"keydown"` and `"keyup"` events.
4003
+ *
4004
+ * This is different to a browser's `"click"` event, which does
4005
+ * respond to keyboards but only for the `"click"` itself, rather
4006
+ * than the press start and end/cancel. The element also needs
4007
+ * to be focusable for this to work, whereas a press gesture will
4008
+ * make an element focusable by default.
4009
+ *
4010
+ * @public
4011
+ */
4012
+ function press(targetOrSelector, onPressStart, options = {}) {
4013
+ const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);
4014
+ const startPress = (startEvent) => {
4015
+ const target = startEvent.currentTarget;
4016
+ if (!isValidPressEvent(startEvent) || isPressing.has(target))
4017
+ return;
4018
+ isPressing.add(target);
4019
+ const onPressEnd = onPressStart(target, startEvent);
4020
+ const onPointerEnd = (endEvent, success) => {
4021
+ window.removeEventListener("pointerup", onPointerUp);
4022
+ window.removeEventListener("pointercancel", onPointerCancel);
4023
+ if (isPressing.has(target)) {
4024
+ isPressing.delete(target);
4025
+ }
4026
+ if (!isValidPressEvent(endEvent)) {
4027
+ return;
4028
+ }
4029
+ if (typeof onPressEnd === "function") {
4030
+ onPressEnd(endEvent, { success });
4031
+ }
4032
+ };
4033
+ const onPointerUp = (upEvent) => {
4034
+ onPointerEnd(upEvent, target === window ||
4035
+ target === document ||
4036
+ options.useGlobalTarget ||
4037
+ isNodeOrChild(target, upEvent.target));
4038
+ };
4039
+ const onPointerCancel = (cancelEvent) => {
4040
+ onPointerEnd(cancelEvent, false);
4041
+ };
4042
+ window.addEventListener("pointerup", onPointerUp, eventOptions);
4043
+ window.addEventListener("pointercancel", onPointerCancel, eventOptions);
4044
+ };
4045
+ targets.forEach((target) => {
4046
+ const pointerDownTarget = options.useGlobalTarget ? window : target;
4047
+ pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions);
4048
+ if (target instanceof HTMLElement) {
4049
+ target.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions));
4050
+ if (!isElementKeyboardAccessible(target) &&
4051
+ !target.hasAttribute("tabindex")) {
4052
+ target.tabIndex = 0;
4054
4053
  }
4055
4054
  }
4056
- this.clearAnimation();
4055
+ });
4056
+ return cancelEvents;
4057
+ }
4058
+
4059
+ function getComputedStyle$2(element, name) {
4060
+ const computedStyle = window.getComputedStyle(element);
4061
+ return isCSSVar(name)
4062
+ ? computedStyle.getPropertyValue(name)
4063
+ : computedStyle[name];
4064
+ }
4065
+
4066
+ function observeTimeline(update, timeline) {
4067
+ let prevProgress;
4068
+ const onFrame = () => {
4069
+ const { currentTime } = timeline;
4070
+ const percentage = currentTime === null ? 0 : currentTime.value;
4071
+ const progress = percentage / 100;
4072
+ if (prevProgress !== progress) {
4073
+ update(progress);
4074
+ }
4075
+ prevProgress = progress;
4076
+ };
4077
+ frame.preUpdate(onFrame, true);
4078
+ return () => cancelFrame(onFrame);
4079
+ }
4080
+
4081
+ function record() {
4082
+ const { value } = statsBuffer;
4083
+ if (value === null) {
4084
+ cancelFrame(record);
4085
+ return;
4057
4086
  }
4058
- /**
4059
- * Returns `true` if this value is currently animating.
4060
- *
4061
- * @public
4062
- */
4063
- isAnimating() {
4064
- return !!this.animation;
4087
+ value.frameloop.rate.push(frameData.delta);
4088
+ value.animations.mainThread.push(activeAnimations.mainThread);
4089
+ value.animations.waapi.push(activeAnimations.waapi);
4090
+ value.animations.layout.push(activeAnimations.layout);
4091
+ }
4092
+ function mean(values) {
4093
+ return values.reduce((acc, value) => acc + value, 0) / values.length;
4094
+ }
4095
+ function summarise(values, calcAverage = mean) {
4096
+ if (values.length === 0) {
4097
+ return {
4098
+ min: 0,
4099
+ max: 0,
4100
+ avg: 0,
4101
+ };
4065
4102
  }
4066
- clearAnimation() {
4067
- delete this.animation;
4103
+ return {
4104
+ min: Math.min(...values),
4105
+ max: Math.max(...values),
4106
+ avg: calcAverage(values),
4107
+ };
4108
+ }
4109
+ const msToFps = (ms) => Math.round(1000 / ms);
4110
+ function clearStatsBuffer() {
4111
+ statsBuffer.value = null;
4112
+ statsBuffer.addProjectionMetrics = null;
4113
+ }
4114
+ function reportStats() {
4115
+ const { value } = statsBuffer;
4116
+ if (!value) {
4117
+ throw new Error("Stats are not being measured");
4068
4118
  }
4119
+ clearStatsBuffer();
4120
+ cancelFrame(record);
4121
+ const summary = {
4122
+ frameloop: {
4123
+ setup: summarise(value.frameloop.setup),
4124
+ rate: summarise(value.frameloop.rate),
4125
+ read: summarise(value.frameloop.read),
4126
+ resolveKeyframes: summarise(value.frameloop.resolveKeyframes),
4127
+ preUpdate: summarise(value.frameloop.preUpdate),
4128
+ update: summarise(value.frameloop.update),
4129
+ preRender: summarise(value.frameloop.preRender),
4130
+ render: summarise(value.frameloop.render),
4131
+ postRender: summarise(value.frameloop.postRender),
4132
+ },
4133
+ animations: {
4134
+ mainThread: summarise(value.animations.mainThread),
4135
+ waapi: summarise(value.animations.waapi),
4136
+ layout: summarise(value.animations.layout),
4137
+ },
4138
+ layoutProjection: {
4139
+ nodes: summarise(value.layoutProjection.nodes),
4140
+ calculatedTargetDeltas: summarise(value.layoutProjection.calculatedTargetDeltas),
4141
+ calculatedProjections: summarise(value.layoutProjection.calculatedProjections),
4142
+ },
4143
+ };
4069
4144
  /**
4070
- * Destroy and clean up subscribers to this `MotionValue`.
4071
- *
4072
- * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
4073
- * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
4074
- * created a `MotionValue` via the `motionValue` function.
4075
- *
4076
- * @public
4145
+ * Convert the rate to FPS
4077
4146
  */
4078
- destroy() {
4079
- this.events.destroy?.notify();
4080
- this.clearListeners();
4081
- this.stop();
4082
- if (this.stopPassiveEffect) {
4083
- this.stopPassiveEffect();
4084
- }
4147
+ const { rate } = summary.frameloop;
4148
+ rate.min = msToFps(rate.min);
4149
+ rate.max = msToFps(rate.max);
4150
+ rate.avg = msToFps(rate.avg);
4151
+ [rate.min, rate.max] = [rate.max, rate.min];
4152
+ return summary;
4153
+ }
4154
+ function recordStats() {
4155
+ if (statsBuffer.value) {
4156
+ clearStatsBuffer();
4157
+ throw new Error("Stats are already being measured");
4085
4158
  }
4159
+ const newStatsBuffer = statsBuffer;
4160
+ newStatsBuffer.value = {
4161
+ frameloop: {
4162
+ setup: [],
4163
+ rate: [],
4164
+ read: [],
4165
+ resolveKeyframes: [],
4166
+ preUpdate: [],
4167
+ update: [],
4168
+ preRender: [],
4169
+ render: [],
4170
+ postRender: [],
4171
+ },
4172
+ animations: {
4173
+ mainThread: [],
4174
+ waapi: [],
4175
+ layout: [],
4176
+ },
4177
+ layoutProjection: {
4178
+ nodes: [],
4179
+ calculatedTargetDeltas: [],
4180
+ calculatedProjections: [],
4181
+ },
4182
+ };
4183
+ newStatsBuffer.addProjectionMetrics = (metrics) => {
4184
+ const { layoutProjection } = newStatsBuffer.value;
4185
+ layoutProjection.nodes.push(metrics.nodes);
4186
+ layoutProjection.calculatedTargetDeltas.push(metrics.calculatedTargetDeltas);
4187
+ layoutProjection.calculatedProjections.push(metrics.calculatedProjections);
4188
+ };
4189
+ frame.postRender(record, true);
4190
+ return reportStats;
4086
4191
  }
4087
- function motionValue(init, options) {
4088
- return new MotionValue(init, options);
4192
+
4193
+ function transform(...args) {
4194
+ const useImmediate = !Array.isArray(args[0]);
4195
+ const argOffset = useImmediate ? 0 : -1;
4196
+ const inputValue = args[0 + argOffset];
4197
+ const inputRange = args[1 + argOffset];
4198
+ const outputRange = args[2 + argOffset];
4199
+ const options = args[3 + argOffset];
4200
+ const interpolator = interpolate(inputRange, outputRange, options);
4201
+ return useImmediate ? interpolator(inputValue) : interpolator;
4089
4202
  }
4090
4203
 
4091
4204
  function subscribeValue(inputValues, outputValue, getLatest) {
@@ -4180,15 +4293,6 @@
4180
4293
  */
4181
4294
  const findValueType = (v) => valueTypes.find(testValueType(v));
4182
4295
 
4183
- /**
4184
- * Provided a value and a ValueType, returns the value as that value type.
4185
- */
4186
- const getValueAsType = (value, type) => {
4187
- return type && typeof value === "number"
4188
- ? type.transform(value)
4189
- : value;
4190
- };
4191
-
4192
4296
  function chooseLayerType(valueName) {
4193
4297
  if (valueName === "layout")
4194
4298
  return "group";