motion-dom 12.27.0-alpha.4 → 12.27.0-alpha.6

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
@@ -7599,6 +7599,13 @@ function createProjectionNode$1({ attachResizeListener, defaultParent, measureSc
7599
7599
  this.relativeTarget = undefined;
7600
7600
  return;
7601
7601
  }
7602
+ /**
7603
+ * Check if this is a follow element in a crossfade (exiting element
7604
+ * whose lead has resumeFrom pointing to it). These elements should
7605
+ * NOT create their own animation - they get the lead's animation via
7606
+ * resumingFrom.currentAnimation in startAnimation().
7607
+ */
7608
+ const isFollowInCrossfade = this.isPresent === false && !this.isLead();
7602
7609
  // TODO: Check here if an animation exists
7603
7610
  const layoutTransition = this.options.transition ||
7604
7611
  visualElement.getDefaultTransition() ||
@@ -7622,43 +7629,51 @@ function createProjectionNode$1({ attachResizeListener, defaultParent, measureSc
7622
7629
  * relative to its parent has indeed changed. So here we check for that.
7623
7630
  */
7624
7631
  const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeLayoutChanged;
7625
- if (this.options.layoutRoot ||
7626
- this.resumeFrom ||
7627
- hasOnlyRelativeTargetChanged ||
7628
- (hasLayoutChanged &&
7629
- (hasTargetChanged || !this.currentAnimation))) {
7630
- if (this.resumeFrom) {
7631
- this.resumingFrom = this.resumeFrom;
7632
- this.resumingFrom.resumingFrom = undefined;
7633
- }
7634
- const animationOptions = {
7635
- ...getValueTransition(layoutTransition, "layout"),
7636
- onPlay: onLayoutAnimationStart,
7637
- onComplete: onLayoutAnimationComplete,
7638
- };
7639
- if (visualElement.shouldReduceMotion ||
7640
- this.options.layoutRoot) {
7641
- animationOptions.delay = 0;
7642
- animationOptions.type = false;
7643
- }
7644
- this.startAnimation(animationOptions);
7645
- /**
7646
- * Set animation origin after starting animation to avoid layout jump
7647
- * caused by stopping previous layout animation
7648
- */
7649
- this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged);
7650
- }
7651
- else {
7652
- /**
7653
- * If the layout hasn't changed and we have an animation that hasn't started yet,
7654
- * finish it immediately. Otherwise it will be animating from a location
7655
- * that was probably never committed to screen and look like a jumpy box.
7656
- */
7657
- if (!hasLayoutChanged) {
7658
- finishAnimation(this);
7632
+ /**
7633
+ * Skip animation handling for follow elements in a crossfade.
7634
+ * These elements get the lead's animation via resumingFrom.currentAnimation
7635
+ * in startAnimation(), so they shouldn't create their own animation.
7636
+ * They also shouldn't call finishAnimation(), which would reset their state.
7637
+ */
7638
+ if (!isFollowInCrossfade) {
7639
+ if (this.options.layoutRoot ||
7640
+ this.resumeFrom ||
7641
+ hasOnlyRelativeTargetChanged ||
7642
+ (hasLayoutChanged &&
7643
+ (hasTargetChanged || !this.currentAnimation))) {
7644
+ if (this.resumeFrom) {
7645
+ this.resumingFrom = this.resumeFrom;
7646
+ this.resumingFrom.resumingFrom = undefined;
7647
+ }
7648
+ const animationOptions = {
7649
+ ...getValueTransition(layoutTransition, "layout"),
7650
+ onPlay: onLayoutAnimationStart,
7651
+ onComplete: onLayoutAnimationComplete,
7652
+ };
7653
+ if (visualElement.shouldReduceMotion ||
7654
+ this.options.layoutRoot) {
7655
+ animationOptions.delay = 0;
7656
+ animationOptions.type = false;
7657
+ }
7658
+ this.startAnimation(animationOptions);
7659
+ /**
7660
+ * Set animation origin after starting animation to avoid layout jump
7661
+ * caused by stopping previous layout animation
7662
+ */
7663
+ this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged);
7659
7664
  }
7660
- if (this.isLead() && this.options.onExitComplete) {
7661
- this.options.onExitComplete();
7665
+ else {
7666
+ /**
7667
+ * If the layout hasn't changed and we have an animation that hasn't started yet,
7668
+ * finish it immediately. Otherwise it will be animating from a location
7669
+ * that was probably never committed to screen and look like a jumpy box.
7670
+ */
7671
+ if (!hasLayoutChanged) {
7672
+ finishAnimation(this);
7673
+ }
7674
+ if (this.isLead() && this.options.onExitComplete) {
7675
+ this.options.onExitComplete();
7676
+ }
7662
7677
  }
7663
7678
  }
7664
7679
  this.targetLayout = newLayout;
@@ -9033,6 +9048,7 @@ function detectMutations(beforeRecords, scope) {
9033
9048
  const persisting = [];
9034
9049
  const sharedEntering = new Map();
9035
9050
  const sharedExiting = new Map();
9051
+ const sharedPersisting = new Map();
9036
9052
  // Find exiting elements (were in before, not in after)
9037
9053
  for (const element of beforeElements) {
9038
9054
  if (!afterElements.has(element)) {
@@ -9060,40 +9076,32 @@ function detectMutations(beforeRecords, scope) {
9060
9076
  persisting.push(element);
9061
9077
  }
9062
9078
  }
9079
+ // Find persisting elements that share a layoutId with exiting elements
9080
+ // This handles the A -> AB -> A pattern where A persists and B exits
9081
+ for (const element of persisting) {
9082
+ const layoutId = getLayoutId(element);
9083
+ if (layoutId && sharedExiting.has(layoutId)) {
9084
+ sharedPersisting.set(layoutId, element);
9085
+ }
9086
+ }
9063
9087
  return {
9064
9088
  entering,
9065
9089
  exiting,
9066
9090
  persisting,
9067
9091
  sharedEntering,
9068
9092
  sharedExiting,
9093
+ sharedPersisting,
9069
9094
  };
9070
9095
  }
9071
- /**
9072
- * Check if an element is a "root" entering element (no entering ancestors)
9073
- */
9074
- function isRootEnteringElement(element, allEntering) {
9075
- let parent = element.parentElement;
9076
- while (parent) {
9077
- if (allEntering.has(parent))
9078
- return false;
9079
- parent = parent.parentElement;
9080
- }
9081
- return true;
9082
- }
9083
- /**
9084
- * Check if an element is a "root" exiting element (no exiting ancestors)
9085
- */
9086
- function isRootExitingElement(element, allExiting) {
9087
- let parent = element.parentElement;
9088
- while (parent) {
9089
- if (allExiting.has(parent))
9090
- return false;
9091
- parent = parent.parentElement;
9092
- }
9093
- return true;
9094
- }
9095
9096
 
9096
9097
  let scaleCorrectorAdded = false;
9098
+ /**
9099
+ * Track active projection nodes per element to handle animation interruption.
9100
+ * When a new animation starts on an element that already has an active animation,
9101
+ * we need to stop the old animation so the new one can start from the current
9102
+ * visual position.
9103
+ */
9104
+ const activeProjectionNodes = new WeakMap();
9097
9105
  function ensureScaleCorrectors() {
9098
9106
  if (scaleCorrectorAdded)
9099
9107
  return;
@@ -9141,9 +9149,31 @@ function findProjectionParent(element, nodeCache) {
9141
9149
  return undefined;
9142
9150
  }
9143
9151
  /**
9144
- * Create a single projection node for an element
9152
+ * Create or reuse a projection node for an element
9145
9153
  */
9146
9154
  function createProjectionNode(element, parent, options, transition) {
9155
+ // Check for existing active node - reuse it to preserve animation state
9156
+ const existingNode = activeProjectionNodes.get(element);
9157
+ if (existingNode) {
9158
+ const visualElement = existingNode.options.visualElement;
9159
+ // Update transition options for the new animation
9160
+ const nodeTransition = transition
9161
+ ? { duration: transition.duration, ease: transition.ease }
9162
+ : { duration: 0.3, ease: "easeOut" };
9163
+ existingNode.setOptions({
9164
+ ...existingNode.options,
9165
+ animate: true,
9166
+ transition: nodeTransition,
9167
+ ...options,
9168
+ });
9169
+ // Re-mount the node if it was previously unmounted
9170
+ // This re-adds it to root.nodes so didUpdate() will process it
9171
+ if (!existingNode.instance) {
9172
+ existingNode.mount(element);
9173
+ }
9174
+ return { node: existingNode, visualElement };
9175
+ }
9176
+ // No existing node - create a new one
9147
9177
  const latestValues = {};
9148
9178
  const visualElement = new HTMLVisualElement({
9149
9179
  visualState: {
@@ -9172,6 +9202,8 @@ function createProjectionNode(element, parent, options, transition) {
9172
9202
  });
9173
9203
  node.mount(element);
9174
9204
  visualElement.projection = node;
9205
+ // Track this node as the active one for this element
9206
+ activeProjectionNodes.set(element, node);
9175
9207
  return { node, visualElement };
9176
9208
  }
9177
9209
  /**
@@ -9230,15 +9262,28 @@ function parseLayoutMode(value) {
9230
9262
  return "both";
9231
9263
  }
9232
9264
  /**
9233
- * Clean up projection nodes
9265
+ * Clean up projection nodes for specific elements.
9266
+ * If elementsToCleanup is provided, only those elements are cleaned up.
9267
+ * If not provided, all nodes are cleaned up.
9268
+ *
9269
+ * This allows persisting elements to keep their nodes between animations,
9270
+ * matching React's behavior where nodes persist for elements that remain in the DOM.
9234
9271
  */
9235
- function cleanupProjectionTree(context) {
9236
- for (const node of context.nodes.values()) {
9272
+ function cleanupProjectionTree(context, elementsToCleanup) {
9273
+ const elementsToProcess = elementsToCleanup
9274
+ ? [...context.nodes.entries()].filter(([el]) => elementsToCleanup.has(el))
9275
+ : [...context.nodes.entries()];
9276
+ for (const [element, node] of elementsToProcess) {
9237
9277
  context.group.remove(node);
9238
9278
  node.unmount();
9279
+ // Only clear from activeProjectionNodes if this is still the active node.
9280
+ // A newer animation might have already taken over.
9281
+ if (activeProjectionNodes.get(element) === node) {
9282
+ activeProjectionNodes.delete(element);
9283
+ }
9284
+ context.nodes.delete(element);
9285
+ context.visualElements.delete(element);
9239
9286
  }
9240
- context.nodes.clear();
9241
- context.visualElements.clear();
9242
9287
  }
9243
9288
 
9244
9289
  class LayoutAnimationBuilder {
@@ -9255,16 +9300,6 @@ class LayoutAnimationBuilder {
9255
9300
  // Queue execution on microtask to allow builder methods to be called
9256
9301
  queueMicrotask(() => this.execute());
9257
9302
  }
9258
- enter(keyframes, options) {
9259
- this.enterKeyframes = keyframes;
9260
- this.enterOptions = options;
9261
- return this;
9262
- }
9263
- exit(keyframes, options) {
9264
- this.exitKeyframes = keyframes;
9265
- this.exitOptions = options;
9266
- return this;
9267
- }
9268
9303
  shared(layoutIdOrOptions, options) {
9269
9304
  if (typeof layoutIdOrOptions === "string") {
9270
9305
  this.sharedTransitions.set(layoutIdOrOptions, options);
@@ -9308,13 +9343,16 @@ class LayoutAnimationBuilder {
9308
9343
  this.updateDom();
9309
9344
  // Phase 3: Post-mutation (Detect & Prepare)
9310
9345
  const mutationResult = detectMutations(beforeRecords, this.scope);
9311
- // Reattach exiting elements that are NOT part of shared transitions
9312
- // Shared elements are handled by the projection system via resumeFrom
9313
- const nonSharedExiting = mutationResult.exiting.filter(({ element }) => {
9346
+ // Determine which exiting elements should be reattached:
9347
+ // Non-shared exiting elements (no layoutId or no matching entering/persisting element)
9348
+ const exitingToReattach = mutationResult.exiting.filter(({ element }) => {
9314
9349
  const layoutId = element.getAttribute("data-layout-id");
9315
- return !layoutId || !mutationResult.sharedEntering.has(layoutId);
9350
+ const isSharedWithEntering = layoutId && mutationResult.sharedEntering.has(layoutId);
9351
+ const isSharedWithPersisting = layoutId && mutationResult.sharedPersisting.has(layoutId);
9352
+ // Reattach if not a shared element
9353
+ return !isSharedWithEntering && !isSharedWithPersisting;
9316
9354
  });
9317
- this.reattachExitingElements(nonSharedExiting, context);
9355
+ this.reattachExitingElements(exitingToReattach, context);
9318
9356
  // Build projection nodes for entering elements
9319
9357
  if (mutationResult.entering.length > 0) {
9320
9358
  context = buildProjectionTree(mutationResult.entering, context, this.getBuildOptions());
@@ -9323,24 +9361,45 @@ class LayoutAnimationBuilder {
9323
9361
  if (!context && mutationResult.persisting.length > 0) {
9324
9362
  context = buildProjectionTree(mutationResult.persisting, undefined, this.getBuildOptions());
9325
9363
  }
9326
- // Build set of shared exiting elements to exclude from animation collection
9327
- // Their nodes are still in the tree for resumeFrom relationship, but we don't animate them
9364
+ // Build set of shared exiting elements (they don't animate separately)
9328
9365
  const sharedExitingElements = new Set();
9329
- for (const [layoutId] of mutationResult.sharedEntering) {
9366
+ for (const [layoutId, enteringElement] of mutationResult.sharedEntering) {
9330
9367
  const exitingElement = mutationResult.sharedExiting.get(layoutId);
9331
9368
  if (exitingElement) {
9332
9369
  sharedExitingElements.add(exitingElement);
9333
- // Remove the exiting node from the shared stack so that crossfade
9334
- // doesn't trigger. When an element is removed from the DOM, it can't
9335
- // participate in crossfade (no element to fade out). The entering
9336
- // element still has resumeFrom set for position morphing.
9337
9370
  const exitingNode = context?.nodes.get(exitingElement);
9338
- if (exitingNode) {
9371
+ const enteringNode = context?.nodes.get(enteringElement);
9372
+ if (exitingNode && enteringNode) {
9373
+ // Remove exiting node from stack, no crossfade
9339
9374
  const stack = exitingNode.getStack();
9340
9375
  if (stack) {
9341
9376
  stack.remove(exitingNode);
9342
9377
  }
9343
9378
  }
9379
+ else if (exitingNode && !enteringNode) {
9380
+ // Fallback: If entering node doesn't exist yet, just handle exiting
9381
+ const stack = exitingNode.getStack();
9382
+ if (stack) {
9383
+ stack.remove(exitingNode);
9384
+ }
9385
+ }
9386
+ }
9387
+ }
9388
+ // Handle A -> AB -> A pattern: persisting element should become lead again
9389
+ // when exiting element with same layoutId is removed
9390
+ for (const [layoutId, persistingElement] of mutationResult.sharedPersisting) {
9391
+ const exitingElement = mutationResult.sharedExiting.get(layoutId);
9392
+ if (!exitingElement)
9393
+ continue;
9394
+ sharedExitingElements.add(exitingElement);
9395
+ const exitingNode = context?.nodes.get(exitingElement);
9396
+ const persistingNode = context?.nodes.get(persistingElement);
9397
+ if (exitingNode && persistingNode) {
9398
+ // Remove exiting node from stack, no crossfade
9399
+ const stack = exitingNode.getStack();
9400
+ if (stack) {
9401
+ stack.remove(exitingNode);
9402
+ }
9344
9403
  }
9345
9404
  }
9346
9405
  // Phase 4: Animate
@@ -9349,7 +9408,8 @@ class LayoutAnimationBuilder {
9349
9408
  context.root.didUpdate();
9350
9409
  // Wait for animations to be created (they're scheduled via frame.update)
9351
9410
  await new Promise((resolve) => frame.postRender(() => resolve()));
9352
- // Collect layout animations from projection nodes (excluding shared exiting elements)
9411
+ // Collect layout animations from projection nodes
9412
+ // Skip shared exiting elements (they don't animate)
9353
9413
  for (const [element, node] of context.nodes.entries()) {
9354
9414
  if (sharedExitingElements.has(element))
9355
9415
  continue;
@@ -9357,31 +9417,25 @@ class LayoutAnimationBuilder {
9357
9417
  animations.push(node.currentAnimation);
9358
9418
  }
9359
9419
  }
9360
- // Apply enter keyframes to root entering elements
9361
- if (this.enterKeyframes) {
9362
- const enterAnimations = this.animateEntering(mutationResult, context);
9363
- animations.push(...enterAnimations);
9364
- }
9365
- // Apply exit keyframes to root exiting elements
9366
- if (this.exitKeyframes) {
9367
- const exitAnimations = this.animateExiting(mutationResult, context);
9368
- animations.push(...exitAnimations);
9369
- }
9370
9420
  }
9371
9421
  // Create and return group animation
9372
9422
  const groupAnimation = new GroupAnimation(animations);
9373
9423
  // Phase 5: Setup cleanup on complete
9424
+ // Only cleanup exiting elements - persisting elements keep their nodes
9425
+ // This matches React's behavior where nodes persist for elements in the DOM
9426
+ const exitingElements = new Set(mutationResult.exiting.map(({ element }) => element));
9374
9427
  groupAnimation.finished.then(() => {
9375
- // Only clean up non-shared exiting elements (those we reattached)
9376
- this.cleanupExitingElements(nonSharedExiting);
9428
+ // Clean up all reattached exiting elements (remove from DOM)
9429
+ this.cleanupExitingElements(exitingToReattach);
9377
9430
  if (context) {
9378
- cleanupProjectionTree(context);
9431
+ // Only cleanup projection nodes for exiting elements
9432
+ cleanupProjectionTree(context, exitingElements);
9379
9433
  }
9380
9434
  });
9381
9435
  this.notifyReady(groupAnimation);
9382
9436
  }
9383
9437
  catch (error) {
9384
- // Cleanup on error
9438
+ // Cleanup on error - cleanup all nodes since animation failed
9385
9439
  if (context) {
9386
9440
  cleanupProjectionTree(context);
9387
9441
  }
@@ -9390,8 +9444,13 @@ class LayoutAnimationBuilder {
9390
9444
  }
9391
9445
  getBuildOptions() {
9392
9446
  return {
9393
- defaultTransition: this.defaultOptions || { duration: 0.3, ease: "easeOut" },
9394
- sharedTransitions: this.sharedTransitions.size > 0 ? this.sharedTransitions : undefined,
9447
+ defaultTransition: this.defaultOptions || {
9448
+ duration: 0.3,
9449
+ ease: "easeOut",
9450
+ },
9451
+ sharedTransitions: this.sharedTransitions.size > 0
9452
+ ? this.sharedTransitions
9453
+ : undefined,
9395
9454
  };
9396
9455
  }
9397
9456
  reattachExitingElements(exiting, context) {
@@ -9431,50 +9490,6 @@ class LayoutAnimationBuilder {
9431
9490
  }
9432
9491
  }
9433
9492
  }
9434
- animateEntering(mutationResult, context) {
9435
- const enteringSet = new Set(mutationResult.entering);
9436
- // Find root entering elements
9437
- const rootEntering = mutationResult.entering.filter((el) => isRootEnteringElement(el, enteringSet));
9438
- const animations = [];
9439
- for (const element of rootEntering) {
9440
- const visualElement = context.visualElements.get(element);
9441
- if (!visualElement)
9442
- continue;
9443
- // If entering with opacity: 1, start from opacity: 0
9444
- const keyframes = { ...this.enterKeyframes };
9445
- if (keyframes.opacity !== undefined) {
9446
- const targetOpacity = Array.isArray(keyframes.opacity)
9447
- ? keyframes.opacity[keyframes.opacity.length - 1]
9448
- : keyframes.opacity;
9449
- if (targetOpacity === 1) {
9450
- element.style.opacity = "0";
9451
- }
9452
- }
9453
- const options = this.enterOptions || this.defaultOptions || {};
9454
- const enterAnims = animateTarget(visualElement, keyframes, {
9455
- transitionOverride: options,
9456
- });
9457
- animations.push(...enterAnims);
9458
- }
9459
- return animations;
9460
- }
9461
- animateExiting(mutationResult, context) {
9462
- const exitingSet = new Set(mutationResult.exiting.map((r) => r.element));
9463
- // Find root exiting elements
9464
- const rootExiting = mutationResult.exiting.filter((r) => isRootExitingElement(r.element, exitingSet));
9465
- const animations = [];
9466
- for (const { element } of rootExiting) {
9467
- const visualElement = context.visualElements.get(element);
9468
- if (!visualElement)
9469
- continue;
9470
- const options = this.exitOptions || this.defaultOptions || {};
9471
- const exitAnims = animateTarget(visualElement, this.exitKeyframes, {
9472
- transitionOverride: options,
9473
- });
9474
- animations.push(...exitAnims);
9475
- }
9476
- return animations;
9477
- }
9478
9493
  }
9479
9494
  /**
9480
9495
  * Parse arguments for animateLayout overloads
@@ -9516,12 +9531,10 @@ function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9516
9531
  * // With options
9517
9532
  * await animateLayout(() => update(), { duration: 0.5 })
9518
9533
  *
9519
- * // Builder pattern for enter/exit animations
9534
+ * // Configure shared element transitions
9520
9535
  * animateLayout(".cards", () => {
9521
9536
  * container.innerHTML = newCards
9522
9537
  * }, { duration: 0.3 })
9523
- * .enter({ opacity: 1, scale: 1 }, { duration: 0.2 })
9524
- * .exit({ opacity: 0, scale: 0.8 })
9525
9538
  * .shared("hero", { type: "spring" })
9526
9539
  * ```
9527
9540
  *