framer-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.
@@ -3825,420 +3825,6 @@
3825
3825
  return Array.from(elementOrSelector);
3826
3826
  }
3827
3827
 
3828
- function styleEffect(subject, values) {
3829
- const elements = resolveElements(subject);
3830
- const subscriptions = [];
3831
- for (let i = 0; i < elements.length; i++) {
3832
- const element = elements[i];
3833
- for (const key in values) {
3834
- const value = values[key];
3835
- /**
3836
- * TODO: Get specific setters for combined props (like x)
3837
- * or values with default types (like color)
3838
- *
3839
- * TODO: CSS variable support
3840
- */
3841
- const updateStyle = () => {
3842
- element.style[key] = value.get();
3843
- };
3844
- const scheduleUpdate = () => frame.render(updateStyle);
3845
- const cancel = value.on("change", scheduleUpdate);
3846
- scheduleUpdate();
3847
- subscriptions.push(() => {
3848
- cancel();
3849
- cancelFrame(updateStyle);
3850
- });
3851
- }
3852
- }
3853
- return () => {
3854
- for (const cancel of subscriptions) {
3855
- cancel();
3856
- }
3857
- };
3858
- }
3859
-
3860
- const { schedule: microtask, cancel: cancelMicrotask } =
3861
- /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
3862
-
3863
- const isDragging = {
3864
- x: false,
3865
- y: false,
3866
- };
3867
- function isDragActive() {
3868
- return isDragging.x || isDragging.y;
3869
- }
3870
-
3871
- function setDragLock(axis) {
3872
- if (axis === "x" || axis === "y") {
3873
- if (isDragging[axis]) {
3874
- return null;
3875
- }
3876
- else {
3877
- isDragging[axis] = true;
3878
- return () => {
3879
- isDragging[axis] = false;
3880
- };
3881
- }
3882
- }
3883
- else {
3884
- if (isDragging.x || isDragging.y) {
3885
- return null;
3886
- }
3887
- else {
3888
- isDragging.x = isDragging.y = true;
3889
- return () => {
3890
- isDragging.x = isDragging.y = false;
3891
- };
3892
- }
3893
- }
3894
- }
3895
-
3896
- function setupGesture(elementOrSelector, options) {
3897
- const elements = resolveElements(elementOrSelector);
3898
- const gestureAbortController = new AbortController();
3899
- const eventOptions = {
3900
- passive: true,
3901
- ...options,
3902
- signal: gestureAbortController.signal,
3903
- };
3904
- const cancel = () => gestureAbortController.abort();
3905
- return [elements, eventOptions, cancel];
3906
- }
3907
-
3908
- function isValidHover(event) {
3909
- return !(event.pointerType === "touch" || isDragActive());
3910
- }
3911
- /**
3912
- * Create a hover gesture. hover() is different to .addEventListener("pointerenter")
3913
- * in that it has an easier syntax, filters out polyfilled touch events, interoperates
3914
- * with drag gestures, and automatically removes the "pointerennd" event listener when the hover ends.
3915
- *
3916
- * @public
3917
- */
3918
- function hover(elementOrSelector, onHoverStart, options = {}) {
3919
- const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options);
3920
- const onPointerEnter = (enterEvent) => {
3921
- if (!isValidHover(enterEvent))
3922
- return;
3923
- const { target } = enterEvent;
3924
- const onHoverEnd = onHoverStart(target, enterEvent);
3925
- if (typeof onHoverEnd !== "function" || !target)
3926
- return;
3927
- const onPointerLeave = (leaveEvent) => {
3928
- if (!isValidHover(leaveEvent))
3929
- return;
3930
- onHoverEnd(leaveEvent);
3931
- target.removeEventListener("pointerleave", onPointerLeave);
3932
- };
3933
- target.addEventListener("pointerleave", onPointerLeave, eventOptions);
3934
- };
3935
- elements.forEach((element) => {
3936
- element.addEventListener("pointerenter", onPointerEnter, eventOptions);
3937
- });
3938
- return cancel;
3939
- }
3940
-
3941
- /**
3942
- * Recursively traverse up the tree to check whether the provided child node
3943
- * is the parent or a descendant of it.
3944
- *
3945
- * @param parent - Element to find
3946
- * @param child - Element to test against parent
3947
- */
3948
- const isNodeOrChild = (parent, child) => {
3949
- if (!child) {
3950
- return false;
3951
- }
3952
- else if (parent === child) {
3953
- return true;
3954
- }
3955
- else {
3956
- return isNodeOrChild(parent, child.parentElement);
3957
- }
3958
- };
3959
-
3960
- const isPrimaryPointer = (event) => {
3961
- if (event.pointerType === "mouse") {
3962
- return typeof event.button !== "number" || event.button <= 0;
3963
- }
3964
- else {
3965
- /**
3966
- * isPrimary is true for all mice buttons, whereas every touch point
3967
- * is regarded as its own input. So subsequent concurrent touch points
3968
- * will be false.
3969
- *
3970
- * Specifically match against false here as incomplete versions of
3971
- * PointerEvents in very old browser might have it set as undefined.
3972
- */
3973
- return event.isPrimary !== false;
3974
- }
3975
- };
3976
-
3977
- const focusableElements = new Set([
3978
- "BUTTON",
3979
- "INPUT",
3980
- "SELECT",
3981
- "TEXTAREA",
3982
- "A",
3983
- ]);
3984
- function isElementKeyboardAccessible(element) {
3985
- return (focusableElements.has(element.tagName) ||
3986
- element.tabIndex !== -1);
3987
- }
3988
-
3989
- const isPressing = new WeakSet();
3990
-
3991
- /**
3992
- * Filter out events that are not "Enter" keys.
3993
- */
3994
- function filterEvents(callback) {
3995
- return (event) => {
3996
- if (event.key !== "Enter")
3997
- return;
3998
- callback(event);
3999
- };
4000
- }
4001
- function firePointerEvent(target, type) {
4002
- target.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true }));
4003
- }
4004
- const enableKeyboardPress = (focusEvent, eventOptions) => {
4005
- const element = focusEvent.currentTarget;
4006
- if (!element)
4007
- return;
4008
- const handleKeydown = filterEvents(() => {
4009
- if (isPressing.has(element))
4010
- return;
4011
- firePointerEvent(element, "down");
4012
- const handleKeyup = filterEvents(() => {
4013
- firePointerEvent(element, "up");
4014
- });
4015
- const handleBlur = () => firePointerEvent(element, "cancel");
4016
- element.addEventListener("keyup", handleKeyup, eventOptions);
4017
- element.addEventListener("blur", handleBlur, eventOptions);
4018
- });
4019
- element.addEventListener("keydown", handleKeydown, eventOptions);
4020
- /**
4021
- * Add an event listener that fires on blur to remove the keydown events.
4022
- */
4023
- element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions);
4024
- };
4025
-
4026
- /**
4027
- * Filter out events that are not primary pointer events, or are triggering
4028
- * while a Motion gesture is active.
4029
- */
4030
- function isValidPressEvent(event) {
4031
- return isPrimaryPointer(event) && !isDragActive();
4032
- }
4033
- /**
4034
- * Create a press gesture.
4035
- *
4036
- * Press is different to `"pointerdown"`, `"pointerup"` in that it
4037
- * automatically filters out secondary pointer events like right
4038
- * click and multitouch.
4039
- *
4040
- * It also adds accessibility support for keyboards, where
4041
- * an element with a press gesture will receive focus and
4042
- * trigger on Enter `"keydown"` and `"keyup"` events.
4043
- *
4044
- * This is different to a browser's `"click"` event, which does
4045
- * respond to keyboards but only for the `"click"` itself, rather
4046
- * than the press start and end/cancel. The element also needs
4047
- * to be focusable for this to work, whereas a press gesture will
4048
- * make an element focusable by default.
4049
- *
4050
- * @public
4051
- */
4052
- function press(targetOrSelector, onPressStart, options = {}) {
4053
- const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);
4054
- const startPress = (startEvent) => {
4055
- const target = startEvent.currentTarget;
4056
- if (!isValidPressEvent(startEvent) || isPressing.has(target))
4057
- return;
4058
- isPressing.add(target);
4059
- const onPressEnd = onPressStart(target, startEvent);
4060
- const onPointerEnd = (endEvent, success) => {
4061
- window.removeEventListener("pointerup", onPointerUp);
4062
- window.removeEventListener("pointercancel", onPointerCancel);
4063
- if (!isValidPressEvent(endEvent) || !isPressing.has(target)) {
4064
- return;
4065
- }
4066
- isPressing.delete(target);
4067
- if (typeof onPressEnd === "function") {
4068
- onPressEnd(endEvent, { success });
4069
- }
4070
- };
4071
- const onPointerUp = (upEvent) => {
4072
- onPointerEnd(upEvent, target === window ||
4073
- target === document ||
4074
- options.useGlobalTarget ||
4075
- isNodeOrChild(target, upEvent.target));
4076
- };
4077
- const onPointerCancel = (cancelEvent) => {
4078
- onPointerEnd(cancelEvent, false);
4079
- };
4080
- window.addEventListener("pointerup", onPointerUp, eventOptions);
4081
- window.addEventListener("pointercancel", onPointerCancel, eventOptions);
4082
- };
4083
- targets.forEach((target) => {
4084
- const pointerDownTarget = options.useGlobalTarget ? window : target;
4085
- pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions);
4086
- if (target instanceof HTMLElement) {
4087
- target.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions));
4088
- if (!isElementKeyboardAccessible(target) &&
4089
- !target.hasAttribute("tabindex")) {
4090
- target.tabIndex = 0;
4091
- }
4092
- }
4093
- });
4094
- return cancelEvents;
4095
- }
4096
-
4097
- function getComputedStyle$2(element, name) {
4098
- const computedStyle = window.getComputedStyle(element);
4099
- return isCSSVar(name)
4100
- ? computedStyle.getPropertyValue(name)
4101
- : computedStyle[name];
4102
- }
4103
-
4104
- function observeTimeline(update, timeline) {
4105
- let prevProgress;
4106
- const onFrame = () => {
4107
- const { currentTime } = timeline;
4108
- const percentage = currentTime === null ? 0 : currentTime.value;
4109
- const progress = percentage / 100;
4110
- if (prevProgress !== progress) {
4111
- update(progress);
4112
- }
4113
- prevProgress = progress;
4114
- };
4115
- frame.preUpdate(onFrame, true);
4116
- return () => cancelFrame(onFrame);
4117
- }
4118
-
4119
- function record() {
4120
- const { value } = statsBuffer;
4121
- if (value === null) {
4122
- cancelFrame(record);
4123
- return;
4124
- }
4125
- value.frameloop.rate.push(frameData.delta);
4126
- value.animations.mainThread.push(activeAnimations.mainThread);
4127
- value.animations.waapi.push(activeAnimations.waapi);
4128
- value.animations.layout.push(activeAnimations.layout);
4129
- }
4130
- function mean(values) {
4131
- return values.reduce((acc, value) => acc + value, 0) / values.length;
4132
- }
4133
- function summarise(values, calcAverage = mean) {
4134
- if (values.length === 0) {
4135
- return {
4136
- min: 0,
4137
- max: 0,
4138
- avg: 0,
4139
- };
4140
- }
4141
- return {
4142
- min: Math.min(...values),
4143
- max: Math.max(...values),
4144
- avg: calcAverage(values),
4145
- };
4146
- }
4147
- const msToFps = (ms) => Math.round(1000 / ms);
4148
- function clearStatsBuffer() {
4149
- statsBuffer.value = null;
4150
- statsBuffer.addProjectionMetrics = null;
4151
- }
4152
- function reportStats() {
4153
- const { value } = statsBuffer;
4154
- if (!value) {
4155
- throw new Error("Stats are not being measured");
4156
- }
4157
- clearStatsBuffer();
4158
- cancelFrame(record);
4159
- const summary = {
4160
- frameloop: {
4161
- setup: summarise(value.frameloop.setup),
4162
- rate: summarise(value.frameloop.rate),
4163
- read: summarise(value.frameloop.read),
4164
- resolveKeyframes: summarise(value.frameloop.resolveKeyframes),
4165
- preUpdate: summarise(value.frameloop.preUpdate),
4166
- update: summarise(value.frameloop.update),
4167
- preRender: summarise(value.frameloop.preRender),
4168
- render: summarise(value.frameloop.render),
4169
- postRender: summarise(value.frameloop.postRender),
4170
- },
4171
- animations: {
4172
- mainThread: summarise(value.animations.mainThread),
4173
- waapi: summarise(value.animations.waapi),
4174
- layout: summarise(value.animations.layout),
4175
- },
4176
- layoutProjection: {
4177
- nodes: summarise(value.layoutProjection.nodes),
4178
- calculatedTargetDeltas: summarise(value.layoutProjection.calculatedTargetDeltas),
4179
- calculatedProjections: summarise(value.layoutProjection.calculatedProjections),
4180
- },
4181
- };
4182
- /**
4183
- * Convert the rate to FPS
4184
- */
4185
- const { rate } = summary.frameloop;
4186
- rate.min = msToFps(rate.min);
4187
- rate.max = msToFps(rate.max);
4188
- rate.avg = msToFps(rate.avg);
4189
- [rate.min, rate.max] = [rate.max, rate.min];
4190
- return summary;
4191
- }
4192
- function recordStats() {
4193
- if (statsBuffer.value) {
4194
- clearStatsBuffer();
4195
- throw new Error("Stats are already being measured");
4196
- }
4197
- const newStatsBuffer = statsBuffer;
4198
- newStatsBuffer.value = {
4199
- frameloop: {
4200
- setup: [],
4201
- rate: [],
4202
- read: [],
4203
- resolveKeyframes: [],
4204
- preUpdate: [],
4205
- update: [],
4206
- preRender: [],
4207
- render: [],
4208
- postRender: [],
4209
- },
4210
- animations: {
4211
- mainThread: [],
4212
- waapi: [],
4213
- layout: [],
4214
- },
4215
- layoutProjection: {
4216
- nodes: [],
4217
- calculatedTargetDeltas: [],
4218
- calculatedProjections: [],
4219
- },
4220
- };
4221
- newStatsBuffer.addProjectionMetrics = (metrics) => {
4222
- const { layoutProjection } = newStatsBuffer.value;
4223
- layoutProjection.nodes.push(metrics.nodes);
4224
- layoutProjection.calculatedTargetDeltas.push(metrics.calculatedTargetDeltas);
4225
- layoutProjection.calculatedProjections.push(metrics.calculatedProjections);
4226
- };
4227
- frame.postRender(record, true);
4228
- return reportStats;
4229
- }
4230
-
4231
- function transform(...args) {
4232
- const useImmediate = !Array.isArray(args[0]);
4233
- const argOffset = useImmediate ? 0 : -1;
4234
- const inputValue = args[0 + argOffset];
4235
- const inputRange = args[1 + argOffset];
4236
- const outputRange = args[2 + argOffset];
4237
- const options = args[3 + argOffset];
4238
- const interpolator = interpolate(inputRange, outputRange, options);
4239
- return useImmediate ? interpolator(inputValue) : interpolator;
4240
- }
4241
-
4242
3828
  /**
4243
3829
  * Maximum time between the value of two frames, beyond which we
4244
3830
  * assume the velocity has since been 0.
@@ -4257,293 +3843,820 @@
4257
3843
  */
4258
3844
  class MotionValue {
4259
3845
  /**
4260
- * @param init - The initiating value
4261
- * @param config - Optional configuration options
3846
+ * @param init - The initiating value
3847
+ * @param config - Optional configuration options
3848
+ *
3849
+ * - `transformer`: A function to transform incoming values with.
3850
+ */
3851
+ constructor(init, options = {}) {
3852
+ /**
3853
+ * This will be replaced by the build step with the latest version number.
3854
+ * When MotionValues are provided to motion components, warn if versions are mixed.
3855
+ */
3856
+ this.version = "__VERSION__";
3857
+ /**
3858
+ * Tracks whether this value can output a velocity. Currently this is only true
3859
+ * if the value is numerical, but we might be able to widen the scope here and support
3860
+ * other value types.
3861
+ *
3862
+ * @internal
3863
+ */
3864
+ this.canTrackVelocity = null;
3865
+ /**
3866
+ * An object containing a SubscriptionManager for each active event.
3867
+ */
3868
+ this.events = {};
3869
+ this.updateAndNotify = (v, render = true) => {
3870
+ const currentTime = time.now();
3871
+ /**
3872
+ * If we're updating the value during another frame or eventloop
3873
+ * than the previous frame, then the we set the previous frame value
3874
+ * to current.
3875
+ */
3876
+ if (this.updatedAt !== currentTime) {
3877
+ this.setPrevFrameValue();
3878
+ }
3879
+ this.prev = this.current;
3880
+ this.setCurrent(v);
3881
+ // Update update subscribers
3882
+ if (this.current !== this.prev) {
3883
+ this.events.change?.notify(this.current);
3884
+ if (this.dependents) {
3885
+ for (const dependent of this.dependents) {
3886
+ dependent.dirty();
3887
+ }
3888
+ }
3889
+ }
3890
+ // Update render subscribers
3891
+ if (render) {
3892
+ this.events.renderRequest?.notify(this.current);
3893
+ }
3894
+ };
3895
+ this.hasAnimated = false;
3896
+ this.setCurrent(init);
3897
+ this.owner = options.owner;
3898
+ }
3899
+ setCurrent(current) {
3900
+ this.current = current;
3901
+ this.updatedAt = time.now();
3902
+ if (this.canTrackVelocity === null && current !== undefined) {
3903
+ this.canTrackVelocity = isFloat(this.current);
3904
+ }
3905
+ }
3906
+ setPrevFrameValue(prevFrameValue = this.current) {
3907
+ this.prevFrameValue = prevFrameValue;
3908
+ this.prevUpdatedAt = this.updatedAt;
3909
+ }
3910
+ /**
3911
+ * Adds a function that will be notified when the `MotionValue` is updated.
3912
+ *
3913
+ * It returns a function that, when called, will cancel the subscription.
3914
+ *
3915
+ * When calling `onChange` inside a React component, it should be wrapped with the
3916
+ * `useEffect` hook. As it returns an unsubscribe function, this should be returned
3917
+ * from the `useEffect` function to ensure you don't add duplicate subscribers..
3918
+ *
3919
+ * ```jsx
3920
+ * export const MyComponent = () => {
3921
+ * const x = useMotionValue(0)
3922
+ * const y = useMotionValue(0)
3923
+ * const opacity = useMotionValue(1)
3924
+ *
3925
+ * useEffect(() => {
3926
+ * function updateOpacity() {
3927
+ * const maxXY = Math.max(x.get(), y.get())
3928
+ * const newOpacity = transform(maxXY, [0, 100], [1, 0])
3929
+ * opacity.set(newOpacity)
3930
+ * }
3931
+ *
3932
+ * const unsubscribeX = x.on("change", updateOpacity)
3933
+ * const unsubscribeY = y.on("change", updateOpacity)
3934
+ *
3935
+ * return () => {
3936
+ * unsubscribeX()
3937
+ * unsubscribeY()
3938
+ * }
3939
+ * }, [])
3940
+ *
3941
+ * return <motion.div style={{ x }} />
3942
+ * }
3943
+ * ```
3944
+ *
3945
+ * @param subscriber - A function that receives the latest value.
3946
+ * @returns A function that, when called, will cancel this subscription.
3947
+ *
3948
+ * @deprecated
3949
+ */
3950
+ onChange(subscription) {
3951
+ {
3952
+ warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on("change", callback).`);
3953
+ }
3954
+ return this.on("change", subscription);
3955
+ }
3956
+ on(eventName, callback) {
3957
+ if (!this.events[eventName]) {
3958
+ this.events[eventName] = new SubscriptionManager();
3959
+ }
3960
+ const unsubscribe = this.events[eventName].add(callback);
3961
+ if (eventName === "change") {
3962
+ return () => {
3963
+ unsubscribe();
3964
+ /**
3965
+ * If we have no more change listeners by the start
3966
+ * of the next frame, stop active animations.
3967
+ */
3968
+ frame.read(() => {
3969
+ if (!this.events.change.getSize()) {
3970
+ this.stop();
3971
+ }
3972
+ });
3973
+ };
3974
+ }
3975
+ return unsubscribe;
3976
+ }
3977
+ clearListeners() {
3978
+ for (const eventManagers in this.events) {
3979
+ this.events[eventManagers].clear();
3980
+ }
3981
+ }
3982
+ /**
3983
+ * Attaches a passive effect to the `MotionValue`.
3984
+ */
3985
+ attach(passiveEffect, stopPassiveEffect) {
3986
+ this.passiveEffect = passiveEffect;
3987
+ this.stopPassiveEffect = stopPassiveEffect;
3988
+ }
3989
+ /**
3990
+ * Sets the state of the `MotionValue`.
3991
+ *
3992
+ * @remarks
3993
+ *
3994
+ * ```jsx
3995
+ * const x = useMotionValue(0)
3996
+ * x.set(10)
3997
+ * ```
3998
+ *
3999
+ * @param latest - Latest value to set.
4000
+ * @param render - Whether to notify render subscribers. Defaults to `true`
4001
+ *
4002
+ * @public
4003
+ */
4004
+ set(v, render = true) {
4005
+ if (!render || !this.passiveEffect) {
4006
+ this.updateAndNotify(v, render);
4007
+ }
4008
+ else {
4009
+ this.passiveEffect(v, this.updateAndNotify);
4010
+ }
4011
+ }
4012
+ setWithVelocity(prev, current, delta) {
4013
+ this.set(current);
4014
+ this.prev = undefined;
4015
+ this.prevFrameValue = prev;
4016
+ this.prevUpdatedAt = this.updatedAt - delta;
4017
+ }
4018
+ /**
4019
+ * Set the state of the `MotionValue`, stopping any active animations,
4020
+ * effects, and resets velocity to `0`.
4021
+ */
4022
+ jump(v, endAnimation = true) {
4023
+ this.updateAndNotify(v);
4024
+ this.prev = v;
4025
+ this.prevUpdatedAt = this.prevFrameValue = undefined;
4026
+ endAnimation && this.stop();
4027
+ if (this.stopPassiveEffect)
4028
+ this.stopPassiveEffect();
4029
+ }
4030
+ dirty() {
4031
+ this.events.change?.notify(this.current);
4032
+ }
4033
+ addDependent(dependent) {
4034
+ if (!this.dependents) {
4035
+ this.dependents = new Set();
4036
+ }
4037
+ this.dependents.add(dependent);
4038
+ }
4039
+ removeDependent(dependent) {
4040
+ if (this.dependents) {
4041
+ this.dependents.delete(dependent);
4042
+ }
4043
+ }
4044
+ /**
4045
+ * Returns the latest state of `MotionValue`
4262
4046
  *
4263
- * - `transformer`: A function to transform incoming values with.
4047
+ * @returns - The latest state of `MotionValue`
4048
+ *
4049
+ * @public
4264
4050
  */
4265
- constructor(init, options = {}) {
4266
- /**
4267
- * This will be replaced by the build step with the latest version number.
4268
- * When MotionValues are provided to motion components, warn if versions are mixed.
4269
- */
4270
- this.version = "__VERSION__";
4271
- /**
4272
- * Tracks whether this value can output a velocity. Currently this is only true
4273
- * if the value is numerical, but we might be able to widen the scope here and support
4274
- * other value types.
4275
- *
4276
- * @internal
4277
- */
4278
- this.canTrackVelocity = null;
4279
- /**
4280
- * An object containing a SubscriptionManager for each active event.
4281
- */
4282
- this.events = {};
4283
- this.updateAndNotify = (v, render = true) => {
4284
- const currentTime = time.now();
4285
- /**
4286
- * If we're updating the value during another frame or eventloop
4287
- * than the previous frame, then the we set the previous frame value
4288
- * to current.
4289
- */
4290
- if (this.updatedAt !== currentTime) {
4291
- this.setPrevFrameValue();
4292
- }
4293
- this.prev = this.current;
4294
- this.setCurrent(v);
4295
- // Update update subscribers
4296
- if (this.current !== this.prev) {
4297
- this.events.change?.notify(this.current);
4298
- }
4299
- // Update render subscribers
4300
- if (render) {
4301
- this.events.renderRequest?.notify(this.current);
4302
- }
4303
- };
4304
- this.hasAnimated = false;
4305
- this.setCurrent(init);
4306
- this.owner = options.owner;
4307
- }
4308
- setCurrent(current) {
4309
- this.current = current;
4310
- this.updatedAt = time.now();
4311
- if (this.canTrackVelocity === null && current !== undefined) {
4312
- this.canTrackVelocity = isFloat(this.current);
4051
+ get() {
4052
+ if (collectMotionValues.current) {
4053
+ collectMotionValues.current.push(this);
4313
4054
  }
4055
+ return this.current;
4314
4056
  }
4315
- setPrevFrameValue(prevFrameValue = this.current) {
4316
- this.prevFrameValue = prevFrameValue;
4317
- this.prevUpdatedAt = this.updatedAt;
4057
+ /**
4058
+ * @public
4059
+ */
4060
+ getPrevious() {
4061
+ return this.prev;
4318
4062
  }
4319
4063
  /**
4320
- * Adds a function that will be notified when the `MotionValue` is updated.
4064
+ * Returns the latest velocity of `MotionValue`
4321
4065
  *
4322
- * It returns a function that, when called, will cancel the subscription.
4066
+ * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.
4323
4067
  *
4324
- * When calling `onChange` inside a React component, it should be wrapped with the
4325
- * `useEffect` hook. As it returns an unsubscribe function, this should be returned
4326
- * from the `useEffect` function to ensure you don't add duplicate subscribers..
4068
+ * @public
4069
+ */
4070
+ getVelocity() {
4071
+ const currentTime = time.now();
4072
+ if (!this.canTrackVelocity ||
4073
+ this.prevFrameValue === undefined ||
4074
+ currentTime - this.updatedAt > MAX_VELOCITY_DELTA) {
4075
+ return 0;
4076
+ }
4077
+ const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA);
4078
+ // Casts because of parseFloat's poor typing
4079
+ return velocityPerSecond(parseFloat(this.current) -
4080
+ parseFloat(this.prevFrameValue), delta);
4081
+ }
4082
+ /**
4083
+ * Registers a new animation to control this `MotionValue`. Only one
4084
+ * animation can drive a `MotionValue` at one time.
4327
4085
  *
4328
4086
  * ```jsx
4329
- * export const MyComponent = () => {
4330
- * const x = useMotionValue(0)
4331
- * const y = useMotionValue(0)
4332
- * const opacity = useMotionValue(1)
4333
- *
4334
- * useEffect(() => {
4335
- * function updateOpacity() {
4336
- * const maxXY = Math.max(x.get(), y.get())
4337
- * const newOpacity = transform(maxXY, [0, 100], [1, 0])
4338
- * opacity.set(newOpacity)
4339
- * }
4087
+ * value.start()
4088
+ * ```
4340
4089
  *
4341
- * const unsubscribeX = x.on("change", updateOpacity)
4342
- * const unsubscribeY = y.on("change", updateOpacity)
4090
+ * @param animation - A function that starts the provided animation
4091
+ */
4092
+ start(startAnimation) {
4093
+ this.stop();
4094
+ return new Promise((resolve) => {
4095
+ this.hasAnimated = true;
4096
+ this.animation = startAnimation(resolve);
4097
+ if (this.events.animationStart) {
4098
+ this.events.animationStart.notify();
4099
+ }
4100
+ }).then(() => {
4101
+ if (this.events.animationComplete) {
4102
+ this.events.animationComplete.notify();
4103
+ }
4104
+ this.clearAnimation();
4105
+ });
4106
+ }
4107
+ /**
4108
+ * Stop the currently active animation.
4343
4109
  *
4344
- * return () => {
4345
- * unsubscribeX()
4346
- * unsubscribeY()
4347
- * }
4348
- * }, [])
4110
+ * @public
4111
+ */
4112
+ stop() {
4113
+ if (this.animation) {
4114
+ this.animation.stop();
4115
+ if (this.events.animationCancel) {
4116
+ this.events.animationCancel.notify();
4117
+ }
4118
+ }
4119
+ this.clearAnimation();
4120
+ }
4121
+ /**
4122
+ * Returns `true` if this value is currently animating.
4349
4123
  *
4350
- * return <motion.div style={{ x }} />
4351
- * }
4352
- * ```
4124
+ * @public
4125
+ */
4126
+ isAnimating() {
4127
+ return !!this.animation;
4128
+ }
4129
+ clearAnimation() {
4130
+ delete this.animation;
4131
+ }
4132
+ /**
4133
+ * Destroy and clean up subscribers to this `MotionValue`.
4353
4134
  *
4354
- * @param subscriber - A function that receives the latest value.
4355
- * @returns A function that, when called, will cancel this subscription.
4135
+ * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
4136
+ * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
4137
+ * created a `MotionValue` via the `motionValue` function.
4356
4138
  *
4357
- * @deprecated
4139
+ * @public
4358
4140
  */
4359
- onChange(subscription) {
4360
- {
4361
- warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on("change", callback).`);
4141
+ destroy() {
4142
+ this.dependents?.clear();
4143
+ this.events.destroy?.notify();
4144
+ this.clearListeners();
4145
+ this.stop();
4146
+ if (this.stopPassiveEffect) {
4147
+ this.stopPassiveEffect();
4362
4148
  }
4363
- return this.on("change", subscription);
4364
4149
  }
4365
- on(eventName, callback) {
4366
- if (!this.events[eventName]) {
4367
- this.events[eventName] = new SubscriptionManager();
4150
+ }
4151
+ function motionValue(init, options) {
4152
+ return new MotionValue(init, options);
4153
+ }
4154
+
4155
+ /**
4156
+ * Provided a value and a ValueType, returns the value as that value type.
4157
+ */
4158
+ const getValueAsType = (value, type) => {
4159
+ return type && typeof value === "number"
4160
+ ? type.transform(value)
4161
+ : value;
4162
+ };
4163
+
4164
+ class MotionValueState {
4165
+ constructor() {
4166
+ this.latest = {};
4167
+ this.values = new Map();
4168
+ }
4169
+ set(name, value, render, computed) {
4170
+ const existingValue = this.values.get(name);
4171
+ if (existingValue) {
4172
+ existingValue.onRemove();
4173
+ }
4174
+ const onChange = () => {
4175
+ this.latest[name] = getValueAsType(value.get(), numberValueTypes[name]);
4176
+ render && frame.render(render);
4177
+ };
4178
+ onChange();
4179
+ const cancelOnChange = value.on("change", onChange);
4180
+ computed && value.addDependent(computed);
4181
+ const remove = () => {
4182
+ cancelOnChange();
4183
+ render && cancelFrame(render);
4184
+ this.values.delete(name);
4185
+ computed && value.removeDependent(computed);
4186
+ };
4187
+ this.values.set(name, { value, onRemove: remove });
4188
+ return remove;
4189
+ }
4190
+ get(name) {
4191
+ return this.values.get(name)?.value;
4192
+ }
4193
+ destroy() {
4194
+ for (const value of this.values.values()) {
4195
+ value.onRemove();
4196
+ }
4197
+ }
4198
+ }
4199
+
4200
+ const translateAlias$1 = {
4201
+ x: "translateX",
4202
+ y: "translateY",
4203
+ z: "translateZ",
4204
+ transformPerspective: "perspective",
4205
+ };
4206
+ function buildTransform$1(state) {
4207
+ let transform = "";
4208
+ let transformIsDefault = true;
4209
+ /**
4210
+ * Loop over all possible transforms in order, adding the ones that
4211
+ * are present to the transform string.
4212
+ */
4213
+ for (let i = 0; i < transformPropOrder.length; i++) {
4214
+ const key = transformPropOrder[i];
4215
+ const value = state.latest[key];
4216
+ if (value === undefined)
4217
+ continue;
4218
+ let valueIsDefault = true;
4219
+ if (typeof value === "number") {
4220
+ valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
4221
+ }
4222
+ else {
4223
+ valueIsDefault = parseFloat(value) === 0;
4224
+ }
4225
+ if (!valueIsDefault) {
4226
+ transformIsDefault = false;
4227
+ const transformName = translateAlias$1[key] || key;
4228
+ const valueToRender = state.latest[key];
4229
+ transform += `${transformName}(${valueToRender}) `;
4230
+ }
4231
+ }
4232
+ return transformIsDefault ? "none" : transform.trim();
4233
+ }
4234
+
4235
+ const stateMap = new WeakMap();
4236
+ function styleEffect(subject, values) {
4237
+ const elements = resolveElements(subject);
4238
+ const subscriptions = [];
4239
+ for (let i = 0; i < elements.length; i++) {
4240
+ const element = elements[i];
4241
+ const state = stateMap.get(element) ?? new MotionValueState();
4242
+ stateMap.set(element, state);
4243
+ for (const key in values) {
4244
+ const value = values[key];
4245
+ const remove = addValue(element, state, key, value);
4246
+ subscriptions.push(remove);
4247
+ }
4248
+ }
4249
+ return () => {
4250
+ for (const cancel of subscriptions)
4251
+ cancel();
4252
+ };
4253
+ }
4254
+ function addValue(element, state, key, value) {
4255
+ let render = undefined;
4256
+ let computed = undefined;
4257
+ if (transformProps.has(key)) {
4258
+ if (!state.get("transform")) {
4259
+ state.set("transform", new MotionValue("none"), () => {
4260
+ element.style.transform = buildTransform$1(state);
4261
+ });
4262
+ }
4263
+ computed = state.get("transform");
4264
+ }
4265
+ else if (isCSSVar(key)) {
4266
+ render = () => {
4267
+ element.style.setProperty(key, state.latest[key]);
4268
+ };
4269
+ }
4270
+ else {
4271
+ render = () => {
4272
+ element.style[key] = state.latest[key];
4273
+ };
4274
+ }
4275
+ return state.set(key, value, render, computed);
4276
+ }
4277
+
4278
+ const { schedule: microtask, cancel: cancelMicrotask } =
4279
+ /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
4280
+
4281
+ const isDragging = {
4282
+ x: false,
4283
+ y: false,
4284
+ };
4285
+ function isDragActive() {
4286
+ return isDragging.x || isDragging.y;
4287
+ }
4288
+
4289
+ function setDragLock(axis) {
4290
+ if (axis === "x" || axis === "y") {
4291
+ if (isDragging[axis]) {
4292
+ return null;
4368
4293
  }
4369
- const unsubscribe = this.events[eventName].add(callback);
4370
- if (eventName === "change") {
4294
+ else {
4295
+ isDragging[axis] = true;
4371
4296
  return () => {
4372
- unsubscribe();
4373
- /**
4374
- * If we have no more change listeners by the start
4375
- * of the next frame, stop active animations.
4376
- */
4377
- frame.read(() => {
4378
- if (!this.events.change.getSize()) {
4379
- this.stop();
4380
- }
4381
- });
4297
+ isDragging[axis] = false;
4382
4298
  };
4383
4299
  }
4384
- return unsubscribe;
4385
- }
4386
- clearListeners() {
4387
- for (const eventManagers in this.events) {
4388
- this.events[eventManagers].clear();
4389
- }
4390
- }
4391
- /**
4392
- * Attaches a passive effect to the `MotionValue`.
4393
- */
4394
- attach(passiveEffect, stopPassiveEffect) {
4395
- this.passiveEffect = passiveEffect;
4396
- this.stopPassiveEffect = stopPassiveEffect;
4397
4300
  }
4398
- /**
4399
- * Sets the state of the `MotionValue`.
4400
- *
4401
- * @remarks
4402
- *
4403
- * ```jsx
4404
- * const x = useMotionValue(0)
4405
- * x.set(10)
4406
- * ```
4407
- *
4408
- * @param latest - Latest value to set.
4409
- * @param render - Whether to notify render subscribers. Defaults to `true`
4410
- *
4411
- * @public
4412
- */
4413
- set(v, render = true) {
4414
- if (!render || !this.passiveEffect) {
4415
- this.updateAndNotify(v, render);
4301
+ else {
4302
+ if (isDragging.x || isDragging.y) {
4303
+ return null;
4416
4304
  }
4417
4305
  else {
4418
- this.passiveEffect(v, this.updateAndNotify);
4306
+ isDragging.x = isDragging.y = true;
4307
+ return () => {
4308
+ isDragging.x = isDragging.y = false;
4309
+ };
4419
4310
  }
4420
4311
  }
4421
- setWithVelocity(prev, current, delta) {
4422
- this.set(current);
4423
- this.prev = undefined;
4424
- this.prevFrameValue = prev;
4425
- this.prevUpdatedAt = this.updatedAt - delta;
4312
+ }
4313
+
4314
+ function setupGesture(elementOrSelector, options) {
4315
+ const elements = resolveElements(elementOrSelector);
4316
+ const gestureAbortController = new AbortController();
4317
+ const eventOptions = {
4318
+ passive: true,
4319
+ ...options,
4320
+ signal: gestureAbortController.signal,
4321
+ };
4322
+ const cancel = () => gestureAbortController.abort();
4323
+ return [elements, eventOptions, cancel];
4324
+ }
4325
+
4326
+ function isValidHover(event) {
4327
+ return !(event.pointerType === "touch" || isDragActive());
4328
+ }
4329
+ /**
4330
+ * Create a hover gesture. hover() is different to .addEventListener("pointerenter")
4331
+ * in that it has an easier syntax, filters out polyfilled touch events, interoperates
4332
+ * with drag gestures, and automatically removes the "pointerennd" event listener when the hover ends.
4333
+ *
4334
+ * @public
4335
+ */
4336
+ function hover(elementOrSelector, onHoverStart, options = {}) {
4337
+ const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options);
4338
+ const onPointerEnter = (enterEvent) => {
4339
+ if (!isValidHover(enterEvent))
4340
+ return;
4341
+ const { target } = enterEvent;
4342
+ const onHoverEnd = onHoverStart(target, enterEvent);
4343
+ if (typeof onHoverEnd !== "function" || !target)
4344
+ return;
4345
+ const onPointerLeave = (leaveEvent) => {
4346
+ if (!isValidHover(leaveEvent))
4347
+ return;
4348
+ onHoverEnd(leaveEvent);
4349
+ target.removeEventListener("pointerleave", onPointerLeave);
4350
+ };
4351
+ target.addEventListener("pointerleave", onPointerLeave, eventOptions);
4352
+ };
4353
+ elements.forEach((element) => {
4354
+ element.addEventListener("pointerenter", onPointerEnter, eventOptions);
4355
+ });
4356
+ return cancel;
4357
+ }
4358
+
4359
+ /**
4360
+ * Recursively traverse up the tree to check whether the provided child node
4361
+ * is the parent or a descendant of it.
4362
+ *
4363
+ * @param parent - Element to find
4364
+ * @param child - Element to test against parent
4365
+ */
4366
+ const isNodeOrChild = (parent, child) => {
4367
+ if (!child) {
4368
+ return false;
4426
4369
  }
4427
- /**
4428
- * Set the state of the `MotionValue`, stopping any active animations,
4429
- * effects, and resets velocity to `0`.
4430
- */
4431
- jump(v, endAnimation = true) {
4432
- this.updateAndNotify(v);
4433
- this.prev = v;
4434
- this.prevUpdatedAt = this.prevFrameValue = undefined;
4435
- endAnimation && this.stop();
4436
- if (this.stopPassiveEffect)
4437
- this.stopPassiveEffect();
4370
+ else if (parent === child) {
4371
+ return true;
4438
4372
  }
4439
- /**
4440
- * Returns the latest state of `MotionValue`
4441
- *
4442
- * @returns - The latest state of `MotionValue`
4443
- *
4444
- * @public
4445
- */
4446
- get() {
4447
- if (collectMotionValues.current) {
4448
- collectMotionValues.current.push(this);
4449
- }
4450
- return this.current;
4373
+ else {
4374
+ return isNodeOrChild(parent, child.parentElement);
4451
4375
  }
4452
- /**
4453
- * @public
4454
- */
4455
- getPrevious() {
4456
- return this.prev;
4376
+ };
4377
+
4378
+ const isPrimaryPointer = (event) => {
4379
+ if (event.pointerType === "mouse") {
4380
+ return typeof event.button !== "number" || event.button <= 0;
4457
4381
  }
4458
- /**
4459
- * Returns the latest velocity of `MotionValue`
4460
- *
4461
- * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.
4462
- *
4463
- * @public
4464
- */
4465
- getVelocity() {
4466
- const currentTime = time.now();
4467
- if (!this.canTrackVelocity ||
4468
- this.prevFrameValue === undefined ||
4469
- currentTime - this.updatedAt > MAX_VELOCITY_DELTA) {
4470
- return 0;
4471
- }
4472
- const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA);
4473
- // Casts because of parseFloat's poor typing
4474
- return velocityPerSecond(parseFloat(this.current) -
4475
- parseFloat(this.prevFrameValue), delta);
4382
+ else {
4383
+ /**
4384
+ * isPrimary is true for all mice buttons, whereas every touch point
4385
+ * is regarded as its own input. So subsequent concurrent touch points
4386
+ * will be false.
4387
+ *
4388
+ * Specifically match against false here as incomplete versions of
4389
+ * PointerEvents in very old browser might have it set as undefined.
4390
+ */
4391
+ return event.isPrimary !== false;
4476
4392
  }
4477
- /**
4478
- * Registers a new animation to control this `MotionValue`. Only one
4479
- * animation can drive a `MotionValue` at one time.
4480
- *
4481
- * ```jsx
4482
- * value.start()
4483
- * ```
4484
- *
4485
- * @param animation - A function that starts the provided animation
4486
- */
4487
- start(startAnimation) {
4488
- this.stop();
4489
- return new Promise((resolve) => {
4490
- this.hasAnimated = true;
4491
- this.animation = startAnimation(resolve);
4492
- if (this.events.animationStart) {
4493
- this.events.animationStart.notify();
4494
- }
4495
- }).then(() => {
4496
- if (this.events.animationComplete) {
4497
- this.events.animationComplete.notify();
4498
- }
4499
- this.clearAnimation();
4393
+ };
4394
+
4395
+ const focusableElements = new Set([
4396
+ "BUTTON",
4397
+ "INPUT",
4398
+ "SELECT",
4399
+ "TEXTAREA",
4400
+ "A",
4401
+ ]);
4402
+ function isElementKeyboardAccessible(element) {
4403
+ return (focusableElements.has(element.tagName) ||
4404
+ element.tabIndex !== -1);
4405
+ }
4406
+
4407
+ const isPressing = new WeakSet();
4408
+
4409
+ /**
4410
+ * Filter out events that are not "Enter" keys.
4411
+ */
4412
+ function filterEvents(callback) {
4413
+ return (event) => {
4414
+ if (event.key !== "Enter")
4415
+ return;
4416
+ callback(event);
4417
+ };
4418
+ }
4419
+ function firePointerEvent(target, type) {
4420
+ target.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true }));
4421
+ }
4422
+ const enableKeyboardPress = (focusEvent, eventOptions) => {
4423
+ const element = focusEvent.currentTarget;
4424
+ if (!element)
4425
+ return;
4426
+ const handleKeydown = filterEvents(() => {
4427
+ if (isPressing.has(element))
4428
+ return;
4429
+ firePointerEvent(element, "down");
4430
+ const handleKeyup = filterEvents(() => {
4431
+ firePointerEvent(element, "up");
4500
4432
  });
4501
- }
4433
+ const handleBlur = () => firePointerEvent(element, "cancel");
4434
+ element.addEventListener("keyup", handleKeyup, eventOptions);
4435
+ element.addEventListener("blur", handleBlur, eventOptions);
4436
+ });
4437
+ element.addEventListener("keydown", handleKeydown, eventOptions);
4502
4438
  /**
4503
- * Stop the currently active animation.
4504
- *
4505
- * @public
4439
+ * Add an event listener that fires on blur to remove the keydown events.
4506
4440
  */
4507
- stop() {
4508
- if (this.animation) {
4509
- this.animation.stop();
4510
- if (this.events.animationCancel) {
4511
- this.events.animationCancel.notify();
4441
+ element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions);
4442
+ };
4443
+
4444
+ /**
4445
+ * Filter out events that are not primary pointer events, or are triggering
4446
+ * while a Motion gesture is active.
4447
+ */
4448
+ function isValidPressEvent(event) {
4449
+ return isPrimaryPointer(event) && !isDragActive();
4450
+ }
4451
+ /**
4452
+ * Create a press gesture.
4453
+ *
4454
+ * Press is different to `"pointerdown"`, `"pointerup"` in that it
4455
+ * automatically filters out secondary pointer events like right
4456
+ * click and multitouch.
4457
+ *
4458
+ * It also adds accessibility support for keyboards, where
4459
+ * an element with a press gesture will receive focus and
4460
+ * trigger on Enter `"keydown"` and `"keyup"` events.
4461
+ *
4462
+ * This is different to a browser's `"click"` event, which does
4463
+ * respond to keyboards but only for the `"click"` itself, rather
4464
+ * than the press start and end/cancel. The element also needs
4465
+ * to be focusable for this to work, whereas a press gesture will
4466
+ * make an element focusable by default.
4467
+ *
4468
+ * @public
4469
+ */
4470
+ function press(targetOrSelector, onPressStart, options = {}) {
4471
+ const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);
4472
+ const startPress = (startEvent) => {
4473
+ const target = startEvent.currentTarget;
4474
+ if (!isValidPressEvent(startEvent) || isPressing.has(target))
4475
+ return;
4476
+ isPressing.add(target);
4477
+ const onPressEnd = onPressStart(target, startEvent);
4478
+ const onPointerEnd = (endEvent, success) => {
4479
+ window.removeEventListener("pointerup", onPointerUp);
4480
+ window.removeEventListener("pointercancel", onPointerCancel);
4481
+ if (isPressing.has(target)) {
4482
+ isPressing.delete(target);
4483
+ }
4484
+ if (!isValidPressEvent(endEvent)) {
4485
+ return;
4486
+ }
4487
+ if (typeof onPressEnd === "function") {
4488
+ onPressEnd(endEvent, { success });
4489
+ }
4490
+ };
4491
+ const onPointerUp = (upEvent) => {
4492
+ onPointerEnd(upEvent, target === window ||
4493
+ target === document ||
4494
+ options.useGlobalTarget ||
4495
+ isNodeOrChild(target, upEvent.target));
4496
+ };
4497
+ const onPointerCancel = (cancelEvent) => {
4498
+ onPointerEnd(cancelEvent, false);
4499
+ };
4500
+ window.addEventListener("pointerup", onPointerUp, eventOptions);
4501
+ window.addEventListener("pointercancel", onPointerCancel, eventOptions);
4502
+ };
4503
+ targets.forEach((target) => {
4504
+ const pointerDownTarget = options.useGlobalTarget ? window : target;
4505
+ pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions);
4506
+ if (target instanceof HTMLElement) {
4507
+ target.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions));
4508
+ if (!isElementKeyboardAccessible(target) &&
4509
+ !target.hasAttribute("tabindex")) {
4510
+ target.tabIndex = 0;
4512
4511
  }
4513
4512
  }
4514
- this.clearAnimation();
4513
+ });
4514
+ return cancelEvents;
4515
+ }
4516
+
4517
+ function getComputedStyle$2(element, name) {
4518
+ const computedStyle = window.getComputedStyle(element);
4519
+ return isCSSVar(name)
4520
+ ? computedStyle.getPropertyValue(name)
4521
+ : computedStyle[name];
4522
+ }
4523
+
4524
+ function observeTimeline(update, timeline) {
4525
+ let prevProgress;
4526
+ const onFrame = () => {
4527
+ const { currentTime } = timeline;
4528
+ const percentage = currentTime === null ? 0 : currentTime.value;
4529
+ const progress = percentage / 100;
4530
+ if (prevProgress !== progress) {
4531
+ update(progress);
4532
+ }
4533
+ prevProgress = progress;
4534
+ };
4535
+ frame.preUpdate(onFrame, true);
4536
+ return () => cancelFrame(onFrame);
4537
+ }
4538
+
4539
+ function record() {
4540
+ const { value } = statsBuffer;
4541
+ if (value === null) {
4542
+ cancelFrame(record);
4543
+ return;
4515
4544
  }
4516
- /**
4517
- * Returns `true` if this value is currently animating.
4518
- *
4519
- * @public
4520
- */
4521
- isAnimating() {
4522
- return !!this.animation;
4545
+ value.frameloop.rate.push(frameData.delta);
4546
+ value.animations.mainThread.push(activeAnimations.mainThread);
4547
+ value.animations.waapi.push(activeAnimations.waapi);
4548
+ value.animations.layout.push(activeAnimations.layout);
4549
+ }
4550
+ function mean(values) {
4551
+ return values.reduce((acc, value) => acc + value, 0) / values.length;
4552
+ }
4553
+ function summarise(values, calcAverage = mean) {
4554
+ if (values.length === 0) {
4555
+ return {
4556
+ min: 0,
4557
+ max: 0,
4558
+ avg: 0,
4559
+ };
4523
4560
  }
4524
- clearAnimation() {
4525
- delete this.animation;
4561
+ return {
4562
+ min: Math.min(...values),
4563
+ max: Math.max(...values),
4564
+ avg: calcAverage(values),
4565
+ };
4566
+ }
4567
+ const msToFps = (ms) => Math.round(1000 / ms);
4568
+ function clearStatsBuffer() {
4569
+ statsBuffer.value = null;
4570
+ statsBuffer.addProjectionMetrics = null;
4571
+ }
4572
+ function reportStats() {
4573
+ const { value } = statsBuffer;
4574
+ if (!value) {
4575
+ throw new Error("Stats are not being measured");
4526
4576
  }
4577
+ clearStatsBuffer();
4578
+ cancelFrame(record);
4579
+ const summary = {
4580
+ frameloop: {
4581
+ setup: summarise(value.frameloop.setup),
4582
+ rate: summarise(value.frameloop.rate),
4583
+ read: summarise(value.frameloop.read),
4584
+ resolveKeyframes: summarise(value.frameloop.resolveKeyframes),
4585
+ preUpdate: summarise(value.frameloop.preUpdate),
4586
+ update: summarise(value.frameloop.update),
4587
+ preRender: summarise(value.frameloop.preRender),
4588
+ render: summarise(value.frameloop.render),
4589
+ postRender: summarise(value.frameloop.postRender),
4590
+ },
4591
+ animations: {
4592
+ mainThread: summarise(value.animations.mainThread),
4593
+ waapi: summarise(value.animations.waapi),
4594
+ layout: summarise(value.animations.layout),
4595
+ },
4596
+ layoutProjection: {
4597
+ nodes: summarise(value.layoutProjection.nodes),
4598
+ calculatedTargetDeltas: summarise(value.layoutProjection.calculatedTargetDeltas),
4599
+ calculatedProjections: summarise(value.layoutProjection.calculatedProjections),
4600
+ },
4601
+ };
4527
4602
  /**
4528
- * Destroy and clean up subscribers to this `MotionValue`.
4529
- *
4530
- * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
4531
- * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
4532
- * created a `MotionValue` via the `motionValue` function.
4533
- *
4534
- * @public
4603
+ * Convert the rate to FPS
4535
4604
  */
4536
- destroy() {
4537
- this.events.destroy?.notify();
4538
- this.clearListeners();
4539
- this.stop();
4540
- if (this.stopPassiveEffect) {
4541
- this.stopPassiveEffect();
4542
- }
4605
+ const { rate } = summary.frameloop;
4606
+ rate.min = msToFps(rate.min);
4607
+ rate.max = msToFps(rate.max);
4608
+ rate.avg = msToFps(rate.avg);
4609
+ [rate.min, rate.max] = [rate.max, rate.min];
4610
+ return summary;
4611
+ }
4612
+ function recordStats() {
4613
+ if (statsBuffer.value) {
4614
+ clearStatsBuffer();
4615
+ throw new Error("Stats are already being measured");
4543
4616
  }
4617
+ const newStatsBuffer = statsBuffer;
4618
+ newStatsBuffer.value = {
4619
+ frameloop: {
4620
+ setup: [],
4621
+ rate: [],
4622
+ read: [],
4623
+ resolveKeyframes: [],
4624
+ preUpdate: [],
4625
+ update: [],
4626
+ preRender: [],
4627
+ render: [],
4628
+ postRender: [],
4629
+ },
4630
+ animations: {
4631
+ mainThread: [],
4632
+ waapi: [],
4633
+ layout: [],
4634
+ },
4635
+ layoutProjection: {
4636
+ nodes: [],
4637
+ calculatedTargetDeltas: [],
4638
+ calculatedProjections: [],
4639
+ },
4640
+ };
4641
+ newStatsBuffer.addProjectionMetrics = (metrics) => {
4642
+ const { layoutProjection } = newStatsBuffer.value;
4643
+ layoutProjection.nodes.push(metrics.nodes);
4644
+ layoutProjection.calculatedTargetDeltas.push(metrics.calculatedTargetDeltas);
4645
+ layoutProjection.calculatedProjections.push(metrics.calculatedProjections);
4646
+ };
4647
+ frame.postRender(record, true);
4648
+ return reportStats;
4544
4649
  }
4545
- function motionValue(init, options) {
4546
- return new MotionValue(init, options);
4650
+
4651
+ function transform(...args) {
4652
+ const useImmediate = !Array.isArray(args[0]);
4653
+ const argOffset = useImmediate ? 0 : -1;
4654
+ const inputValue = args[0 + argOffset];
4655
+ const inputRange = args[1 + argOffset];
4656
+ const outputRange = args[2 + argOffset];
4657
+ const options = args[3 + argOffset];
4658
+ const interpolator = interpolate(inputRange, outputRange, options);
4659
+ return useImmediate ? interpolator(inputValue) : interpolator;
4547
4660
  }
4548
4661
 
4549
4662
  function subscribeValue(inputValues, outputValue, getLatest) {
@@ -4638,15 +4751,6 @@
4638
4751
  */
4639
4752
  const findValueType = (v) => valueTypes.find(testValueType(v));
4640
4753
 
4641
- /**
4642
- * Provided a value and a ValueType, returns the value as that value type.
4643
- */
4644
- const getValueAsType = (value, type) => {
4645
- return type && typeof value === "number"
4646
- ? type.transform(value)
4647
- : value;
4648
- };
4649
-
4650
4754
  function chooseLayerType(valueName) {
4651
4755
  if (valueName === "layout")
4652
4756
  return "group";