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