motion-dom 12.29.1-alpha.0 → 12.30.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
@@ -1618,30 +1618,6 @@ class JSAnimation extends WithPromise {
1618
1618
  this.startTime = 0;
1619
1619
  return this.tick(sampleTime, true);
1620
1620
  }
1621
- /**
1622
- * Returns whether this animation can provide accurate velocity sampling.
1623
- * This is false for animations using mixKeyframes (non-numeric values)
1624
- * or animations that aren't currently running.
1625
- */
1626
- get canSampleVelocity() {
1627
- return (this.state === "running" &&
1628
- !this.isStopped &&
1629
- !this.mixKeyframes &&
1630
- !!this.generator);
1631
- }
1632
- /**
1633
- * Sample the animation's value at a specific time in milliseconds.
1634
- * Used for velocity calculations via finite differencing.
1635
- */
1636
- sampleAt(t) {
1637
- return this.generator.next(t).value;
1638
- }
1639
- /**
1640
- * The current elapsed time of the animation in milliseconds.
1641
- */
1642
- get elapsed() {
1643
- return this.currentTime;
1644
- }
1645
1621
  attachTimeline(timeline) {
1646
1622
  if (this.options.allowFlatten) {
1647
1623
  this.options.type = "keyframes";
@@ -2158,7 +2134,8 @@ class NativeAnimation extends WithPromise {
2158
2134
  * while deferring the commit until the next animation frame.
2159
2135
  */
2160
2136
  commitStyles() {
2161
- if (!this.isPseudoElement) {
2137
+ const element = this.options?.element;
2138
+ if (!this.isPseudoElement && element?.isConnected) {
2162
2139
  this.animation.commitStyles?.();
2163
2140
  }
2164
2141
  }
@@ -2859,7 +2836,8 @@ const animateMotionValue = (name, value, target, transition = {}, element, isHan
2859
2836
  }
2860
2837
  }
2861
2838
  if (motionUtils.MotionGlobalConfig.instantAnimations ||
2862
- motionUtils.MotionGlobalConfig.skipAnimations) {
2839
+ motionUtils.MotionGlobalConfig.skipAnimations ||
2840
+ element?.shouldSkipAnimations) {
2863
2841
  shouldSkip = true;
2864
2842
  makeAnimationInstant(options);
2865
2843
  options.delay = 0;
@@ -4760,25 +4738,16 @@ function attachFollow(value, source, options = {}) {
4760
4738
  }
4761
4739
  };
4762
4740
  const startAnimation = () => {
4741
+ stopAnimation();
4763
4742
  const currentValue = asNumber$1(value.get());
4764
4743
  const targetValue = asNumber$1(latestValue);
4765
4744
  // Don't animate if we're already at the target
4766
4745
  if (currentValue === targetValue) {
4767
- stopAnimation();
4768
4746
  return;
4769
4747
  }
4770
- // Get velocity from the running animation before stopping it.
4771
- // This provides the instantaneous velocity from the spring physics,
4772
- // which is more accurate than the motion value's finite difference.
4773
- let velocity = value.getVelocity();
4774
- if (activeAnimation?.canSampleVelocity) {
4775
- const elapsed = activeAnimation.elapsed;
4776
- velocity = calcGeneratorVelocity((t) => activeAnimation.sampleAt(t), elapsed, activeAnimation.sampleAt(elapsed));
4777
- }
4778
- stopAnimation();
4779
4748
  activeAnimation = new JSAnimation({
4780
4749
  keyframes: [currentValue, targetValue],
4781
- velocity,
4750
+ velocity: value.getVelocity(),
4782
4751
  // Default to spring if no type specified (matches useSpring behavior)
4783
4752
  type: "spring",
4784
4753
  restDelta: 0.001,
@@ -5412,7 +5381,7 @@ class VisualElement {
5412
5381
  scrapeMotionValuesFromProps(_props, _prevProps, _visualElement) {
5413
5382
  return {};
5414
5383
  }
5415
- constructor({ parent, props, presenceContext, reducedMotionConfig, blockInitialAnimation, visualState, }, options = {}) {
5384
+ constructor({ parent, props, presenceContext, reducedMotionConfig, skipAnimations, blockInitialAnimation, visualState, }, options = {}) {
5416
5385
  /**
5417
5386
  * A reference to the current underlying Instance, e.g. a HTMLElement
5418
5387
  * or Three.Mesh etc.
@@ -5435,6 +5404,11 @@ class VisualElement {
5435
5404
  * like it could be set globally.
5436
5405
  */
5437
5406
  this.shouldReduceMotion = null;
5407
+ /**
5408
+ * Decides whether animations should be skipped for this VisualElement.
5409
+ * Useful for E2E tests and visual regression testing.
5410
+ */
5411
+ this.shouldSkipAnimations = false;
5438
5412
  /**
5439
5413
  * A map of all motion values attached to this visual element. Motion
5440
5414
  * values are source of truth for any given animated value. A motion
@@ -5492,6 +5466,7 @@ class VisualElement {
5492
5466
  this.presenceContext = presenceContext;
5493
5467
  this.depth = parent ? parent.depth + 1 : 0;
5494
5468
  this.reducedMotionConfig = reducedMotionConfig;
5469
+ this.skipAnimationsConfig = skipAnimations;
5495
5470
  this.options = options;
5496
5471
  this.blockInitialAnimation = Boolean(blockInitialAnimation);
5497
5472
  this.isControllingVariants = isControllingVariants(props);
@@ -5548,6 +5523,10 @@ class VisualElement {
5548
5523
  if (process.env.NODE_ENV !== "production") {
5549
5524
  motionUtils.warnOnce(this.shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled");
5550
5525
  }
5526
+ /**
5527
+ * Set whether animations should be skipped based on the config.
5528
+ */
5529
+ this.shouldSkipAnimations = this.skipAnimationsConfig ?? false;
5551
5530
  this.parent?.addChild(this);
5552
5531
  this.update(this.props, this.presenceContext);
5553
5532
  }
@@ -7490,7 +7469,7 @@ function cancelTreeOptimisedTransformAnimations(projectionNode) {
7490
7469
  cancelTreeOptimisedTransformAnimations(parent);
7491
7470
  }
7492
7471
  }
7493
- function createProjectionNode$1({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) {
7472
+ function createProjectionNode({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) {
7494
7473
  return class ProjectionNode {
7495
7474
  constructor(latestValues = {}, parent = defaultParent?.()) {
7496
7475
  /**
@@ -9047,7 +9026,7 @@ function checkNodeWasScrollRoot(node) {
9047
9026
  return node !== node.root && node.scroll?.wasRoot;
9048
9027
  }
9049
9028
 
9050
- const DocumentProjectionNode = createProjectionNode$1({
9029
+ const DocumentProjectionNode = createProjectionNode({
9051
9030
  attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify),
9052
9031
  measureScroll: () => ({
9053
9032
  x: document.documentElement.scrollLeft || document.body?.scrollLeft || 0,
@@ -9082,7 +9061,7 @@ function nodeGroup() {
9082
9061
  const rootProjectionNode = {
9083
9062
  current: undefined,
9084
9063
  };
9085
- const HTMLProjectionNode = createProjectionNode$1({
9064
+ const HTMLProjectionNode = createProjectionNode({
9086
9065
  measureScroll: (instance) => ({
9087
9066
  x: instance.scrollLeft,
9088
9067
  y: instance.scrollTop,
@@ -9102,315 +9081,153 @@ const HTMLProjectionNode = createProjectionNode$1({
9102
9081
  checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"),
9103
9082
  });
9104
9083
 
9105
- const LAYOUT_SELECTOR = "[data-layout], [data-layout-id]";
9106
- function getLayoutElements(scope) {
9107
- const elements = Array.from(scope.querySelectorAll(LAYOUT_SELECTOR));
9108
- // Include scope itself if it's an Element (not Document) and has layout attributes
9109
- if (scope instanceof Element && hasLayout(scope)) {
9110
- elements.unshift(scope);
9111
- }
9112
- return elements;
9113
- }
9114
- function getLayoutId(element) {
9115
- return element.getAttribute("data-layout-id");
9116
- }
9117
- function hasLayout(element) {
9118
- return (element.hasAttribute("data-layout") ||
9119
- element.hasAttribute("data-layout-id"));
9120
- }
9121
-
9122
- let scaleCorrectorAdded = false;
9123
- /**
9124
- * Track active projection nodes per element to handle animation interruption.
9125
- * When a new animation starts on an element that already has an active animation,
9126
- * we need to stop the old animation so the new one can start from the current
9127
- * visual position.
9128
- */
9129
- const activeProjectionNodes = new WeakMap();
9130
- function ensureScaleCorrectors() {
9131
- if (scaleCorrectorAdded)
9132
- return;
9133
- scaleCorrectorAdded = true;
9134
- addScaleCorrector({
9135
- borderRadius: {
9136
- ...correctBorderRadius,
9137
- applyTo: [
9138
- "borderTopLeftRadius",
9139
- "borderTopRightRadius",
9140
- "borderBottomLeftRadius",
9141
- "borderBottomRightRadius",
9142
- ],
9143
- },
9144
- borderTopLeftRadius: correctBorderRadius,
9145
- borderTopRightRadius: correctBorderRadius,
9146
- borderBottomLeftRadius: correctBorderRadius,
9147
- borderBottomRightRadius: correctBorderRadius,
9148
- boxShadow: correctBoxShadow,
9149
- });
9150
- }
9151
- /**
9152
- * Get DOM depth of an element
9153
- */
9154
- function getDepth(element) {
9155
- let depth = 0;
9156
- let current = element.parentElement;
9157
- while (current) {
9158
- depth++;
9159
- current = current.parentElement;
9160
- }
9161
- return depth;
9162
- }
9163
- /**
9164
- * Find the closest projection parent for an element
9165
- */
9166
- function findProjectionParent(element, nodeCache) {
9167
- let parent = element.parentElement;
9168
- while (parent) {
9169
- const node = nodeCache.get(parent);
9170
- if (node)
9171
- return node;
9172
- parent = parent.parentElement;
9173
- }
9174
- return undefined;
9175
- }
9176
- /**
9177
- * Create or reuse a projection node for an element
9178
- */
9179
- function createProjectionNode(element, parent, options, transition) {
9180
- // Check for existing active node - reuse it to preserve animation state
9181
- const existingNode = activeProjectionNodes.get(element);
9182
- if (existingNode) {
9183
- const visualElement = existingNode.options.visualElement;
9184
- // Update transition options for the new animation
9185
- const nodeTransition = transition
9186
- ? { duration: transition.duration, ease: transition.ease }
9187
- : { duration: 0.3, ease: "easeOut" };
9188
- existingNode.setOptions({
9189
- ...existingNode.options,
9190
- animate: true,
9191
- transition: nodeTransition,
9192
- ...options,
9193
- });
9194
- // Re-mount the node if it was previously unmounted
9195
- // This re-adds it to root.nodes so didUpdate() will process it
9196
- if (!existingNode.instance) {
9197
- existingNode.mount(element);
9198
- }
9199
- return { node: existingNode, visualElement };
9200
- }
9201
- // No existing node - create a new one
9202
- const latestValues = {};
9203
- const visualElement = new HTMLVisualElement({
9204
- visualState: {
9205
- latestValues,
9206
- renderState: {
9207
- transformOrigin: {},
9208
- transform: {},
9209
- style: {},
9210
- vars: {},
9211
- },
9212
- },
9213
- presenceContext: null,
9214
- props: {},
9215
- });
9216
- const node = new HTMLProjectionNode(latestValues, parent);
9217
- // Convert AnimationOptions to transition format for the projection system
9218
- const nodeTransition = transition
9219
- ? { duration: transition.duration, ease: transition.ease }
9220
- : { duration: 0.3, ease: "easeOut" };
9221
- node.setOptions({
9222
- visualElement,
9223
- layout: true,
9224
- animate: true,
9225
- transition: nodeTransition,
9226
- ...options,
9227
- });
9228
- node.mount(element);
9229
- visualElement.projection = node;
9230
- // Track this node as the active one for this element
9231
- activeProjectionNodes.set(element, node);
9232
- return { node, visualElement };
9233
- }
9234
- /**
9235
- * Build a projection tree from a list of elements
9236
- */
9237
- function buildProjectionTree(elements, existingContext, options) {
9238
- ensureScaleCorrectors();
9239
- const nodes = existingContext?.nodes ?? new Map();
9240
- const visualElements = existingContext?.visualElements ?? new Map();
9241
- const group = existingContext?.group ?? nodeGroup();
9242
- const defaultTransition = options?.defaultTransition;
9243
- const sharedTransitions = options?.sharedTransitions;
9244
- // Sort elements by DOM depth (parents before children)
9245
- const sorted = [...elements].sort((a, b) => getDepth(a) - getDepth(b));
9246
- let root = existingContext?.root;
9247
- for (const element of sorted) {
9248
- // Skip if already has a node
9249
- if (nodes.has(element))
9250
- continue;
9251
- const parent = findProjectionParent(element, nodes);
9252
- const layoutId = getLayoutId(element);
9253
- const layoutMode = element.getAttribute("data-layout");
9254
- const nodeOptions = {
9255
- layoutId: layoutId ?? undefined,
9256
- animationType: parseLayoutMode(layoutMode),
9257
- };
9258
- // Use layoutId-specific transition if available, otherwise use default
9259
- const transition = layoutId && sharedTransitions?.get(layoutId)
9260
- ? sharedTransitions.get(layoutId)
9261
- : defaultTransition;
9262
- const { node, visualElement } = createProjectionNode(element, parent, nodeOptions, transition);
9263
- nodes.set(element, node);
9264
- visualElements.set(element, visualElement);
9265
- group.add(node);
9266
- if (!root) {
9267
- root = node.root;
9268
- }
9269
- }
9084
+ const layoutSelector = "[data-layout], [data-layout-id]";
9085
+ const noop = () => { };
9086
+ function snapshotFromTarget(projection) {
9087
+ const target = projection.targetWithTransforms || projection.target;
9088
+ if (!target)
9089
+ return undefined;
9090
+ const measuredBox = createBox();
9091
+ const layoutBox = createBox();
9092
+ copyBoxInto(measuredBox, target);
9093
+ copyBoxInto(layoutBox, target);
9270
9094
  return {
9271
- nodes,
9272
- visualElements,
9273
- group,
9274
- root: root,
9095
+ animationId: projection.root?.animationId ?? 0,
9096
+ measuredBox,
9097
+ layoutBox,
9098
+ latestValues: projection.animationValues || projection.latestValues || {},
9099
+ source: projection.id,
9275
9100
  };
9276
9101
  }
9277
- /**
9278
- * Parse the data-layout attribute value
9279
- */
9280
- function parseLayoutMode(value) {
9281
- if (value === "position")
9282
- return "position";
9283
- if (value === "size")
9284
- return "size";
9285
- if (value === "preserve-aspect")
9286
- return "preserve-aspect";
9287
- return "both";
9288
- }
9289
- /**
9290
- * Clean up projection nodes for specific elements.
9291
- * If elementsToCleanup is provided, only those elements are cleaned up.
9292
- * If not provided, all nodes are cleaned up.
9293
- *
9294
- * This allows persisting elements to keep their nodes between animations,
9295
- * matching React's behavior where nodes persist for elements that remain in the DOM.
9296
- */
9297
- function cleanupProjectionTree(context, elementsToCleanup) {
9298
- const elementsToProcess = elementsToCleanup
9299
- ? [...context.nodes.entries()].filter(([el]) => elementsToCleanup.has(el))
9300
- : [...context.nodes.entries()];
9301
- for (const [element, node] of elementsToProcess) {
9302
- context.group.remove(node);
9303
- node.unmount();
9304
- // Only clear from activeProjectionNodes if this is still the active node.
9305
- // A newer animation might have already taken over.
9306
- if (activeProjectionNodes.get(element) === node) {
9307
- activeProjectionNodes.delete(element);
9308
- }
9309
- context.nodes.delete(element);
9310
- context.visualElements.delete(element);
9311
- }
9312
- }
9313
-
9314
9102
  class LayoutAnimationBuilder {
9315
9103
  constructor(scope, updateDom, defaultOptions) {
9316
9104
  this.sharedTransitions = new Map();
9317
- this.notifyReady = motionUtils.noop;
9318
- this.executed = false;
9105
+ this.notifyReady = noop;
9106
+ this.rejectReady = noop;
9319
9107
  this.scope = scope;
9320
9108
  this.updateDom = updateDom;
9321
9109
  this.defaultOptions = defaultOptions;
9322
- this.readyPromise = new Promise((resolve) => {
9110
+ this.readyPromise = new Promise((resolve, reject) => {
9323
9111
  this.notifyReady = resolve;
9112
+ this.rejectReady = reject;
9113
+ });
9114
+ frame.postRender(() => {
9115
+ this.start().then(this.notifyReady).catch(this.rejectReady);
9324
9116
  });
9325
- // Queue execution on microtask to allow builder methods to be called
9326
- queueMicrotask(() => this.execute());
9327
9117
  }
9328
- shared(id, options) {
9329
- this.sharedTransitions.set(id, options);
9118
+ shared(id, transition) {
9119
+ this.sharedTransitions.set(id, transition);
9330
9120
  return this;
9331
9121
  }
9332
- then(onfulfilled, onrejected) {
9333
- return this.readyPromise.then(onfulfilled, onrejected);
9122
+ then(resolve, reject) {
9123
+ return this.readyPromise.then(resolve, reject);
9334
9124
  }
9335
- async execute() {
9336
- if (this.executed)
9337
- return;
9338
- this.executed = true;
9339
- let context;
9340
- // Phase 1: Pre-mutation - Build projection tree and take snapshots
9341
- const beforeElements = getLayoutElements(this.scope);
9342
- if (beforeElements.length > 0) {
9343
- context = buildProjectionTree(beforeElements, undefined, this.getBuildOptions());
9344
- context.root.startUpdate();
9345
- for (const node of context.nodes.values()) {
9346
- node.isLayoutDirty = false;
9347
- node.willUpdate();
9348
- }
9349
- }
9350
- // Phase 2: Execute DOM update
9351
- this.updateDom();
9352
- // Phase 3: Post-mutation - Compare before/after elements
9353
- const afterElements = getLayoutElements(this.scope);
9354
- const beforeSet = new Set(beforeElements);
9355
- const afterSet = new Set(afterElements);
9356
- const entering = afterElements.filter((el) => !beforeSet.has(el));
9357
- const exiting = beforeElements.filter((el) => !afterSet.has(el));
9358
- // Build projection nodes for entering elements
9359
- if (entering.length > 0) {
9360
- context = buildProjectionTree(entering, context, this.getBuildOptions());
9361
- }
9362
- // No layout elements - return empty animation
9363
- if (!context) {
9364
- this.notifyReady(new GroupAnimation([]));
9365
- return;
9366
- }
9367
- // Handle shared elements
9368
- for (const element of exiting) {
9369
- const node = context.nodes.get(element);
9370
- node?.getStack()?.remove(node);
9371
- }
9372
- for (const element of entering) {
9373
- context.nodes.get(element)?.promote();
9374
- }
9375
- // Phase 4: Animate
9376
- context.root.didUpdate();
9377
- await new Promise((resolve) => frame.postRender(() => resolve()));
9378
- const animations = [];
9379
- for (const node of context.nodes.values()) {
9380
- if (node.currentAnimation) {
9381
- animations.push(node.currentAnimation);
9382
- }
9383
- }
9384
- const groupAnimation = new GroupAnimation(animations);
9385
- groupAnimation.finished.then(() => {
9386
- // Only clean up nodes for elements no longer in the document.
9387
- // Elements still in DOM keep their nodes so subsequent animations
9388
- // can use the stored position snapshots (A→B→A pattern).
9389
- const elementsToCleanup = new Set();
9390
- for (const element of context.nodes.keys()) {
9391
- if (!document.contains(element)) {
9392
- elementsToCleanup.add(element);
9125
+ async start() {
9126
+ const beforeElements = collectLayoutElements(this.scope);
9127
+ const beforeRecords = this.buildRecords(beforeElements);
9128
+ beforeRecords.forEach(({ projection }) => {
9129
+ const hasCurrentAnimation = Boolean(projection.currentAnimation);
9130
+ const isSharedLayout = Boolean(projection.options.layoutId);
9131
+ if (hasCurrentAnimation && isSharedLayout) {
9132
+ const snapshot = snapshotFromTarget(projection);
9133
+ if (snapshot) {
9134
+ projection.snapshot = snapshot;
9393
9135
  }
9136
+ else if (projection.snapshot) {
9137
+ projection.snapshot = undefined;
9138
+ }
9139
+ }
9140
+ else if (projection.snapshot &&
9141
+ (projection.currentAnimation || projection.isProjecting())) {
9142
+ projection.snapshot = undefined;
9143
+ }
9144
+ projection.isPresent = true;
9145
+ projection.willUpdate();
9146
+ });
9147
+ await this.updateDom();
9148
+ const afterElements = collectLayoutElements(this.scope);
9149
+ const afterRecords = this.buildRecords(afterElements);
9150
+ this.handleExitingElements(beforeRecords, afterRecords);
9151
+ afterRecords.forEach(({ projection }) => {
9152
+ const instance = projection.instance;
9153
+ const resumeFromInstance = projection.resumeFrom
9154
+ ?.instance;
9155
+ if (!instance || !resumeFromInstance)
9156
+ return;
9157
+ if (!("style" in instance))
9158
+ return;
9159
+ const currentTransform = instance.style.transform;
9160
+ const resumeFromTransform = resumeFromInstance.style.transform;
9161
+ if (currentTransform &&
9162
+ resumeFromTransform &&
9163
+ currentTransform === resumeFromTransform) {
9164
+ instance.style.transform = "";
9165
+ instance.style.transformOrigin = "";
9394
9166
  }
9395
- cleanupProjectionTree(context, elementsToCleanup);
9396
9167
  });
9397
- this.notifyReady(groupAnimation);
9168
+ afterRecords.forEach(({ projection }) => {
9169
+ projection.isPresent = true;
9170
+ });
9171
+ const root = getProjectionRoot(afterRecords, beforeRecords);
9172
+ root?.didUpdate();
9173
+ await new Promise((resolve) => {
9174
+ frame.postRender(() => resolve());
9175
+ });
9176
+ const animations = collectAnimations(afterRecords);
9177
+ const animation = new GroupAnimation(animations);
9178
+ return animation;
9398
9179
  }
9399
- getBuildOptions() {
9400
- return {
9401
- defaultTransition: this.defaultOptions || {
9402
- duration: 0.3,
9403
- ease: "easeOut",
9404
- },
9405
- sharedTransitions: this.sharedTransitions.size > 0
9406
- ? this.sharedTransitions
9407
- : undefined,
9408
- };
9180
+ buildRecords(elements) {
9181
+ const records = [];
9182
+ const recordMap = new Map();
9183
+ for (const element of elements) {
9184
+ const parentRecord = findParentRecord(element, recordMap, this.scope);
9185
+ const { layout, layoutId } = readLayoutAttributes(element);
9186
+ const override = layoutId
9187
+ ? this.sharedTransitions.get(layoutId)
9188
+ : undefined;
9189
+ const transition = override || this.defaultOptions;
9190
+ const record = getOrCreateRecord(element, parentRecord?.projection, {
9191
+ layout,
9192
+ layoutId,
9193
+ animationType: typeof layout === "string" ? layout : "both",
9194
+ transition: transition,
9195
+ });
9196
+ recordMap.set(element, record);
9197
+ records.push(record);
9198
+ }
9199
+ return records;
9200
+ }
9201
+ handleExitingElements(beforeRecords, afterRecords) {
9202
+ const afterElementsSet = new Set(afterRecords.map((record) => record.element));
9203
+ beforeRecords.forEach((record) => {
9204
+ if (afterElementsSet.has(record.element))
9205
+ return;
9206
+ // For shared layout elements, relegate to set up resumeFrom
9207
+ // so the remaining element animates from this position
9208
+ if (record.projection.options.layoutId) {
9209
+ record.projection.isPresent = false;
9210
+ record.projection.relegate();
9211
+ }
9212
+ record.visualElement.unmount();
9213
+ visualElementStore.delete(record.element);
9214
+ });
9215
+ // Clear resumeFrom on EXISTING nodes that point to unmounted projections
9216
+ // This prevents crossfade animation when the source element was removed entirely
9217
+ // But preserve resumeFrom for NEW nodes so they can animate from the old position
9218
+ // Also preserve resumeFrom for lead nodes that were just promoted via relegate
9219
+ const beforeElementsSet = new Set(beforeRecords.map((record) => record.element));
9220
+ afterRecords.forEach(({ element, projection }) => {
9221
+ if (beforeElementsSet.has(element) &&
9222
+ projection.resumeFrom &&
9223
+ !projection.resumeFrom.instance &&
9224
+ !projection.isLead()) {
9225
+ projection.resumeFrom = undefined;
9226
+ projection.snapshot = undefined;
9227
+ }
9228
+ });
9409
9229
  }
9410
9230
  }
9411
- /**
9412
- * Parse arguments for animateLayout overloads
9413
- */
9414
9231
  function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9415
9232
  // animateLayout(updateDom)
9416
9233
  if (typeof scopeOrUpdateDom === "function") {
@@ -9424,11 +9241,103 @@ function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9424
9241
  const elements = resolveElements(scopeOrUpdateDom);
9425
9242
  const scope = elements[0] || document;
9426
9243
  return {
9427
- scope: scope instanceof Document ? scope : scope,
9244
+ scope,
9428
9245
  updateDom: updateDomOrOptions,
9429
9246
  defaultOptions: options,
9430
9247
  };
9431
9248
  }
9249
+ function collectLayoutElements(scope) {
9250
+ const elements = Array.from(scope.querySelectorAll(layoutSelector));
9251
+ if (scope instanceof Element && scope.matches(layoutSelector)) {
9252
+ if (!elements.includes(scope)) {
9253
+ elements.unshift(scope);
9254
+ }
9255
+ }
9256
+ return elements;
9257
+ }
9258
+ function readLayoutAttributes(element) {
9259
+ const layoutId = element.getAttribute("data-layout-id") || undefined;
9260
+ const rawLayout = element.getAttribute("data-layout");
9261
+ let layout;
9262
+ if (rawLayout === "" || rawLayout === "true") {
9263
+ layout = true;
9264
+ }
9265
+ else if (rawLayout) {
9266
+ layout = rawLayout;
9267
+ }
9268
+ return {
9269
+ layout,
9270
+ layoutId,
9271
+ };
9272
+ }
9273
+ function createVisualState() {
9274
+ return {
9275
+ latestValues: {},
9276
+ renderState: {
9277
+ transform: {},
9278
+ transformOrigin: {},
9279
+ style: {},
9280
+ vars: {},
9281
+ },
9282
+ };
9283
+ }
9284
+ function getOrCreateRecord(element, parentProjection, projectionOptions) {
9285
+ const existing = visualElementStore.get(element);
9286
+ const visualElement = existing ??
9287
+ new HTMLVisualElement({
9288
+ props: {},
9289
+ presenceContext: null,
9290
+ visualState: createVisualState(),
9291
+ }, { allowProjection: true });
9292
+ if (!existing || !visualElement.projection) {
9293
+ visualElement.projection = new HTMLProjectionNode(visualElement.latestValues, parentProjection);
9294
+ }
9295
+ visualElement.projection.setOptions({
9296
+ ...projectionOptions,
9297
+ visualElement,
9298
+ });
9299
+ if (!visualElement.current) {
9300
+ visualElement.mount(element);
9301
+ }
9302
+ else if (!visualElement.projection.instance) {
9303
+ // Mount projection if VisualElement is already mounted but projection isn't
9304
+ // This happens when animate() was called before animateLayout()
9305
+ visualElement.projection.mount(element);
9306
+ }
9307
+ if (!existing) {
9308
+ visualElementStore.set(element, visualElement);
9309
+ }
9310
+ return {
9311
+ element,
9312
+ visualElement,
9313
+ projection: visualElement.projection,
9314
+ };
9315
+ }
9316
+ function findParentRecord(element, recordMap, scope) {
9317
+ let parent = element.parentElement;
9318
+ while (parent) {
9319
+ const record = recordMap.get(parent);
9320
+ if (record)
9321
+ return record;
9322
+ if (parent === scope)
9323
+ break;
9324
+ parent = parent.parentElement;
9325
+ }
9326
+ return undefined;
9327
+ }
9328
+ function getProjectionRoot(afterRecords, beforeRecords) {
9329
+ const record = afterRecords[0] || beforeRecords[0];
9330
+ return record?.projection.root;
9331
+ }
9332
+ function collectAnimations(afterRecords) {
9333
+ const animations = new Set();
9334
+ afterRecords.forEach((record) => {
9335
+ const animation = record.projection.currentAnimation;
9336
+ if (animation)
9337
+ animations.add(animation);
9338
+ });
9339
+ return Array.from(animations);
9340
+ }
9432
9341
 
9433
9342
  /**
9434
9343
  * @deprecated
@@ -9540,7 +9449,7 @@ exports.createAxisDelta = createAxisDelta;
9540
9449
  exports.createBox = createBox;
9541
9450
  exports.createDelta = createDelta;
9542
9451
  exports.createGeneratorEasing = createGeneratorEasing;
9543
- exports.createProjectionNode = createProjectionNode$1;
9452
+ exports.createProjectionNode = createProjectionNode;
9544
9453
  exports.createRenderBatcher = createRenderBatcher;
9545
9454
  exports.cubicBezierAsString = cubicBezierAsString;
9546
9455
  exports.defaultEasing = defaultEasing;