motion-dom 12.9.6 → 12.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -689,7 +689,7 @@ function mix(from, to, p) {
689
689
  const frameloopDriver = (update) => {
690
690
  const passTimestamp = ({ timestamp }) => update(timestamp);
691
691
  return {
692
- start: () => frame.update(passTimestamp, true),
692
+ start: (keepAlive = true) => frame.update(passTimestamp, keepAlive),
693
693
  stop: () => cancelFrame(passTimestamp),
694
694
  /**
695
695
  * If we're processing this frame we can use the
@@ -1517,6 +1517,7 @@ class JSAnimation extends WithPromise {
1517
1517
  else if (this.driver) {
1518
1518
  this.startTime = this.driver.now() - newTime / this.playbackSpeed;
1519
1519
  }
1520
+ this.driver?.start(false);
1520
1521
  }
1521
1522
  get speed() {
1522
1523
  return this.playbackSpeed;
@@ -1606,6 +1607,7 @@ class JSAnimation extends WithPromise {
1606
1607
  this.options.ease = "linear";
1607
1608
  this.initAnimation();
1608
1609
  }
1610
+ this.driver?.stop();
1609
1611
  return timeline.observe(this);
1610
1612
  }
1611
1613
  }
@@ -3073,420 +3075,6 @@ function resolveElements(elementOrSelector, scope, selectorCache) {
3073
3075
  return Array.from(elementOrSelector);
3074
3076
  }
3075
3077
 
3076
- function styleEffect(subject, values) {
3077
- const elements = resolveElements(subject);
3078
- const subscriptions = [];
3079
- for (let i = 0; i < elements.length; i++) {
3080
- const element = elements[i];
3081
- for (const key in values) {
3082
- const value = values[key];
3083
- /**
3084
- * TODO: Get specific setters for combined props (like x)
3085
- * or values with default types (like color)
3086
- *
3087
- * TODO: CSS variable support
3088
- */
3089
- const updateStyle = () => {
3090
- element.style[key] = value.get();
3091
- };
3092
- const scheduleUpdate = () => frame.render(updateStyle);
3093
- const cancel = value.on("change", scheduleUpdate);
3094
- scheduleUpdate();
3095
- subscriptions.push(() => {
3096
- cancel();
3097
- cancelFrame(updateStyle);
3098
- });
3099
- }
3100
- }
3101
- return () => {
3102
- for (const cancel of subscriptions) {
3103
- cancel();
3104
- }
3105
- };
3106
- }
3107
-
3108
- const { schedule: microtask, cancel: cancelMicrotask } =
3109
- /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
3110
-
3111
- const isDragging = {
3112
- x: false,
3113
- y: false,
3114
- };
3115
- function isDragActive() {
3116
- return isDragging.x || isDragging.y;
3117
- }
3118
-
3119
- function setDragLock(axis) {
3120
- if (axis === "x" || axis === "y") {
3121
- if (isDragging[axis]) {
3122
- return null;
3123
- }
3124
- else {
3125
- isDragging[axis] = true;
3126
- return () => {
3127
- isDragging[axis] = false;
3128
- };
3129
- }
3130
- }
3131
- else {
3132
- if (isDragging.x || isDragging.y) {
3133
- return null;
3134
- }
3135
- else {
3136
- isDragging.x = isDragging.y = true;
3137
- return () => {
3138
- isDragging.x = isDragging.y = false;
3139
- };
3140
- }
3141
- }
3142
- }
3143
-
3144
- function setupGesture(elementOrSelector, options) {
3145
- const elements = resolveElements(elementOrSelector);
3146
- const gestureAbortController = new AbortController();
3147
- const eventOptions = {
3148
- passive: true,
3149
- ...options,
3150
- signal: gestureAbortController.signal,
3151
- };
3152
- const cancel = () => gestureAbortController.abort();
3153
- return [elements, eventOptions, cancel];
3154
- }
3155
-
3156
- function isValidHover(event) {
3157
- return !(event.pointerType === "touch" || isDragActive());
3158
- }
3159
- /**
3160
- * Create a hover gesture. hover() is different to .addEventListener("pointerenter")
3161
- * in that it has an easier syntax, filters out polyfilled touch events, interoperates
3162
- * with drag gestures, and automatically removes the "pointerennd" event listener when the hover ends.
3163
- *
3164
- * @public
3165
- */
3166
- function hover(elementOrSelector, onHoverStart, options = {}) {
3167
- const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options);
3168
- const onPointerEnter = (enterEvent) => {
3169
- if (!isValidHover(enterEvent))
3170
- return;
3171
- const { target } = enterEvent;
3172
- const onHoverEnd = onHoverStart(target, enterEvent);
3173
- if (typeof onHoverEnd !== "function" || !target)
3174
- return;
3175
- const onPointerLeave = (leaveEvent) => {
3176
- if (!isValidHover(leaveEvent))
3177
- return;
3178
- onHoverEnd(leaveEvent);
3179
- target.removeEventListener("pointerleave", onPointerLeave);
3180
- };
3181
- target.addEventListener("pointerleave", onPointerLeave, eventOptions);
3182
- };
3183
- elements.forEach((element) => {
3184
- element.addEventListener("pointerenter", onPointerEnter, eventOptions);
3185
- });
3186
- return cancel;
3187
- }
3188
-
3189
- /**
3190
- * Recursively traverse up the tree to check whether the provided child node
3191
- * is the parent or a descendant of it.
3192
- *
3193
- * @param parent - Element to find
3194
- * @param child - Element to test against parent
3195
- */
3196
- const isNodeOrChild = (parent, child) => {
3197
- if (!child) {
3198
- return false;
3199
- }
3200
- else if (parent === child) {
3201
- return true;
3202
- }
3203
- else {
3204
- return isNodeOrChild(parent, child.parentElement);
3205
- }
3206
- };
3207
-
3208
- const isPrimaryPointer = (event) => {
3209
- if (event.pointerType === "mouse") {
3210
- return typeof event.button !== "number" || event.button <= 0;
3211
- }
3212
- else {
3213
- /**
3214
- * isPrimary is true for all mice buttons, whereas every touch point
3215
- * is regarded as its own input. So subsequent concurrent touch points
3216
- * will be false.
3217
- *
3218
- * Specifically match against false here as incomplete versions of
3219
- * PointerEvents in very old browser might have it set as undefined.
3220
- */
3221
- return event.isPrimary !== false;
3222
- }
3223
- };
3224
-
3225
- const focusableElements = new Set([
3226
- "BUTTON",
3227
- "INPUT",
3228
- "SELECT",
3229
- "TEXTAREA",
3230
- "A",
3231
- ]);
3232
- function isElementKeyboardAccessible(element) {
3233
- return (focusableElements.has(element.tagName) ||
3234
- element.tabIndex !== -1);
3235
- }
3236
-
3237
- const isPressing = new WeakSet();
3238
-
3239
- /**
3240
- * Filter out events that are not "Enter" keys.
3241
- */
3242
- function filterEvents(callback) {
3243
- return (event) => {
3244
- if (event.key !== "Enter")
3245
- return;
3246
- callback(event);
3247
- };
3248
- }
3249
- function firePointerEvent(target, type) {
3250
- target.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true }));
3251
- }
3252
- const enableKeyboardPress = (focusEvent, eventOptions) => {
3253
- const element = focusEvent.currentTarget;
3254
- if (!element)
3255
- return;
3256
- const handleKeydown = filterEvents(() => {
3257
- if (isPressing.has(element))
3258
- return;
3259
- firePointerEvent(element, "down");
3260
- const handleKeyup = filterEvents(() => {
3261
- firePointerEvent(element, "up");
3262
- });
3263
- const handleBlur = () => firePointerEvent(element, "cancel");
3264
- element.addEventListener("keyup", handleKeyup, eventOptions);
3265
- element.addEventListener("blur", handleBlur, eventOptions);
3266
- });
3267
- element.addEventListener("keydown", handleKeydown, eventOptions);
3268
- /**
3269
- * Add an event listener that fires on blur to remove the keydown events.
3270
- */
3271
- element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions);
3272
- };
3273
-
3274
- /**
3275
- * Filter out events that are not primary pointer events, or are triggering
3276
- * while a Motion gesture is active.
3277
- */
3278
- function isValidPressEvent(event) {
3279
- return isPrimaryPointer(event) && !isDragActive();
3280
- }
3281
- /**
3282
- * Create a press gesture.
3283
- *
3284
- * Press is different to `"pointerdown"`, `"pointerup"` in that it
3285
- * automatically filters out secondary pointer events like right
3286
- * click and multitouch.
3287
- *
3288
- * It also adds accessibility support for keyboards, where
3289
- * an element with a press gesture will receive focus and
3290
- * trigger on Enter `"keydown"` and `"keyup"` events.
3291
- *
3292
- * This is different to a browser's `"click"` event, which does
3293
- * respond to keyboards but only for the `"click"` itself, rather
3294
- * than the press start and end/cancel. The element also needs
3295
- * to be focusable for this to work, whereas a press gesture will
3296
- * make an element focusable by default.
3297
- *
3298
- * @public
3299
- */
3300
- function press(targetOrSelector, onPressStart, options = {}) {
3301
- const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);
3302
- const startPress = (startEvent) => {
3303
- const target = startEvent.currentTarget;
3304
- if (!isValidPressEvent(startEvent) || isPressing.has(target))
3305
- return;
3306
- isPressing.add(target);
3307
- const onPressEnd = onPressStart(target, startEvent);
3308
- const onPointerEnd = (endEvent, success) => {
3309
- window.removeEventListener("pointerup", onPointerUp);
3310
- window.removeEventListener("pointercancel", onPointerCancel);
3311
- if (!isValidPressEvent(endEvent) || !isPressing.has(target)) {
3312
- return;
3313
- }
3314
- isPressing.delete(target);
3315
- if (typeof onPressEnd === "function") {
3316
- onPressEnd(endEvent, { success });
3317
- }
3318
- };
3319
- const onPointerUp = (upEvent) => {
3320
- onPointerEnd(upEvent, target === window ||
3321
- target === document ||
3322
- options.useGlobalTarget ||
3323
- isNodeOrChild(target, upEvent.target));
3324
- };
3325
- const onPointerCancel = (cancelEvent) => {
3326
- onPointerEnd(cancelEvent, false);
3327
- };
3328
- window.addEventListener("pointerup", onPointerUp, eventOptions);
3329
- window.addEventListener("pointercancel", onPointerCancel, eventOptions);
3330
- };
3331
- targets.forEach((target) => {
3332
- const pointerDownTarget = options.useGlobalTarget ? window : target;
3333
- pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions);
3334
- if (target instanceof HTMLElement) {
3335
- target.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions));
3336
- if (!isElementKeyboardAccessible(target) &&
3337
- !target.hasAttribute("tabindex")) {
3338
- target.tabIndex = 0;
3339
- }
3340
- }
3341
- });
3342
- return cancelEvents;
3343
- }
3344
-
3345
- function getComputedStyle$1(element, name) {
3346
- const computedStyle = window.getComputedStyle(element);
3347
- return isCSSVar(name)
3348
- ? computedStyle.getPropertyValue(name)
3349
- : computedStyle[name];
3350
- }
3351
-
3352
- function observeTimeline(update, timeline) {
3353
- let prevProgress;
3354
- const onFrame = () => {
3355
- const { currentTime } = timeline;
3356
- const percentage = currentTime === null ? 0 : currentTime.value;
3357
- const progress = percentage / 100;
3358
- if (prevProgress !== progress) {
3359
- update(progress);
3360
- }
3361
- prevProgress = progress;
3362
- };
3363
- frame.preUpdate(onFrame, true);
3364
- return () => cancelFrame(onFrame);
3365
- }
3366
-
3367
- function record() {
3368
- const { value } = statsBuffer;
3369
- if (value === null) {
3370
- cancelFrame(record);
3371
- return;
3372
- }
3373
- value.frameloop.rate.push(frameData.delta);
3374
- value.animations.mainThread.push(activeAnimations.mainThread);
3375
- value.animations.waapi.push(activeAnimations.waapi);
3376
- value.animations.layout.push(activeAnimations.layout);
3377
- }
3378
- function mean(values) {
3379
- return values.reduce((acc, value) => acc + value, 0) / values.length;
3380
- }
3381
- function summarise(values, calcAverage = mean) {
3382
- if (values.length === 0) {
3383
- return {
3384
- min: 0,
3385
- max: 0,
3386
- avg: 0,
3387
- };
3388
- }
3389
- return {
3390
- min: Math.min(...values),
3391
- max: Math.max(...values),
3392
- avg: calcAverage(values),
3393
- };
3394
- }
3395
- const msToFps = (ms) => Math.round(1000 / ms);
3396
- function clearStatsBuffer() {
3397
- statsBuffer.value = null;
3398
- statsBuffer.addProjectionMetrics = null;
3399
- }
3400
- function reportStats() {
3401
- const { value } = statsBuffer;
3402
- if (!value) {
3403
- throw new Error("Stats are not being measured");
3404
- }
3405
- clearStatsBuffer();
3406
- cancelFrame(record);
3407
- const summary = {
3408
- frameloop: {
3409
- setup: summarise(value.frameloop.setup),
3410
- rate: summarise(value.frameloop.rate),
3411
- read: summarise(value.frameloop.read),
3412
- resolveKeyframes: summarise(value.frameloop.resolveKeyframes),
3413
- preUpdate: summarise(value.frameloop.preUpdate),
3414
- update: summarise(value.frameloop.update),
3415
- preRender: summarise(value.frameloop.preRender),
3416
- render: summarise(value.frameloop.render),
3417
- postRender: summarise(value.frameloop.postRender),
3418
- },
3419
- animations: {
3420
- mainThread: summarise(value.animations.mainThread),
3421
- waapi: summarise(value.animations.waapi),
3422
- layout: summarise(value.animations.layout),
3423
- },
3424
- layoutProjection: {
3425
- nodes: summarise(value.layoutProjection.nodes),
3426
- calculatedTargetDeltas: summarise(value.layoutProjection.calculatedTargetDeltas),
3427
- calculatedProjections: summarise(value.layoutProjection.calculatedProjections),
3428
- },
3429
- };
3430
- /**
3431
- * Convert the rate to FPS
3432
- */
3433
- const { rate } = summary.frameloop;
3434
- rate.min = msToFps(rate.min);
3435
- rate.max = msToFps(rate.max);
3436
- rate.avg = msToFps(rate.avg);
3437
- [rate.min, rate.max] = [rate.max, rate.min];
3438
- return summary;
3439
- }
3440
- function recordStats() {
3441
- if (statsBuffer.value) {
3442
- clearStatsBuffer();
3443
- throw new Error("Stats are already being measured");
3444
- }
3445
- const newStatsBuffer = statsBuffer;
3446
- newStatsBuffer.value = {
3447
- frameloop: {
3448
- setup: [],
3449
- rate: [],
3450
- read: [],
3451
- resolveKeyframes: [],
3452
- preUpdate: [],
3453
- update: [],
3454
- preRender: [],
3455
- render: [],
3456
- postRender: [],
3457
- },
3458
- animations: {
3459
- mainThread: [],
3460
- waapi: [],
3461
- layout: [],
3462
- },
3463
- layoutProjection: {
3464
- nodes: [],
3465
- calculatedTargetDeltas: [],
3466
- calculatedProjections: [],
3467
- },
3468
- };
3469
- newStatsBuffer.addProjectionMetrics = (metrics) => {
3470
- const { layoutProjection } = newStatsBuffer.value;
3471
- layoutProjection.nodes.push(metrics.nodes);
3472
- layoutProjection.calculatedTargetDeltas.push(metrics.calculatedTargetDeltas);
3473
- layoutProjection.calculatedProjections.push(metrics.calculatedProjections);
3474
- };
3475
- frame.postRender(record, true);
3476
- return reportStats;
3477
- }
3478
-
3479
- function transform(...args) {
3480
- const useImmediate = !Array.isArray(args[0]);
3481
- const argOffset = useImmediate ? 0 : -1;
3482
- const inputValue = args[0 + argOffset];
3483
- const inputRange = args[1 + argOffset];
3484
- const outputRange = args[2 + argOffset];
3485
- const options = args[3 + argOffset];
3486
- const interpolator = interpolate(inputRange, outputRange, options);
3487
- return useImmediate ? interpolator(inputValue) : interpolator;
3488
- }
3489
-
3490
3078
  /**
3491
3079
  * Maximum time between the value of two frames, beyond which we
3492
3080
  * assume the velocity has since been 0.
@@ -3543,6 +3131,11 @@ class MotionValue {
3543
3131
  // Update update subscribers
3544
3132
  if (this.current !== this.prev) {
3545
3133
  this.events.change?.notify(this.current);
3134
+ if (this.dependents) {
3135
+ for (const dependent of this.dependents) {
3136
+ dependent.dirty();
3137
+ }
3138
+ }
3546
3139
  }
3547
3140
  // Update render subscribers
3548
3141
  if (render) {
@@ -3684,6 +3277,20 @@ class MotionValue {
3684
3277
  if (this.stopPassiveEffect)
3685
3278
  this.stopPassiveEffect();
3686
3279
  }
3280
+ dirty() {
3281
+ this.events.change?.notify(this.current);
3282
+ }
3283
+ addDependent(dependent) {
3284
+ if (!this.dependents) {
3285
+ this.dependents = new Set();
3286
+ }
3287
+ this.dependents.add(dependent);
3288
+ }
3289
+ removeDependent(dependent) {
3290
+ if (this.dependents) {
3291
+ this.dependents.delete(dependent);
3292
+ }
3293
+ }
3687
3294
  /**
3688
3295
  * Returns the latest state of `MotionValue`
3689
3296
  *
@@ -3748,50 +3355,558 @@ class MotionValue {
3748
3355
  });
3749
3356
  }
3750
3357
  /**
3751
- * Stop the currently active animation.
3752
- *
3753
- * @public
3358
+ * Stop the currently active animation.
3359
+ *
3360
+ * @public
3361
+ */
3362
+ stop() {
3363
+ if (this.animation) {
3364
+ this.animation.stop();
3365
+ if (this.events.animationCancel) {
3366
+ this.events.animationCancel.notify();
3367
+ }
3368
+ }
3369
+ this.clearAnimation();
3370
+ }
3371
+ /**
3372
+ * Returns `true` if this value is currently animating.
3373
+ *
3374
+ * @public
3375
+ */
3376
+ isAnimating() {
3377
+ return !!this.animation;
3378
+ }
3379
+ clearAnimation() {
3380
+ delete this.animation;
3381
+ }
3382
+ /**
3383
+ * Destroy and clean up subscribers to this `MotionValue`.
3384
+ *
3385
+ * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
3386
+ * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
3387
+ * created a `MotionValue` via the `motionValue` function.
3388
+ *
3389
+ * @public
3390
+ */
3391
+ destroy() {
3392
+ this.dependents?.clear();
3393
+ this.events.destroy?.notify();
3394
+ this.clearListeners();
3395
+ this.stop();
3396
+ if (this.stopPassiveEffect) {
3397
+ this.stopPassiveEffect();
3398
+ }
3399
+ }
3400
+ }
3401
+ function motionValue(init, options) {
3402
+ return new MotionValue(init, options);
3403
+ }
3404
+
3405
+ /**
3406
+ * Provided a value and a ValueType, returns the value as that value type.
3407
+ */
3408
+ const getValueAsType = (value, type) => {
3409
+ return type && typeof value === "number"
3410
+ ? type.transform(value)
3411
+ : value;
3412
+ };
3413
+
3414
+ class MotionValueState {
3415
+ constructor() {
3416
+ this.latest = {};
3417
+ this.values = new Map();
3418
+ }
3419
+ set(name, value, render, computed) {
3420
+ const existingValue = this.values.get(name);
3421
+ if (existingValue) {
3422
+ existingValue.onRemove();
3423
+ }
3424
+ const onChange = () => {
3425
+ this.latest[name] = getValueAsType(value.get(), numberValueTypes[name]);
3426
+ render && frame.render(render);
3427
+ };
3428
+ onChange();
3429
+ const cancelOnChange = value.on("change", onChange);
3430
+ computed && value.addDependent(computed);
3431
+ const remove = () => {
3432
+ cancelOnChange();
3433
+ render && cancelFrame(render);
3434
+ this.values.delete(name);
3435
+ computed && value.removeDependent(computed);
3436
+ };
3437
+ this.values.set(name, { value, onRemove: remove });
3438
+ return remove;
3439
+ }
3440
+ get(name) {
3441
+ return this.values.get(name)?.value;
3442
+ }
3443
+ destroy() {
3444
+ for (const value of this.values.values()) {
3445
+ value.onRemove();
3446
+ }
3447
+ }
3448
+ }
3449
+
3450
+ const translateAlias = {
3451
+ x: "translateX",
3452
+ y: "translateY",
3453
+ z: "translateZ",
3454
+ transformPerspective: "perspective",
3455
+ };
3456
+ function buildTransform(state) {
3457
+ let transform = "";
3458
+ let transformIsDefault = true;
3459
+ /**
3460
+ * Loop over all possible transforms in order, adding the ones that
3461
+ * are present to the transform string.
3462
+ */
3463
+ for (let i = 0; i < transformPropOrder.length; i++) {
3464
+ const key = transformPropOrder[i];
3465
+ const value = state.latest[key];
3466
+ if (value === undefined)
3467
+ continue;
3468
+ let valueIsDefault = true;
3469
+ if (typeof value === "number") {
3470
+ valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
3471
+ }
3472
+ else {
3473
+ valueIsDefault = parseFloat(value) === 0;
3474
+ }
3475
+ if (!valueIsDefault) {
3476
+ transformIsDefault = false;
3477
+ const transformName = translateAlias[key] || key;
3478
+ const valueToRender = state.latest[key];
3479
+ transform += `${transformName}(${valueToRender}) `;
3480
+ }
3481
+ }
3482
+ return transformIsDefault ? "none" : transform.trim();
3483
+ }
3484
+
3485
+ const stateMap = new WeakMap();
3486
+ function styleEffect(subject, values) {
3487
+ const elements = resolveElements(subject);
3488
+ const subscriptions = [];
3489
+ for (let i = 0; i < elements.length; i++) {
3490
+ const element = elements[i];
3491
+ const state = stateMap.get(element) ?? new MotionValueState();
3492
+ stateMap.set(element, state);
3493
+ for (const key in values) {
3494
+ const value = values[key];
3495
+ const remove = addValue(element, state, key, value);
3496
+ subscriptions.push(remove);
3497
+ }
3498
+ }
3499
+ return () => {
3500
+ for (const cancel of subscriptions)
3501
+ cancel();
3502
+ };
3503
+ }
3504
+ function addValue(element, state, key, value) {
3505
+ let render = undefined;
3506
+ let computed = undefined;
3507
+ if (transformProps.has(key)) {
3508
+ if (!state.get("transform")) {
3509
+ state.set("transform", new MotionValue("none"), () => {
3510
+ element.style.transform = buildTransform(state);
3511
+ });
3512
+ }
3513
+ computed = state.get("transform");
3514
+ }
3515
+ else if (isCSSVar(key)) {
3516
+ render = () => {
3517
+ element.style.setProperty(key, state.latest[key]);
3518
+ };
3519
+ }
3520
+ else {
3521
+ render = () => {
3522
+ element.style[key] = state.latest[key];
3523
+ };
3524
+ }
3525
+ return state.set(key, value, render, computed);
3526
+ }
3527
+
3528
+ const { schedule: microtask, cancel: cancelMicrotask } =
3529
+ /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
3530
+
3531
+ const isDragging = {
3532
+ x: false,
3533
+ y: false,
3534
+ };
3535
+ function isDragActive() {
3536
+ return isDragging.x || isDragging.y;
3537
+ }
3538
+
3539
+ function setDragLock(axis) {
3540
+ if (axis === "x" || axis === "y") {
3541
+ if (isDragging[axis]) {
3542
+ return null;
3543
+ }
3544
+ else {
3545
+ isDragging[axis] = true;
3546
+ return () => {
3547
+ isDragging[axis] = false;
3548
+ };
3549
+ }
3550
+ }
3551
+ else {
3552
+ if (isDragging.x || isDragging.y) {
3553
+ return null;
3554
+ }
3555
+ else {
3556
+ isDragging.x = isDragging.y = true;
3557
+ return () => {
3558
+ isDragging.x = isDragging.y = false;
3559
+ };
3560
+ }
3561
+ }
3562
+ }
3563
+
3564
+ function setupGesture(elementOrSelector, options) {
3565
+ const elements = resolveElements(elementOrSelector);
3566
+ const gestureAbortController = new AbortController();
3567
+ const eventOptions = {
3568
+ passive: true,
3569
+ ...options,
3570
+ signal: gestureAbortController.signal,
3571
+ };
3572
+ const cancel = () => gestureAbortController.abort();
3573
+ return [elements, eventOptions, cancel];
3574
+ }
3575
+
3576
+ function isValidHover(event) {
3577
+ return !(event.pointerType === "touch" || isDragActive());
3578
+ }
3579
+ /**
3580
+ * Create a hover gesture. hover() is different to .addEventListener("pointerenter")
3581
+ * in that it has an easier syntax, filters out polyfilled touch events, interoperates
3582
+ * with drag gestures, and automatically removes the "pointerennd" event listener when the hover ends.
3583
+ *
3584
+ * @public
3585
+ */
3586
+ function hover(elementOrSelector, onHoverStart, options = {}) {
3587
+ const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options);
3588
+ const onPointerEnter = (enterEvent) => {
3589
+ if (!isValidHover(enterEvent))
3590
+ return;
3591
+ const { target } = enterEvent;
3592
+ const onHoverEnd = onHoverStart(target, enterEvent);
3593
+ if (typeof onHoverEnd !== "function" || !target)
3594
+ return;
3595
+ const onPointerLeave = (leaveEvent) => {
3596
+ if (!isValidHover(leaveEvent))
3597
+ return;
3598
+ onHoverEnd(leaveEvent);
3599
+ target.removeEventListener("pointerleave", onPointerLeave);
3600
+ };
3601
+ target.addEventListener("pointerleave", onPointerLeave, eventOptions);
3602
+ };
3603
+ elements.forEach((element) => {
3604
+ element.addEventListener("pointerenter", onPointerEnter, eventOptions);
3605
+ });
3606
+ return cancel;
3607
+ }
3608
+
3609
+ /**
3610
+ * Recursively traverse up the tree to check whether the provided child node
3611
+ * is the parent or a descendant of it.
3612
+ *
3613
+ * @param parent - Element to find
3614
+ * @param child - Element to test against parent
3615
+ */
3616
+ const isNodeOrChild = (parent, child) => {
3617
+ if (!child) {
3618
+ return false;
3619
+ }
3620
+ else if (parent === child) {
3621
+ return true;
3622
+ }
3623
+ else {
3624
+ return isNodeOrChild(parent, child.parentElement);
3625
+ }
3626
+ };
3627
+
3628
+ const isPrimaryPointer = (event) => {
3629
+ if (event.pointerType === "mouse") {
3630
+ return typeof event.button !== "number" || event.button <= 0;
3631
+ }
3632
+ else {
3633
+ /**
3634
+ * isPrimary is true for all mice buttons, whereas every touch point
3635
+ * is regarded as its own input. So subsequent concurrent touch points
3636
+ * will be false.
3637
+ *
3638
+ * Specifically match against false here as incomplete versions of
3639
+ * PointerEvents in very old browser might have it set as undefined.
3640
+ */
3641
+ return event.isPrimary !== false;
3642
+ }
3643
+ };
3644
+
3645
+ const focusableElements = new Set([
3646
+ "BUTTON",
3647
+ "INPUT",
3648
+ "SELECT",
3649
+ "TEXTAREA",
3650
+ "A",
3651
+ ]);
3652
+ function isElementKeyboardAccessible(element) {
3653
+ return (focusableElements.has(element.tagName) ||
3654
+ element.tabIndex !== -1);
3655
+ }
3656
+
3657
+ const isPressing = new WeakSet();
3658
+
3659
+ /**
3660
+ * Filter out events that are not "Enter" keys.
3661
+ */
3662
+ function filterEvents(callback) {
3663
+ return (event) => {
3664
+ if (event.key !== "Enter")
3665
+ return;
3666
+ callback(event);
3667
+ };
3668
+ }
3669
+ function firePointerEvent(target, type) {
3670
+ target.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true }));
3671
+ }
3672
+ const enableKeyboardPress = (focusEvent, eventOptions) => {
3673
+ const element = focusEvent.currentTarget;
3674
+ if (!element)
3675
+ return;
3676
+ const handleKeydown = filterEvents(() => {
3677
+ if (isPressing.has(element))
3678
+ return;
3679
+ firePointerEvent(element, "down");
3680
+ const handleKeyup = filterEvents(() => {
3681
+ firePointerEvent(element, "up");
3682
+ });
3683
+ const handleBlur = () => firePointerEvent(element, "cancel");
3684
+ element.addEventListener("keyup", handleKeyup, eventOptions);
3685
+ element.addEventListener("blur", handleBlur, eventOptions);
3686
+ });
3687
+ element.addEventListener("keydown", handleKeydown, eventOptions);
3688
+ /**
3689
+ * Add an event listener that fires on blur to remove the keydown events.
3754
3690
  */
3755
- stop() {
3756
- if (this.animation) {
3757
- this.animation.stop();
3758
- if (this.events.animationCancel) {
3759
- this.events.animationCancel.notify();
3691
+ element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions);
3692
+ };
3693
+
3694
+ /**
3695
+ * Filter out events that are not primary pointer events, or are triggering
3696
+ * while a Motion gesture is active.
3697
+ */
3698
+ function isValidPressEvent(event) {
3699
+ return isPrimaryPointer(event) && !isDragActive();
3700
+ }
3701
+ /**
3702
+ * Create a press gesture.
3703
+ *
3704
+ * Press is different to `"pointerdown"`, `"pointerup"` in that it
3705
+ * automatically filters out secondary pointer events like right
3706
+ * click and multitouch.
3707
+ *
3708
+ * It also adds accessibility support for keyboards, where
3709
+ * an element with a press gesture will receive focus and
3710
+ * trigger on Enter `"keydown"` and `"keyup"` events.
3711
+ *
3712
+ * This is different to a browser's `"click"` event, which does
3713
+ * respond to keyboards but only for the `"click"` itself, rather
3714
+ * than the press start and end/cancel. The element also needs
3715
+ * to be focusable for this to work, whereas a press gesture will
3716
+ * make an element focusable by default.
3717
+ *
3718
+ * @public
3719
+ */
3720
+ function press(targetOrSelector, onPressStart, options = {}) {
3721
+ const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);
3722
+ const startPress = (startEvent) => {
3723
+ const target = startEvent.currentTarget;
3724
+ if (!isValidPressEvent(startEvent) || isPressing.has(target))
3725
+ return;
3726
+ isPressing.add(target);
3727
+ const onPressEnd = onPressStart(target, startEvent);
3728
+ const onPointerEnd = (endEvent, success) => {
3729
+ window.removeEventListener("pointerup", onPointerUp);
3730
+ window.removeEventListener("pointercancel", onPointerCancel);
3731
+ if (isPressing.has(target)) {
3732
+ isPressing.delete(target);
3733
+ }
3734
+ if (!isValidPressEvent(endEvent)) {
3735
+ return;
3736
+ }
3737
+ if (typeof onPressEnd === "function") {
3738
+ onPressEnd(endEvent, { success });
3739
+ }
3740
+ };
3741
+ const onPointerUp = (upEvent) => {
3742
+ onPointerEnd(upEvent, target === window ||
3743
+ target === document ||
3744
+ options.useGlobalTarget ||
3745
+ isNodeOrChild(target, upEvent.target));
3746
+ };
3747
+ const onPointerCancel = (cancelEvent) => {
3748
+ onPointerEnd(cancelEvent, false);
3749
+ };
3750
+ window.addEventListener("pointerup", onPointerUp, eventOptions);
3751
+ window.addEventListener("pointercancel", onPointerCancel, eventOptions);
3752
+ };
3753
+ targets.forEach((target) => {
3754
+ const pointerDownTarget = options.useGlobalTarget ? window : target;
3755
+ pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions);
3756
+ if (target instanceof HTMLElement) {
3757
+ target.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions));
3758
+ if (!isElementKeyboardAccessible(target) &&
3759
+ !target.hasAttribute("tabindex")) {
3760
+ target.tabIndex = 0;
3760
3761
  }
3761
3762
  }
3762
- this.clearAnimation();
3763
+ });
3764
+ return cancelEvents;
3765
+ }
3766
+
3767
+ function getComputedStyle$1(element, name) {
3768
+ const computedStyle = window.getComputedStyle(element);
3769
+ return isCSSVar(name)
3770
+ ? computedStyle.getPropertyValue(name)
3771
+ : computedStyle[name];
3772
+ }
3773
+
3774
+ function observeTimeline(update, timeline) {
3775
+ let prevProgress;
3776
+ const onFrame = () => {
3777
+ const { currentTime } = timeline;
3778
+ const percentage = currentTime === null ? 0 : currentTime.value;
3779
+ const progress = percentage / 100;
3780
+ if (prevProgress !== progress) {
3781
+ update(progress);
3782
+ }
3783
+ prevProgress = progress;
3784
+ };
3785
+ frame.preUpdate(onFrame, true);
3786
+ return () => cancelFrame(onFrame);
3787
+ }
3788
+
3789
+ function record() {
3790
+ const { value } = statsBuffer;
3791
+ if (value === null) {
3792
+ cancelFrame(record);
3793
+ return;
3763
3794
  }
3764
- /**
3765
- * Returns `true` if this value is currently animating.
3766
- *
3767
- * @public
3768
- */
3769
- isAnimating() {
3770
- return !!this.animation;
3795
+ value.frameloop.rate.push(frameData.delta);
3796
+ value.animations.mainThread.push(activeAnimations.mainThread);
3797
+ value.animations.waapi.push(activeAnimations.waapi);
3798
+ value.animations.layout.push(activeAnimations.layout);
3799
+ }
3800
+ function mean(values) {
3801
+ return values.reduce((acc, value) => acc + value, 0) / values.length;
3802
+ }
3803
+ function summarise(values, calcAverage = mean) {
3804
+ if (values.length === 0) {
3805
+ return {
3806
+ min: 0,
3807
+ max: 0,
3808
+ avg: 0,
3809
+ };
3771
3810
  }
3772
- clearAnimation() {
3773
- delete this.animation;
3811
+ return {
3812
+ min: Math.min(...values),
3813
+ max: Math.max(...values),
3814
+ avg: calcAverage(values),
3815
+ };
3816
+ }
3817
+ const msToFps = (ms) => Math.round(1000 / ms);
3818
+ function clearStatsBuffer() {
3819
+ statsBuffer.value = null;
3820
+ statsBuffer.addProjectionMetrics = null;
3821
+ }
3822
+ function reportStats() {
3823
+ const { value } = statsBuffer;
3824
+ if (!value) {
3825
+ throw new Error("Stats are not being measured");
3774
3826
  }
3827
+ clearStatsBuffer();
3828
+ cancelFrame(record);
3829
+ const summary = {
3830
+ frameloop: {
3831
+ setup: summarise(value.frameloop.setup),
3832
+ rate: summarise(value.frameloop.rate),
3833
+ read: summarise(value.frameloop.read),
3834
+ resolveKeyframes: summarise(value.frameloop.resolveKeyframes),
3835
+ preUpdate: summarise(value.frameloop.preUpdate),
3836
+ update: summarise(value.frameloop.update),
3837
+ preRender: summarise(value.frameloop.preRender),
3838
+ render: summarise(value.frameloop.render),
3839
+ postRender: summarise(value.frameloop.postRender),
3840
+ },
3841
+ animations: {
3842
+ mainThread: summarise(value.animations.mainThread),
3843
+ waapi: summarise(value.animations.waapi),
3844
+ layout: summarise(value.animations.layout),
3845
+ },
3846
+ layoutProjection: {
3847
+ nodes: summarise(value.layoutProjection.nodes),
3848
+ calculatedTargetDeltas: summarise(value.layoutProjection.calculatedTargetDeltas),
3849
+ calculatedProjections: summarise(value.layoutProjection.calculatedProjections),
3850
+ },
3851
+ };
3775
3852
  /**
3776
- * Destroy and clean up subscribers to this `MotionValue`.
3777
- *
3778
- * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
3779
- * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
3780
- * created a `MotionValue` via the `motionValue` function.
3781
- *
3782
- * @public
3853
+ * Convert the rate to FPS
3783
3854
  */
3784
- destroy() {
3785
- this.events.destroy?.notify();
3786
- this.clearListeners();
3787
- this.stop();
3788
- if (this.stopPassiveEffect) {
3789
- this.stopPassiveEffect();
3790
- }
3855
+ const { rate } = summary.frameloop;
3856
+ rate.min = msToFps(rate.min);
3857
+ rate.max = msToFps(rate.max);
3858
+ rate.avg = msToFps(rate.avg);
3859
+ [rate.min, rate.max] = [rate.max, rate.min];
3860
+ return summary;
3861
+ }
3862
+ function recordStats() {
3863
+ if (statsBuffer.value) {
3864
+ clearStatsBuffer();
3865
+ throw new Error("Stats are already being measured");
3791
3866
  }
3867
+ const newStatsBuffer = statsBuffer;
3868
+ newStatsBuffer.value = {
3869
+ frameloop: {
3870
+ setup: [],
3871
+ rate: [],
3872
+ read: [],
3873
+ resolveKeyframes: [],
3874
+ preUpdate: [],
3875
+ update: [],
3876
+ preRender: [],
3877
+ render: [],
3878
+ postRender: [],
3879
+ },
3880
+ animations: {
3881
+ mainThread: [],
3882
+ waapi: [],
3883
+ layout: [],
3884
+ },
3885
+ layoutProjection: {
3886
+ nodes: [],
3887
+ calculatedTargetDeltas: [],
3888
+ calculatedProjections: [],
3889
+ },
3890
+ };
3891
+ newStatsBuffer.addProjectionMetrics = (metrics) => {
3892
+ const { layoutProjection } = newStatsBuffer.value;
3893
+ layoutProjection.nodes.push(metrics.nodes);
3894
+ layoutProjection.calculatedTargetDeltas.push(metrics.calculatedTargetDeltas);
3895
+ layoutProjection.calculatedProjections.push(metrics.calculatedProjections);
3896
+ };
3897
+ frame.postRender(record, true);
3898
+ return reportStats;
3792
3899
  }
3793
- function motionValue(init, options) {
3794
- return new MotionValue(init, options);
3900
+
3901
+ function transform(...args) {
3902
+ const useImmediate = !Array.isArray(args[0]);
3903
+ const argOffset = useImmediate ? 0 : -1;
3904
+ const inputValue = args[0 + argOffset];
3905
+ const inputRange = args[1 + argOffset];
3906
+ const outputRange = args[2 + argOffset];
3907
+ const options = args[3 + argOffset];
3908
+ const interpolator = interpolate(inputRange, outputRange, options);
3909
+ return useImmediate ? interpolator(inputValue) : interpolator;
3795
3910
  }
3796
3911
 
3797
3912
  function subscribeValue(inputValues, outputValue, getLatest) {
@@ -3886,15 +4001,6 @@ const valueTypes = [...dimensionValueTypes, color, complex];
3886
4001
  */
3887
4002
  const findValueType = (v) => valueTypes.find(testValueType(v));
3888
4003
 
3889
- /**
3890
- * Provided a value and a ValueType, returns the value as that value type.
3891
- */
3892
- const getValueAsType = (value, type) => {
3893
- return type && typeof value === "number"
3894
- ? type.transform(value)
3895
- : value;
3896
- };
3897
-
3898
4004
  function chooseLayerType(valueName) {
3899
4005
  if (valueName === "layout")
3900
4006
  return "group";