motion-dom 12.9.6 → 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.
package/dist/cjs/index.js CHANGED
@@ -3073,420 +3073,6 @@ function resolveElements(elementOrSelector, scope, selectorCache) {
3073
3073
  return Array.from(elementOrSelector);
3074
3074
  }
3075
3075
 
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
3076
  /**
3491
3077
  * Maximum time between the value of two frames, beyond which we
3492
3078
  * assume the velocity has since been 0.
@@ -3543,6 +3129,11 @@ class MotionValue {
3543
3129
  // Update update subscribers
3544
3130
  if (this.current !== this.prev) {
3545
3131
  this.events.change?.notify(this.current);
3132
+ if (this.dependents) {
3133
+ for (const dependent of this.dependents) {
3134
+ dependent.dirty();
3135
+ }
3136
+ }
3546
3137
  }
3547
3138
  // Update render subscribers
3548
3139
  if (render) {
@@ -3684,6 +3275,20 @@ class MotionValue {
3684
3275
  if (this.stopPassiveEffect)
3685
3276
  this.stopPassiveEffect();
3686
3277
  }
3278
+ dirty() {
3279
+ this.events.change?.notify(this.current);
3280
+ }
3281
+ addDependent(dependent) {
3282
+ if (!this.dependents) {
3283
+ this.dependents = new Set();
3284
+ }
3285
+ this.dependents.add(dependent);
3286
+ }
3287
+ removeDependent(dependent) {
3288
+ if (this.dependents) {
3289
+ this.dependents.delete(dependent);
3290
+ }
3291
+ }
3687
3292
  /**
3688
3293
  * Returns the latest state of `MotionValue`
3689
3294
  *
@@ -3748,50 +3353,558 @@ class MotionValue {
3748
3353
  });
3749
3354
  }
3750
3355
  /**
3751
- * Stop the currently active animation.
3752
- *
3753
- * @public
3356
+ * Stop the currently active animation.
3357
+ *
3358
+ * @public
3359
+ */
3360
+ stop() {
3361
+ if (this.animation) {
3362
+ this.animation.stop();
3363
+ if (this.events.animationCancel) {
3364
+ this.events.animationCancel.notify();
3365
+ }
3366
+ }
3367
+ this.clearAnimation();
3368
+ }
3369
+ /**
3370
+ * Returns `true` if this value is currently animating.
3371
+ *
3372
+ * @public
3373
+ */
3374
+ isAnimating() {
3375
+ return !!this.animation;
3376
+ }
3377
+ clearAnimation() {
3378
+ delete this.animation;
3379
+ }
3380
+ /**
3381
+ * Destroy and clean up subscribers to this `MotionValue`.
3382
+ *
3383
+ * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
3384
+ * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
3385
+ * created a `MotionValue` via the `motionValue` function.
3386
+ *
3387
+ * @public
3388
+ */
3389
+ destroy() {
3390
+ this.dependents?.clear();
3391
+ this.events.destroy?.notify();
3392
+ this.clearListeners();
3393
+ this.stop();
3394
+ if (this.stopPassiveEffect) {
3395
+ this.stopPassiveEffect();
3396
+ }
3397
+ }
3398
+ }
3399
+ function motionValue(init, options) {
3400
+ return new MotionValue(init, options);
3401
+ }
3402
+
3403
+ /**
3404
+ * Provided a value and a ValueType, returns the value as that value type.
3405
+ */
3406
+ const getValueAsType = (value, type) => {
3407
+ return type && typeof value === "number"
3408
+ ? type.transform(value)
3409
+ : value;
3410
+ };
3411
+
3412
+ class MotionValueState {
3413
+ constructor() {
3414
+ this.latest = {};
3415
+ this.values = new Map();
3416
+ }
3417
+ set(name, value, render, computed) {
3418
+ const existingValue = this.values.get(name);
3419
+ if (existingValue) {
3420
+ existingValue.onRemove();
3421
+ }
3422
+ const onChange = () => {
3423
+ this.latest[name] = getValueAsType(value.get(), numberValueTypes[name]);
3424
+ render && frame.render(render);
3425
+ };
3426
+ onChange();
3427
+ const cancelOnChange = value.on("change", onChange);
3428
+ computed && value.addDependent(computed);
3429
+ const remove = () => {
3430
+ cancelOnChange();
3431
+ render && cancelFrame(render);
3432
+ this.values.delete(name);
3433
+ computed && value.removeDependent(computed);
3434
+ };
3435
+ this.values.set(name, { value, onRemove: remove });
3436
+ return remove;
3437
+ }
3438
+ get(name) {
3439
+ return this.values.get(name)?.value;
3440
+ }
3441
+ destroy() {
3442
+ for (const value of this.values.values()) {
3443
+ value.onRemove();
3444
+ }
3445
+ }
3446
+ }
3447
+
3448
+ const translateAlias = {
3449
+ x: "translateX",
3450
+ y: "translateY",
3451
+ z: "translateZ",
3452
+ transformPerspective: "perspective",
3453
+ };
3454
+ function buildTransform(state) {
3455
+ let transform = "";
3456
+ let transformIsDefault = true;
3457
+ /**
3458
+ * Loop over all possible transforms in order, adding the ones that
3459
+ * are present to the transform string.
3460
+ */
3461
+ for (let i = 0; i < transformPropOrder.length; i++) {
3462
+ const key = transformPropOrder[i];
3463
+ const value = state.latest[key];
3464
+ if (value === undefined)
3465
+ continue;
3466
+ let valueIsDefault = true;
3467
+ if (typeof value === "number") {
3468
+ valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
3469
+ }
3470
+ else {
3471
+ valueIsDefault = parseFloat(value) === 0;
3472
+ }
3473
+ if (!valueIsDefault) {
3474
+ transformIsDefault = false;
3475
+ const transformName = translateAlias[key] || key;
3476
+ const valueToRender = state.latest[key];
3477
+ transform += `${transformName}(${valueToRender}) `;
3478
+ }
3479
+ }
3480
+ return transformIsDefault ? "none" : transform.trim();
3481
+ }
3482
+
3483
+ const stateMap = new WeakMap();
3484
+ function styleEffect(subject, values) {
3485
+ const elements = resolveElements(subject);
3486
+ const subscriptions = [];
3487
+ for (let i = 0; i < elements.length; i++) {
3488
+ const element = elements[i];
3489
+ const state = stateMap.get(element) ?? new MotionValueState();
3490
+ stateMap.set(element, state);
3491
+ for (const key in values) {
3492
+ const value = values[key];
3493
+ const remove = addValue(element, state, key, value);
3494
+ subscriptions.push(remove);
3495
+ }
3496
+ }
3497
+ return () => {
3498
+ for (const cancel of subscriptions)
3499
+ cancel();
3500
+ };
3501
+ }
3502
+ function addValue(element, state, key, value) {
3503
+ let render = undefined;
3504
+ let computed = undefined;
3505
+ if (transformProps.has(key)) {
3506
+ if (!state.get("transform")) {
3507
+ state.set("transform", new MotionValue("none"), () => {
3508
+ element.style.transform = buildTransform(state);
3509
+ });
3510
+ }
3511
+ computed = state.get("transform");
3512
+ }
3513
+ else if (isCSSVar(key)) {
3514
+ render = () => {
3515
+ element.style.setProperty(key, state.latest[key]);
3516
+ };
3517
+ }
3518
+ else {
3519
+ render = () => {
3520
+ element.style[key] = state.latest[key];
3521
+ };
3522
+ }
3523
+ return state.set(key, value, render, computed);
3524
+ }
3525
+
3526
+ const { schedule: microtask, cancel: cancelMicrotask } =
3527
+ /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
3528
+
3529
+ const isDragging = {
3530
+ x: false,
3531
+ y: false,
3532
+ };
3533
+ function isDragActive() {
3534
+ return isDragging.x || isDragging.y;
3535
+ }
3536
+
3537
+ function setDragLock(axis) {
3538
+ if (axis === "x" || axis === "y") {
3539
+ if (isDragging[axis]) {
3540
+ return null;
3541
+ }
3542
+ else {
3543
+ isDragging[axis] = true;
3544
+ return () => {
3545
+ isDragging[axis] = false;
3546
+ };
3547
+ }
3548
+ }
3549
+ else {
3550
+ if (isDragging.x || isDragging.y) {
3551
+ return null;
3552
+ }
3553
+ else {
3554
+ isDragging.x = isDragging.y = true;
3555
+ return () => {
3556
+ isDragging.x = isDragging.y = false;
3557
+ };
3558
+ }
3559
+ }
3560
+ }
3561
+
3562
+ function setupGesture(elementOrSelector, options) {
3563
+ const elements = resolveElements(elementOrSelector);
3564
+ const gestureAbortController = new AbortController();
3565
+ const eventOptions = {
3566
+ passive: true,
3567
+ ...options,
3568
+ signal: gestureAbortController.signal,
3569
+ };
3570
+ const cancel = () => gestureAbortController.abort();
3571
+ return [elements, eventOptions, cancel];
3572
+ }
3573
+
3574
+ function isValidHover(event) {
3575
+ return !(event.pointerType === "touch" || isDragActive());
3576
+ }
3577
+ /**
3578
+ * Create a hover gesture. hover() is different to .addEventListener("pointerenter")
3579
+ * in that it has an easier syntax, filters out polyfilled touch events, interoperates
3580
+ * with drag gestures, and automatically removes the "pointerennd" event listener when the hover ends.
3581
+ *
3582
+ * @public
3583
+ */
3584
+ function hover(elementOrSelector, onHoverStart, options = {}) {
3585
+ const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options);
3586
+ const onPointerEnter = (enterEvent) => {
3587
+ if (!isValidHover(enterEvent))
3588
+ return;
3589
+ const { target } = enterEvent;
3590
+ const onHoverEnd = onHoverStart(target, enterEvent);
3591
+ if (typeof onHoverEnd !== "function" || !target)
3592
+ return;
3593
+ const onPointerLeave = (leaveEvent) => {
3594
+ if (!isValidHover(leaveEvent))
3595
+ return;
3596
+ onHoverEnd(leaveEvent);
3597
+ target.removeEventListener("pointerleave", onPointerLeave);
3598
+ };
3599
+ target.addEventListener("pointerleave", onPointerLeave, eventOptions);
3600
+ };
3601
+ elements.forEach((element) => {
3602
+ element.addEventListener("pointerenter", onPointerEnter, eventOptions);
3603
+ });
3604
+ return cancel;
3605
+ }
3606
+
3607
+ /**
3608
+ * Recursively traverse up the tree to check whether the provided child node
3609
+ * is the parent or a descendant of it.
3610
+ *
3611
+ * @param parent - Element to find
3612
+ * @param child - Element to test against parent
3613
+ */
3614
+ const isNodeOrChild = (parent, child) => {
3615
+ if (!child) {
3616
+ return false;
3617
+ }
3618
+ else if (parent === child) {
3619
+ return true;
3620
+ }
3621
+ else {
3622
+ return isNodeOrChild(parent, child.parentElement);
3623
+ }
3624
+ };
3625
+
3626
+ const isPrimaryPointer = (event) => {
3627
+ if (event.pointerType === "mouse") {
3628
+ return typeof event.button !== "number" || event.button <= 0;
3629
+ }
3630
+ else {
3631
+ /**
3632
+ * isPrimary is true for all mice buttons, whereas every touch point
3633
+ * is regarded as its own input. So subsequent concurrent touch points
3634
+ * will be false.
3635
+ *
3636
+ * Specifically match against false here as incomplete versions of
3637
+ * PointerEvents in very old browser might have it set as undefined.
3638
+ */
3639
+ return event.isPrimary !== false;
3640
+ }
3641
+ };
3642
+
3643
+ const focusableElements = new Set([
3644
+ "BUTTON",
3645
+ "INPUT",
3646
+ "SELECT",
3647
+ "TEXTAREA",
3648
+ "A",
3649
+ ]);
3650
+ function isElementKeyboardAccessible(element) {
3651
+ return (focusableElements.has(element.tagName) ||
3652
+ element.tabIndex !== -1);
3653
+ }
3654
+
3655
+ const isPressing = new WeakSet();
3656
+
3657
+ /**
3658
+ * Filter out events that are not "Enter" keys.
3659
+ */
3660
+ function filterEvents(callback) {
3661
+ return (event) => {
3662
+ if (event.key !== "Enter")
3663
+ return;
3664
+ callback(event);
3665
+ };
3666
+ }
3667
+ function firePointerEvent(target, type) {
3668
+ target.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true }));
3669
+ }
3670
+ const enableKeyboardPress = (focusEvent, eventOptions) => {
3671
+ const element = focusEvent.currentTarget;
3672
+ if (!element)
3673
+ return;
3674
+ const handleKeydown = filterEvents(() => {
3675
+ if (isPressing.has(element))
3676
+ return;
3677
+ firePointerEvent(element, "down");
3678
+ const handleKeyup = filterEvents(() => {
3679
+ firePointerEvent(element, "up");
3680
+ });
3681
+ const handleBlur = () => firePointerEvent(element, "cancel");
3682
+ element.addEventListener("keyup", handleKeyup, eventOptions);
3683
+ element.addEventListener("blur", handleBlur, eventOptions);
3684
+ });
3685
+ element.addEventListener("keydown", handleKeydown, eventOptions);
3686
+ /**
3687
+ * Add an event listener that fires on blur to remove the keydown events.
3754
3688
  */
3755
- stop() {
3756
- if (this.animation) {
3757
- this.animation.stop();
3758
- if (this.events.animationCancel) {
3759
- this.events.animationCancel.notify();
3689
+ element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions);
3690
+ };
3691
+
3692
+ /**
3693
+ * Filter out events that are not primary pointer events, or are triggering
3694
+ * while a Motion gesture is active.
3695
+ */
3696
+ function isValidPressEvent(event) {
3697
+ return isPrimaryPointer(event) && !isDragActive();
3698
+ }
3699
+ /**
3700
+ * Create a press gesture.
3701
+ *
3702
+ * Press is different to `"pointerdown"`, `"pointerup"` in that it
3703
+ * automatically filters out secondary pointer events like right
3704
+ * click and multitouch.
3705
+ *
3706
+ * It also adds accessibility support for keyboards, where
3707
+ * an element with a press gesture will receive focus and
3708
+ * trigger on Enter `"keydown"` and `"keyup"` events.
3709
+ *
3710
+ * This is different to a browser's `"click"` event, which does
3711
+ * respond to keyboards but only for the `"click"` itself, rather
3712
+ * than the press start and end/cancel. The element also needs
3713
+ * to be focusable for this to work, whereas a press gesture will
3714
+ * make an element focusable by default.
3715
+ *
3716
+ * @public
3717
+ */
3718
+ function press(targetOrSelector, onPressStart, options = {}) {
3719
+ const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);
3720
+ const startPress = (startEvent) => {
3721
+ const target = startEvent.currentTarget;
3722
+ if (!isValidPressEvent(startEvent) || isPressing.has(target))
3723
+ return;
3724
+ isPressing.add(target);
3725
+ const onPressEnd = onPressStart(target, startEvent);
3726
+ const onPointerEnd = (endEvent, success) => {
3727
+ window.removeEventListener("pointerup", onPointerUp);
3728
+ window.removeEventListener("pointercancel", onPointerCancel);
3729
+ if (isPressing.has(target)) {
3730
+ isPressing.delete(target);
3731
+ }
3732
+ if (!isValidPressEvent(endEvent)) {
3733
+ return;
3734
+ }
3735
+ if (typeof onPressEnd === "function") {
3736
+ onPressEnd(endEvent, { success });
3737
+ }
3738
+ };
3739
+ const onPointerUp = (upEvent) => {
3740
+ onPointerEnd(upEvent, target === window ||
3741
+ target === document ||
3742
+ options.useGlobalTarget ||
3743
+ isNodeOrChild(target, upEvent.target));
3744
+ };
3745
+ const onPointerCancel = (cancelEvent) => {
3746
+ onPointerEnd(cancelEvent, false);
3747
+ };
3748
+ window.addEventListener("pointerup", onPointerUp, eventOptions);
3749
+ window.addEventListener("pointercancel", onPointerCancel, eventOptions);
3750
+ };
3751
+ targets.forEach((target) => {
3752
+ const pointerDownTarget = options.useGlobalTarget ? window : target;
3753
+ pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions);
3754
+ if (target instanceof HTMLElement) {
3755
+ target.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions));
3756
+ if (!isElementKeyboardAccessible(target) &&
3757
+ !target.hasAttribute("tabindex")) {
3758
+ target.tabIndex = 0;
3760
3759
  }
3761
3760
  }
3762
- this.clearAnimation();
3761
+ });
3762
+ return cancelEvents;
3763
+ }
3764
+
3765
+ function getComputedStyle$1(element, name) {
3766
+ const computedStyle = window.getComputedStyle(element);
3767
+ return isCSSVar(name)
3768
+ ? computedStyle.getPropertyValue(name)
3769
+ : computedStyle[name];
3770
+ }
3771
+
3772
+ function observeTimeline(update, timeline) {
3773
+ let prevProgress;
3774
+ const onFrame = () => {
3775
+ const { currentTime } = timeline;
3776
+ const percentage = currentTime === null ? 0 : currentTime.value;
3777
+ const progress = percentage / 100;
3778
+ if (prevProgress !== progress) {
3779
+ update(progress);
3780
+ }
3781
+ prevProgress = progress;
3782
+ };
3783
+ frame.preUpdate(onFrame, true);
3784
+ return () => cancelFrame(onFrame);
3785
+ }
3786
+
3787
+ function record() {
3788
+ const { value } = statsBuffer;
3789
+ if (value === null) {
3790
+ cancelFrame(record);
3791
+ return;
3763
3792
  }
3764
- /**
3765
- * Returns `true` if this value is currently animating.
3766
- *
3767
- * @public
3768
- */
3769
- isAnimating() {
3770
- return !!this.animation;
3793
+ value.frameloop.rate.push(frameData.delta);
3794
+ value.animations.mainThread.push(activeAnimations.mainThread);
3795
+ value.animations.waapi.push(activeAnimations.waapi);
3796
+ value.animations.layout.push(activeAnimations.layout);
3797
+ }
3798
+ function mean(values) {
3799
+ return values.reduce((acc, value) => acc + value, 0) / values.length;
3800
+ }
3801
+ function summarise(values, calcAverage = mean) {
3802
+ if (values.length === 0) {
3803
+ return {
3804
+ min: 0,
3805
+ max: 0,
3806
+ avg: 0,
3807
+ };
3771
3808
  }
3772
- clearAnimation() {
3773
- delete this.animation;
3809
+ return {
3810
+ min: Math.min(...values),
3811
+ max: Math.max(...values),
3812
+ avg: calcAverage(values),
3813
+ };
3814
+ }
3815
+ const msToFps = (ms) => Math.round(1000 / ms);
3816
+ function clearStatsBuffer() {
3817
+ statsBuffer.value = null;
3818
+ statsBuffer.addProjectionMetrics = null;
3819
+ }
3820
+ function reportStats() {
3821
+ const { value } = statsBuffer;
3822
+ if (!value) {
3823
+ throw new Error("Stats are not being measured");
3774
3824
  }
3825
+ clearStatsBuffer();
3826
+ cancelFrame(record);
3827
+ const summary = {
3828
+ frameloop: {
3829
+ setup: summarise(value.frameloop.setup),
3830
+ rate: summarise(value.frameloop.rate),
3831
+ read: summarise(value.frameloop.read),
3832
+ resolveKeyframes: summarise(value.frameloop.resolveKeyframes),
3833
+ preUpdate: summarise(value.frameloop.preUpdate),
3834
+ update: summarise(value.frameloop.update),
3835
+ preRender: summarise(value.frameloop.preRender),
3836
+ render: summarise(value.frameloop.render),
3837
+ postRender: summarise(value.frameloop.postRender),
3838
+ },
3839
+ animations: {
3840
+ mainThread: summarise(value.animations.mainThread),
3841
+ waapi: summarise(value.animations.waapi),
3842
+ layout: summarise(value.animations.layout),
3843
+ },
3844
+ layoutProjection: {
3845
+ nodes: summarise(value.layoutProjection.nodes),
3846
+ calculatedTargetDeltas: summarise(value.layoutProjection.calculatedTargetDeltas),
3847
+ calculatedProjections: summarise(value.layoutProjection.calculatedProjections),
3848
+ },
3849
+ };
3775
3850
  /**
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
3851
+ * Convert the rate to FPS
3783
3852
  */
3784
- destroy() {
3785
- this.events.destroy?.notify();
3786
- this.clearListeners();
3787
- this.stop();
3788
- if (this.stopPassiveEffect) {
3789
- this.stopPassiveEffect();
3790
- }
3853
+ const { rate } = summary.frameloop;
3854
+ rate.min = msToFps(rate.min);
3855
+ rate.max = msToFps(rate.max);
3856
+ rate.avg = msToFps(rate.avg);
3857
+ [rate.min, rate.max] = [rate.max, rate.min];
3858
+ return summary;
3859
+ }
3860
+ function recordStats() {
3861
+ if (statsBuffer.value) {
3862
+ clearStatsBuffer();
3863
+ throw new Error("Stats are already being measured");
3791
3864
  }
3865
+ const newStatsBuffer = statsBuffer;
3866
+ newStatsBuffer.value = {
3867
+ frameloop: {
3868
+ setup: [],
3869
+ rate: [],
3870
+ read: [],
3871
+ resolveKeyframes: [],
3872
+ preUpdate: [],
3873
+ update: [],
3874
+ preRender: [],
3875
+ render: [],
3876
+ postRender: [],
3877
+ },
3878
+ animations: {
3879
+ mainThread: [],
3880
+ waapi: [],
3881
+ layout: [],
3882
+ },
3883
+ layoutProjection: {
3884
+ nodes: [],
3885
+ calculatedTargetDeltas: [],
3886
+ calculatedProjections: [],
3887
+ },
3888
+ };
3889
+ newStatsBuffer.addProjectionMetrics = (metrics) => {
3890
+ const { layoutProjection } = newStatsBuffer.value;
3891
+ layoutProjection.nodes.push(metrics.nodes);
3892
+ layoutProjection.calculatedTargetDeltas.push(metrics.calculatedTargetDeltas);
3893
+ layoutProjection.calculatedProjections.push(metrics.calculatedProjections);
3894
+ };
3895
+ frame.postRender(record, true);
3896
+ return reportStats;
3792
3897
  }
3793
- function motionValue(init, options) {
3794
- return new MotionValue(init, options);
3898
+
3899
+ function transform(...args) {
3900
+ const useImmediate = !Array.isArray(args[0]);
3901
+ const argOffset = useImmediate ? 0 : -1;
3902
+ const inputValue = args[0 + argOffset];
3903
+ const inputRange = args[1 + argOffset];
3904
+ const outputRange = args[2 + argOffset];
3905
+ const options = args[3 + argOffset];
3906
+ const interpolator = interpolate(inputRange, outputRange, options);
3907
+ return useImmediate ? interpolator(inputValue) : interpolator;
3795
3908
  }
3796
3909
 
3797
3910
  function subscribeValue(inputValues, outputValue, getLatest) {
@@ -3886,15 +3999,6 @@ const valueTypes = [...dimensionValueTypes, color, complex];
3886
3999
  */
3887
4000
  const findValueType = (v) => valueTypes.find(testValueType(v));
3888
4001
 
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
4002
  function chooseLayerType(valueName) {
3899
4003
  if (valueName === "layout")
3900
4004
  return "group";