motion-dom 12.28.1-alpha.0 → 12.28.2

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.
Files changed (38) hide show
  1. package/dist/cjs/index.js +429 -331
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/es/animation/waapi/utils/px-values.mjs +2 -1
  4. package/dist/es/animation/waapi/utils/px-values.mjs.map +1 -1
  5. package/dist/es/effects/style/transform.mjs +2 -1
  6. package/dist/es/effects/style/transform.mjs.map +1 -1
  7. package/dist/es/effects/svg/index.mjs +7 -4
  8. package/dist/es/effects/svg/index.mjs.map +1 -1
  9. package/dist/es/index.mjs +1 -0
  10. package/dist/es/index.mjs.map +1 -1
  11. package/dist/es/layout/LayoutAnimationBuilder.mjs +83 -253
  12. package/dist/es/layout/LayoutAnimationBuilder.mjs.map +1 -1
  13. package/dist/es/layout/get-layout-elements.mjs +19 -0
  14. package/dist/es/layout/get-layout-elements.mjs.map +1 -0
  15. package/dist/es/layout/projection-tree.mjs +202 -0
  16. package/dist/es/layout/projection-tree.mjs.map +1 -0
  17. package/dist/es/projection/node/DocumentProjectionNode.mjs +2 -2
  18. package/dist/es/projection/node/DocumentProjectionNode.mjs.map +1 -1
  19. package/dist/es/projection/node/create-projection-node.mjs +16 -16
  20. package/dist/es/projection/node/create-projection-node.mjs.map +1 -1
  21. package/dist/es/projection/shared/stack.mjs +0 -7
  22. package/dist/es/projection/shared/stack.mjs.map +1 -1
  23. package/dist/es/render/html/utils/build-transform.mjs +2 -1
  24. package/dist/es/render/html/utils/build-transform.mjs.map +1 -1
  25. package/dist/es/render/svg/utils/path.mjs +7 -8
  26. package/dist/es/render/svg/utils/path.mjs.map +1 -1
  27. package/dist/es/value/follow-value.mjs +102 -0
  28. package/dist/es/value/follow-value.mjs.map +1 -0
  29. package/dist/es/value/spring-value.mjs +16 -61
  30. package/dist/es/value/spring-value.mjs.map +1 -1
  31. package/dist/es/value/types/maps/number.mjs +2 -1
  32. package/dist/es/value/types/maps/number.mjs.map +1 -1
  33. package/dist/index.d.ts +63 -14
  34. package/dist/motion-dom.dev.js +429 -331
  35. package/dist/motion-dom.js +1 -1
  36. package/dist/size-rollup-style-effect.js +1 -1
  37. package/dist/size-rollup-style-effect.js.map +1 -1
  38. package/package.json +3 -3
package/dist/cjs/index.js CHANGED
@@ -3547,7 +3547,6 @@ const numberValueTypes = {
3547
3547
  borderBottomWidth: px,
3548
3548
  borderLeftWidth: px,
3549
3549
  borderRadius: px,
3550
- radius: px,
3551
3550
  borderTopLeftRadius: px,
3552
3551
  borderTopRightRadius: px,
3553
3552
  borderBottomRightRadius: px,
@@ -3591,6 +3590,8 @@ const numberValueTypes = {
3591
3590
  marginInline: px,
3592
3591
  marginInlineStart: px,
3593
3592
  marginInlineEnd: px,
3593
+ // Typography
3594
+ fontSize: px,
3594
3595
  // Misc
3595
3596
  backgroundPositionX: px,
3596
3597
  backgroundPositionY: px,
@@ -3802,7 +3803,6 @@ const pxValues = new Set([
3802
3803
  "borderBottomWidth",
3803
3804
  "borderLeftWidth",
3804
3805
  "borderRadius",
3805
- "radius",
3806
3806
  "borderTopLeftRadius",
3807
3807
  "borderTopRightRadius",
3808
3808
  "borderBottomRightRadius",
@@ -3846,6 +3846,8 @@ const pxValues = new Set([
3846
3846
  "marginInline",
3847
3847
  "marginInlineStart",
3848
3848
  "marginInlineEnd",
3849
+ // Typography
3850
+ "fontSize",
3849
3851
  // Misc
3850
3852
  "backgroundPositionX",
3851
3853
  "backgroundPositionY",
@@ -4067,7 +4069,8 @@ function buildTransform$1(state) {
4067
4069
  valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
4068
4070
  }
4069
4071
  else {
4070
- valueIsDefault = parseFloat(value) === 0;
4072
+ const parsed = parseFloat(value);
4073
+ valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0;
4071
4074
  }
4072
4075
  if (!valueIsDefault) {
4073
4076
  transformIsDefault = false;
@@ -4122,17 +4125,21 @@ const addStyleValue = (element, state, key, value) => {
4122
4125
  const styleEffect = /*@__PURE__*/ createSelectorEffect(
4123
4126
  /*@__PURE__*/ createEffect(addStyleValue));
4124
4127
 
4125
- const toPx = px.transform;
4126
4128
  function addSVGPathValue(element, state, key, value) {
4127
4129
  frame.render(() => element.setAttribute("pathLength", "1"));
4128
4130
  if (key === "pathOffset") {
4129
- return state.set(key, value, () => element.setAttribute("stroke-dashoffset", toPx(-state.latest[key])));
4131
+ return state.set(key, value, () => {
4132
+ // Use unitless value to avoid Safari zoom bug
4133
+ const offset = state.latest[key];
4134
+ element.setAttribute("stroke-dashoffset", `${-offset}`);
4135
+ });
4130
4136
  }
4131
4137
  else {
4132
4138
  if (!state.get("stroke-dasharray")) {
4133
4139
  state.set("stroke-dasharray", new MotionValue("1 1"), () => {
4134
4140
  const { pathLength = 1, pathSpacing } = state.latest;
4135
- element.setAttribute("stroke-dasharray", `${toPx(pathLength)} ${toPx(pathSpacing ?? 1 - Number(pathLength))}`);
4141
+ // Use unitless values to avoid Safari zoom bug
4142
+ element.setAttribute("stroke-dasharray", `${pathLength} ${pathSpacing ?? 1 - Number(pathLength)}`);
4136
4143
  });
4137
4144
  }
4138
4145
  return state.set(key, value, undefined, state.get("stroke-dasharray"));
@@ -4678,6 +4685,101 @@ function transform(...args) {
4678
4685
  return useImmediate ? interpolator(inputValue) : interpolator;
4679
4686
  }
4680
4687
 
4688
+ /**
4689
+ * Create a `MotionValue` that animates to its latest value using any transition type.
4690
+ * Can either be a value or track another `MotionValue`.
4691
+ *
4692
+ * ```jsx
4693
+ * const x = motionValue(0)
4694
+ * const y = followValue(x, { type: "spring", stiffness: 300 })
4695
+ * // or with tween
4696
+ * const z = followValue(x, { type: "tween", duration: 0.5, ease: "easeOut" })
4697
+ * ```
4698
+ *
4699
+ * @param source - Initial value or MotionValue to track
4700
+ * @param options - Animation transition options
4701
+ * @returns `MotionValue`
4702
+ *
4703
+ * @public
4704
+ */
4705
+ function followValue(source, options) {
4706
+ const initialValue = isMotionValue(source) ? source.get() : source;
4707
+ const value = motionValue(initialValue);
4708
+ attachFollow(value, source, options);
4709
+ return value;
4710
+ }
4711
+ /**
4712
+ * Attach an animation to a MotionValue that will animate whenever the value changes.
4713
+ * Similar to attachSpring but supports any transition type (spring, tween, inertia, etc.)
4714
+ *
4715
+ * @param value - The MotionValue to animate
4716
+ * @param source - Initial value or MotionValue to track
4717
+ * @param options - Animation transition options
4718
+ * @returns Cleanup function
4719
+ *
4720
+ * @public
4721
+ */
4722
+ function attachFollow(value, source, options = {}) {
4723
+ const initialValue = value.get();
4724
+ let activeAnimation = null;
4725
+ let latestValue = initialValue;
4726
+ let latestSetter;
4727
+ const unit = typeof initialValue === "string"
4728
+ ? initialValue.replace(/[\d.-]/g, "")
4729
+ : undefined;
4730
+ const stopAnimation = () => {
4731
+ if (activeAnimation) {
4732
+ activeAnimation.stop();
4733
+ activeAnimation = null;
4734
+ }
4735
+ };
4736
+ const startAnimation = () => {
4737
+ stopAnimation();
4738
+ const currentValue = asNumber$1(value.get());
4739
+ const targetValue = asNumber$1(latestValue);
4740
+ // Don't animate if we're already at the target
4741
+ if (currentValue === targetValue) {
4742
+ return;
4743
+ }
4744
+ activeAnimation = new JSAnimation({
4745
+ keyframes: [currentValue, targetValue],
4746
+ velocity: value.getVelocity(),
4747
+ // Default to spring if no type specified (matches useSpring behavior)
4748
+ type: "spring",
4749
+ restDelta: 0.001,
4750
+ restSpeed: 0.01,
4751
+ ...options,
4752
+ onUpdate: latestSetter,
4753
+ });
4754
+ };
4755
+ value.attach((v, set) => {
4756
+ latestValue = v;
4757
+ latestSetter = (latest) => set(parseValue(latest, unit));
4758
+ frame.postRender(() => {
4759
+ startAnimation();
4760
+ value["events"].animationStart?.notify();
4761
+ activeAnimation?.then(() => {
4762
+ value["events"].animationComplete?.notify();
4763
+ });
4764
+ });
4765
+ }, stopAnimation);
4766
+ if (isMotionValue(source)) {
4767
+ const removeSourceOnChange = source.on("change", (v) => value.set(parseValue(v, unit)));
4768
+ const removeValueOnDestroy = value.on("destroy", removeSourceOnChange);
4769
+ return () => {
4770
+ removeSourceOnChange();
4771
+ removeValueOnDestroy();
4772
+ };
4773
+ }
4774
+ return stopAnimation;
4775
+ }
4776
+ function parseValue(v, unit) {
4777
+ return unit ? v + unit : v;
4778
+ }
4779
+ function asNumber$1(v) {
4780
+ return typeof v === "number" ? v : parseFloat(v);
4781
+ }
4782
+
4681
4783
  function subscribeValue(inputValues, outputValue, getLatest) {
4682
4784
  const update = () => outputValue.set(getLatest());
4683
4785
  const scheduleUpdate = () => frame.preRender(update, false, true);
@@ -4767,72 +4869,30 @@ function mapValue(inputValue, inputRange, outputRange, options) {
4767
4869
  *
4768
4870
  * ```jsx
4769
4871
  * const x = motionValue(0)
4770
- * const y = transformValue(() => x.get() * 2) // double x
4872
+ * const y = springValue(x, { stiffness: 300 })
4771
4873
  * ```
4772
4874
  *
4773
- * @param transformer - A transform function. This function must be pure with no side-effects or conditional statements.
4875
+ * @param source - Initial value or MotionValue to track
4876
+ * @param options - Spring configuration options
4774
4877
  * @returns `MotionValue`
4775
4878
  *
4776
4879
  * @public
4777
4880
  */
4778
4881
  function springValue(source, options) {
4779
- const initialValue = isMotionValue(source) ? source.get() : source;
4780
- const value = motionValue(initialValue);
4781
- attachSpring(value, source, options);
4782
- return value;
4882
+ return followValue(source, { type: "spring", ...options });
4783
4883
  }
4884
+ /**
4885
+ * Attach a spring animation to a MotionValue that will animate whenever the value changes.
4886
+ *
4887
+ * @param value - The MotionValue to animate
4888
+ * @param source - Initial value or MotionValue to track
4889
+ * @param options - Spring configuration options
4890
+ * @returns Cleanup function
4891
+ *
4892
+ * @public
4893
+ */
4784
4894
  function attachSpring(value, source, options) {
4785
- const initialValue = value.get();
4786
- let activeAnimation = null;
4787
- let latestValue = initialValue;
4788
- let latestSetter;
4789
- const unit = typeof initialValue === "string"
4790
- ? initialValue.replace(/[\d.-]/g, "")
4791
- : undefined;
4792
- const stopAnimation = () => {
4793
- if (activeAnimation) {
4794
- activeAnimation.stop();
4795
- activeAnimation = null;
4796
- }
4797
- };
4798
- const startAnimation = () => {
4799
- stopAnimation();
4800
- activeAnimation = new JSAnimation({
4801
- keyframes: [asNumber$1(value.get()), asNumber$1(latestValue)],
4802
- velocity: value.getVelocity(),
4803
- type: "spring",
4804
- restDelta: 0.001,
4805
- restSpeed: 0.01,
4806
- ...options,
4807
- onUpdate: latestSetter,
4808
- });
4809
- };
4810
- value.attach((v, set) => {
4811
- latestValue = v;
4812
- latestSetter = (latest) => set(parseValue(latest, unit));
4813
- frame.postRender(() => {
4814
- startAnimation();
4815
- value['events'].animationStart?.notify();
4816
- activeAnimation?.then(() => {
4817
- value['events'].animationComplete?.notify();
4818
- });
4819
- });
4820
- }, stopAnimation);
4821
- if (isMotionValue(source)) {
4822
- const removeSourceOnChange = source.on("change", (v) => value.set(parseValue(v, unit)));
4823
- const removeValueOnDestroy = value.on("destroy", removeSourceOnChange);
4824
- return () => {
4825
- removeSourceOnChange();
4826
- removeValueOnDestroy();
4827
- };
4828
- }
4829
- return stopAnimation;
4830
- }
4831
- function parseValue(v, unit) {
4832
- return unit ? v + unit : v;
4833
- }
4834
- function asNumber$1(v) {
4835
- return typeof v === "number" ? v : parseFloat(v);
4895
+ return attachFollow(value, source, { type: "spring", ...options });
4836
4896
  }
4837
4897
 
4838
4898
  /**
@@ -6032,7 +6092,8 @@ function buildTransform(latestValues, transform, transformTemplate) {
6032
6092
  valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
6033
6093
  }
6034
6094
  else {
6035
- valueIsDefault = parseFloat(value) === 0;
6095
+ const parsed = parseFloat(value);
6096
+ valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0;
6036
6097
  }
6037
6098
  if (!valueIsDefault || transformTemplate) {
6038
6099
  const valueAsType = getValueAsType(value, numberValueTypes[key]);
@@ -6335,6 +6396,9 @@ const camelKeys = {
6335
6396
  * and stroke-dasharray attributes.
6336
6397
  *
6337
6398
  * This function is mutative to reduce per-frame GC.
6399
+ *
6400
+ * Note: We use unitless values for stroke-dasharray and stroke-dashoffset
6401
+ * because Safari incorrectly scales px values when the page is zoomed.
6338
6402
  */
6339
6403
  function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) {
6340
6404
  // Normalise path length by setting SVG attribute pathLength to 1
@@ -6342,12 +6406,10 @@ function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true
6342
6406
  // We use dash case when setting attributes directly to the DOM node and camel case
6343
6407
  // when defining props on a React component.
6344
6408
  const keys = useDashCase ? dashKeys : camelKeys;
6345
- // Build the dash offset
6346
- attrs[keys.offset] = px.transform(-offset);
6347
- // Build the dash array
6348
- const pathLength = px.transform(length);
6349
- const pathSpacing = px.transform(spacing);
6350
- attrs[keys.array] = `${pathLength} ${pathSpacing}`;
6409
+ // Build the dash offset (unitless to avoid Safari zoom bug)
6410
+ attrs[keys.offset] = `${-offset}`;
6411
+ // Build the dash array (unitless to avoid Safari zoom bug)
6412
+ attrs[keys.array] = `${length} ${spacing}`;
6351
6413
  }
6352
6414
 
6353
6415
  /**
@@ -7272,13 +7334,6 @@ class NodeStack {
7272
7334
  const prevLead = this.lead;
7273
7335
  if (node === prevLead)
7274
7336
  return;
7275
- console.log("[projection] promote", {
7276
- layoutId: node.options.layoutId,
7277
- node: node.id,
7278
- prevLead: prevLead?.id,
7279
- prevLeadSnapshot: Boolean(prevLead?.snapshot),
7280
- prevLeadResumeFrom: Boolean(prevLead?.resumeFrom),
7281
- });
7282
7337
  this.prevLead = prevLead;
7283
7338
  this.lead = node;
7284
7339
  node.show();
@@ -7387,7 +7442,7 @@ function cancelTreeOptimisedTransformAnimations(projectionNode) {
7387
7442
  cancelTreeOptimisedTransformAnimations(parent);
7388
7443
  }
7389
7444
  }
7390
- function createProjectionNode({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) {
7445
+ function createProjectionNode$1({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) {
7391
7446
  return class ProjectionNode {
7392
7447
  constructor(latestValues = {}, parent = defaultParent?.()) {
7393
7448
  /**
@@ -8944,11 +8999,11 @@ function checkNodeWasScrollRoot(node) {
8944
8999
  return node !== node.root && node.scroll?.wasRoot;
8945
9000
  }
8946
9001
 
8947
- const DocumentProjectionNode = createProjectionNode({
9002
+ const DocumentProjectionNode = createProjectionNode$1({
8948
9003
  attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify),
8949
9004
  measureScroll: () => ({
8950
- x: document.documentElement.scrollLeft || document.body.scrollLeft,
8951
- y: document.documentElement.scrollTop || document.body.scrollTop,
9005
+ x: document.documentElement.scrollLeft || document.body?.scrollLeft || 0,
9006
+ y: document.documentElement.scrollTop || document.body?.scrollTop || 0,
8952
9007
  }),
8953
9008
  checkIsScrollRoot: () => true,
8954
9009
  });
@@ -8979,7 +9034,7 @@ function nodeGroup() {
8979
9034
  const rootProjectionNode = {
8980
9035
  current: undefined,
8981
9036
  };
8982
- const HTMLProjectionNode = createProjectionNode({
9037
+ const HTMLProjectionNode = createProjectionNode$1({
8983
9038
  measureScroll: (instance) => ({
8984
9039
  x: instance.scrollLeft,
8985
9040
  y: instance.scrollTop,
@@ -8999,160 +9054,315 @@ const HTMLProjectionNode = createProjectionNode({
8999
9054
  checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"),
9000
9055
  });
9001
9056
 
9002
- const layoutSelector = "[data-layout], [data-layout-id]";
9003
- const noop = () => { };
9004
- function snapshotFromTarget(projection) {
9005
- const target = projection.targetWithTransforms || projection.target;
9006
- if (!target)
9007
- return undefined;
9008
- const measuredBox = createBox();
9009
- const layoutBox = createBox();
9010
- copyBoxInto(measuredBox, target);
9011
- copyBoxInto(layoutBox, target);
9057
+ const LAYOUT_SELECTOR = "[data-layout], [data-layout-id]";
9058
+ function getLayoutElements(scope) {
9059
+ const elements = Array.from(scope.querySelectorAll(LAYOUT_SELECTOR));
9060
+ // Include scope itself if it's an Element (not Document) and has layout attributes
9061
+ if (scope instanceof Element && hasLayout(scope)) {
9062
+ elements.unshift(scope);
9063
+ }
9064
+ return elements;
9065
+ }
9066
+ function getLayoutId(element) {
9067
+ return element.getAttribute("data-layout-id");
9068
+ }
9069
+ function hasLayout(element) {
9070
+ return (element.hasAttribute("data-layout") ||
9071
+ element.hasAttribute("data-layout-id"));
9072
+ }
9073
+
9074
+ let scaleCorrectorAdded = false;
9075
+ /**
9076
+ * Track active projection nodes per element to handle animation interruption.
9077
+ * When a new animation starts on an element that already has an active animation,
9078
+ * we need to stop the old animation so the new one can start from the current
9079
+ * visual position.
9080
+ */
9081
+ const activeProjectionNodes = new WeakMap();
9082
+ function ensureScaleCorrectors() {
9083
+ if (scaleCorrectorAdded)
9084
+ return;
9085
+ scaleCorrectorAdded = true;
9086
+ addScaleCorrector({
9087
+ borderRadius: {
9088
+ ...correctBorderRadius,
9089
+ applyTo: [
9090
+ "borderTopLeftRadius",
9091
+ "borderTopRightRadius",
9092
+ "borderBottomLeftRadius",
9093
+ "borderBottomRightRadius",
9094
+ ],
9095
+ },
9096
+ borderTopLeftRadius: correctBorderRadius,
9097
+ borderTopRightRadius: correctBorderRadius,
9098
+ borderBottomLeftRadius: correctBorderRadius,
9099
+ borderBottomRightRadius: correctBorderRadius,
9100
+ boxShadow: correctBoxShadow,
9101
+ });
9102
+ }
9103
+ /**
9104
+ * Get DOM depth of an element
9105
+ */
9106
+ function getDepth(element) {
9107
+ let depth = 0;
9108
+ let current = element.parentElement;
9109
+ while (current) {
9110
+ depth++;
9111
+ current = current.parentElement;
9112
+ }
9113
+ return depth;
9114
+ }
9115
+ /**
9116
+ * Find the closest projection parent for an element
9117
+ */
9118
+ function findProjectionParent(element, nodeCache) {
9119
+ let parent = element.parentElement;
9120
+ while (parent) {
9121
+ const node = nodeCache.get(parent);
9122
+ if (node)
9123
+ return node;
9124
+ parent = parent.parentElement;
9125
+ }
9126
+ return undefined;
9127
+ }
9128
+ /**
9129
+ * Create or reuse a projection node for an element
9130
+ */
9131
+ function createProjectionNode(element, parent, options, transition) {
9132
+ // Check for existing active node - reuse it to preserve animation state
9133
+ const existingNode = activeProjectionNodes.get(element);
9134
+ if (existingNode) {
9135
+ const visualElement = existingNode.options.visualElement;
9136
+ // Update transition options for the new animation
9137
+ const nodeTransition = transition
9138
+ ? { duration: transition.duration, ease: transition.ease }
9139
+ : { duration: 0.3, ease: "easeOut" };
9140
+ existingNode.setOptions({
9141
+ ...existingNode.options,
9142
+ animate: true,
9143
+ transition: nodeTransition,
9144
+ ...options,
9145
+ });
9146
+ // Re-mount the node if it was previously unmounted
9147
+ // This re-adds it to root.nodes so didUpdate() will process it
9148
+ if (!existingNode.instance) {
9149
+ existingNode.mount(element);
9150
+ }
9151
+ return { node: existingNode, visualElement };
9152
+ }
9153
+ // No existing node - create a new one
9154
+ const latestValues = {};
9155
+ const visualElement = new HTMLVisualElement({
9156
+ visualState: {
9157
+ latestValues,
9158
+ renderState: {
9159
+ transformOrigin: {},
9160
+ transform: {},
9161
+ style: {},
9162
+ vars: {},
9163
+ },
9164
+ },
9165
+ presenceContext: null,
9166
+ props: {},
9167
+ });
9168
+ const node = new HTMLProjectionNode(latestValues, parent);
9169
+ // Convert AnimationOptions to transition format for the projection system
9170
+ const nodeTransition = transition
9171
+ ? { duration: transition.duration, ease: transition.ease }
9172
+ : { duration: 0.3, ease: "easeOut" };
9173
+ node.setOptions({
9174
+ visualElement,
9175
+ layout: true,
9176
+ animate: true,
9177
+ transition: nodeTransition,
9178
+ ...options,
9179
+ });
9180
+ node.mount(element);
9181
+ visualElement.projection = node;
9182
+ // Track this node as the active one for this element
9183
+ activeProjectionNodes.set(element, node);
9184
+ return { node, visualElement };
9185
+ }
9186
+ /**
9187
+ * Build a projection tree from a list of elements
9188
+ */
9189
+ function buildProjectionTree(elements, existingContext, options) {
9190
+ ensureScaleCorrectors();
9191
+ const nodes = existingContext?.nodes ?? new Map();
9192
+ const visualElements = existingContext?.visualElements ?? new Map();
9193
+ const group = existingContext?.group ?? nodeGroup();
9194
+ const defaultTransition = options?.defaultTransition;
9195
+ const sharedTransitions = options?.sharedTransitions;
9196
+ // Sort elements by DOM depth (parents before children)
9197
+ const sorted = [...elements].sort((a, b) => getDepth(a) - getDepth(b));
9198
+ let root = existingContext?.root;
9199
+ for (const element of sorted) {
9200
+ // Skip if already has a node
9201
+ if (nodes.has(element))
9202
+ continue;
9203
+ const parent = findProjectionParent(element, nodes);
9204
+ const layoutId = getLayoutId(element);
9205
+ const layoutMode = element.getAttribute("data-layout");
9206
+ const nodeOptions = {
9207
+ layoutId: layoutId ?? undefined,
9208
+ animationType: parseLayoutMode(layoutMode),
9209
+ };
9210
+ // Use layoutId-specific transition if available, otherwise use default
9211
+ const transition = layoutId && sharedTransitions?.get(layoutId)
9212
+ ? sharedTransitions.get(layoutId)
9213
+ : defaultTransition;
9214
+ const { node, visualElement } = createProjectionNode(element, parent, nodeOptions, transition);
9215
+ nodes.set(element, node);
9216
+ visualElements.set(element, visualElement);
9217
+ group.add(node);
9218
+ if (!root) {
9219
+ root = node.root;
9220
+ }
9221
+ }
9012
9222
  return {
9013
- animationId: projection.root?.animationId ?? 0,
9014
- measuredBox,
9015
- layoutBox,
9016
- latestValues: projection.animationValues || projection.latestValues || {},
9017
- source: projection.id,
9223
+ nodes,
9224
+ visualElements,
9225
+ group,
9226
+ root: root,
9018
9227
  };
9019
9228
  }
9229
+ /**
9230
+ * Parse the data-layout attribute value
9231
+ */
9232
+ function parseLayoutMode(value) {
9233
+ if (value === "position")
9234
+ return "position";
9235
+ if (value === "size")
9236
+ return "size";
9237
+ if (value === "preserve-aspect")
9238
+ return "preserve-aspect";
9239
+ return "both";
9240
+ }
9241
+ /**
9242
+ * Clean up projection nodes for specific elements.
9243
+ * If elementsToCleanup is provided, only those elements are cleaned up.
9244
+ * If not provided, all nodes are cleaned up.
9245
+ *
9246
+ * This allows persisting elements to keep their nodes between animations,
9247
+ * matching React's behavior where nodes persist for elements that remain in the DOM.
9248
+ */
9249
+ function cleanupProjectionTree(context, elementsToCleanup) {
9250
+ const elementsToProcess = elementsToCleanup
9251
+ ? [...context.nodes.entries()].filter(([el]) => elementsToCleanup.has(el))
9252
+ : [...context.nodes.entries()];
9253
+ for (const [element, node] of elementsToProcess) {
9254
+ context.group.remove(node);
9255
+ node.unmount();
9256
+ // Only clear from activeProjectionNodes if this is still the active node.
9257
+ // A newer animation might have already taken over.
9258
+ if (activeProjectionNodes.get(element) === node) {
9259
+ activeProjectionNodes.delete(element);
9260
+ }
9261
+ context.nodes.delete(element);
9262
+ context.visualElements.delete(element);
9263
+ }
9264
+ }
9265
+
9020
9266
  class LayoutAnimationBuilder {
9021
9267
  constructor(scope, updateDom, defaultOptions) {
9022
9268
  this.sharedTransitions = new Map();
9023
- this.notifyReady = noop;
9024
- this.rejectReady = noop;
9269
+ this.notifyReady = motionUtils.noop;
9270
+ this.executed = false;
9025
9271
  this.scope = scope;
9026
9272
  this.updateDom = updateDom;
9027
9273
  this.defaultOptions = defaultOptions;
9028
- this.readyPromise = new Promise((resolve, reject) => {
9274
+ this.readyPromise = new Promise((resolve) => {
9029
9275
  this.notifyReady = resolve;
9030
- this.rejectReady = reject;
9031
- });
9032
- frame.postRender(() => {
9033
- this.start().then(this.notifyReady).catch(this.rejectReady);
9034
9276
  });
9277
+ // Queue execution on microtask to allow builder methods to be called
9278
+ queueMicrotask(() => this.execute());
9035
9279
  }
9036
- shared(id, transition) {
9037
- this.sharedTransitions.set(id, transition);
9280
+ shared(id, options) {
9281
+ this.sharedTransitions.set(id, options);
9038
9282
  return this;
9039
9283
  }
9040
- then(resolve, reject) {
9041
- return this.readyPromise.then(resolve, reject);
9284
+ then(onfulfilled, onrejected) {
9285
+ return this.readyPromise.then(onfulfilled, onrejected);
9042
9286
  }
9043
- async start() {
9044
- const beforeElements = collectLayoutElements(this.scope);
9045
- const beforeRecords = this.buildRecords(beforeElements);
9046
- const exitCandidates = collectExitCandidates(beforeRecords);
9047
- beforeRecords.forEach(({ projection }) => {
9048
- const hasCurrentAnimation = Boolean(projection.currentAnimation);
9049
- const isSharedLayout = Boolean(projection.options.layoutId);
9050
- if (hasCurrentAnimation && isSharedLayout) {
9051
- const snapshot = snapshotFromTarget(projection);
9052
- if (snapshot) {
9053
- projection.snapshot = snapshot;
9054
- }
9055
- else if (projection.snapshot) {
9056
- projection.snapshot = undefined;
9057
- }
9058
- }
9059
- else if (projection.snapshot &&
9060
- (projection.currentAnimation || projection.isProjecting())) {
9061
- projection.snapshot = undefined;
9062
- }
9063
- projection.isPresent = true;
9064
- projection.willUpdate();
9065
- });
9066
- await this.updateDom();
9067
- const afterElements = collectLayoutElements(this.scope);
9068
- const afterRecords = this.buildRecords(afterElements);
9069
- const exitRecords = this.handleExitingElements(beforeRecords, afterRecords, exitCandidates);
9070
- afterRecords.forEach(({ projection }) => {
9071
- const instance = projection.instance;
9072
- const resumeFromInstance = projection.resumeFrom
9073
- ?.instance;
9074
- if (!instance || !resumeFromInstance)
9075
- return;
9076
- if (!("style" in instance))
9077
- return;
9078
- const currentTransform = instance.style.transform;
9079
- const resumeFromTransform = resumeFromInstance.style.transform;
9080
- if (currentTransform &&
9081
- resumeFromTransform &&
9082
- currentTransform === resumeFromTransform) {
9083
- instance.style.transform = "";
9084
- instance.style.transformOrigin = "";
9085
- }
9086
- });
9087
- afterRecords.forEach(({ projection }) => {
9088
- projection.isPresent = true;
9089
- });
9090
- const root = getProjectionRoot(afterRecords, beforeRecords);
9091
- root?.didUpdate();
9092
- await new Promise((resolve) => {
9093
- frame.postRender(() => resolve());
9094
- });
9095
- const animations = collectAnimations(afterRecords, exitRecords);
9096
- const animation = new GroupAnimation(animations);
9097
- if (exitRecords.length) {
9098
- const cleanup = () => {
9099
- exitRecords.forEach(({ element, visualElement }) => {
9100
- if (element.isConnected) {
9101
- element.remove();
9102
- }
9103
- visualElement.unmount();
9104
- visualElementStore.delete(element);
9105
- });
9106
- };
9107
- animation.finished.then(cleanup, cleanup);
9287
+ async execute() {
9288
+ if (this.executed)
9289
+ return;
9290
+ this.executed = true;
9291
+ let context;
9292
+ // Phase 1: Pre-mutation - Build projection tree and take snapshots
9293
+ const beforeElements = getLayoutElements(this.scope);
9294
+ if (beforeElements.length > 0) {
9295
+ context = buildProjectionTree(beforeElements, undefined, this.getBuildOptions());
9296
+ context.root.startUpdate();
9297
+ for (const node of context.nodes.values()) {
9298
+ node.isLayoutDirty = false;
9299
+ node.willUpdate();
9300
+ }
9301
+ }
9302
+ // Phase 2: Execute DOM update
9303
+ this.updateDom();
9304
+ // Phase 3: Post-mutation - Compare before/after elements
9305
+ const afterElements = getLayoutElements(this.scope);
9306
+ const beforeSet = new Set(beforeElements);
9307
+ const afterSet = new Set(afterElements);
9308
+ const entering = afterElements.filter((el) => !beforeSet.has(el));
9309
+ const exiting = beforeElements.filter((el) => !afterSet.has(el));
9310
+ // Build projection nodes for entering elements
9311
+ if (entering.length > 0) {
9312
+ context = buildProjectionTree(entering, context, this.getBuildOptions());
9313
+ }
9314
+ // No layout elements - return empty animation
9315
+ if (!context) {
9316
+ this.notifyReady(new GroupAnimation([]));
9317
+ return;
9108
9318
  }
9109
- return animation;
9110
- }
9111
- buildRecords(elements) {
9112
- const records = [];
9113
- const recordMap = new Map();
9114
- for (const element of elements) {
9115
- const parentRecord = findParentRecord(element, recordMap, this.scope);
9116
- const { layout, layoutId } = readLayoutAttributes(element);
9117
- const override = layoutId
9118
- ? this.sharedTransitions.get(layoutId)
9119
- : undefined;
9120
- const transition = override || this.defaultOptions;
9121
- const record = getOrCreateRecord(element, parentRecord?.projection, {
9122
- layout,
9123
- layoutId,
9124
- animationType: typeof layout === "string" ? layout : "both",
9125
- transition: transition,
9126
- });
9127
- recordMap.set(element, record);
9128
- records.push(record);
9319
+ // Handle shared elements
9320
+ for (const element of exiting) {
9321
+ const node = context.nodes.get(element);
9322
+ node?.getStack()?.remove(node);
9129
9323
  }
9130
- return records;
9131
- }
9132
- handleExitingElements(beforeRecords, afterRecords, exitCandidates) {
9133
- const afterElementsSet = new Set(afterRecords.map((record) => record.element));
9134
- const exiting = [];
9135
- beforeRecords.forEach((record) => {
9136
- if (afterElementsSet.has(record.element))
9137
- return;
9138
- const exitRecord = exitCandidates.get(record.element);
9139
- if (!exitRecord) {
9140
- record.visualElement.unmount();
9141
- visualElementStore.delete(record.element);
9142
- return;
9143
- }
9144
- if (!exitRecord.element.isConnected) {
9145
- reinstateExitElement(exitRecord);
9146
- }
9147
- record.projection.isPresent = false;
9148
- if (record.projection.options.layoutId) {
9149
- record.projection.relegate();
9324
+ for (const element of entering) {
9325
+ context.nodes.get(element)?.promote();
9326
+ }
9327
+ // Phase 4: Animate
9328
+ context.root.didUpdate();
9329
+ await new Promise((resolve) => frame.postRender(() => resolve()));
9330
+ const animations = [];
9331
+ for (const node of context.nodes.values()) {
9332
+ if (node.currentAnimation) {
9333
+ animations.push(node.currentAnimation);
9334
+ }
9335
+ }
9336
+ const groupAnimation = new GroupAnimation(animations);
9337
+ groupAnimation.finished.then(() => {
9338
+ // Only clean up nodes for elements no longer in the document.
9339
+ // Elements still in DOM keep their nodes so subsequent animations
9340
+ // can use the stored position snapshots (A→B→A pattern).
9341
+ const elementsToCleanup = new Set();
9342
+ for (const element of context.nodes.keys()) {
9343
+ if (!document.contains(element)) {
9344
+ elementsToCleanup.add(element);
9345
+ }
9150
9346
  }
9151
- exiting.push(record);
9347
+ cleanupProjectionTree(context, elementsToCleanup);
9152
9348
  });
9153
- return exiting;
9349
+ this.notifyReady(groupAnimation);
9350
+ }
9351
+ getBuildOptions() {
9352
+ return {
9353
+ defaultTransition: this.defaultOptions || {
9354
+ duration: 0.3,
9355
+ ease: "easeOut",
9356
+ },
9357
+ sharedTransitions: this.sharedTransitions.size > 0
9358
+ ? this.sharedTransitions
9359
+ : undefined,
9360
+ };
9154
9361
  }
9155
9362
  }
9363
+ /**
9364
+ * Parse arguments for animateLayout overloads
9365
+ */
9156
9366
  function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9157
9367
  // animateLayout(updateDom)
9158
9368
  if (typeof scopeOrUpdateDom === "function") {
@@ -9166,125 +9376,11 @@ function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9166
9376
  const elements = resolveElements(scopeOrUpdateDom);
9167
9377
  const scope = elements[0] || document;
9168
9378
  return {
9169
- scope,
9379
+ scope: scope instanceof Document ? scope : scope,
9170
9380
  updateDom: updateDomOrOptions,
9171
9381
  defaultOptions: options,
9172
9382
  };
9173
9383
  }
9174
- function collectLayoutElements(scope) {
9175
- const elements = Array.from(scope.querySelectorAll(layoutSelector));
9176
- if (scope instanceof Element && scope.matches(layoutSelector)) {
9177
- if (!elements.includes(scope)) {
9178
- elements.unshift(scope);
9179
- }
9180
- }
9181
- return elements;
9182
- }
9183
- function readLayoutAttributes(element) {
9184
- const layoutId = element.getAttribute("data-layout-id") || undefined;
9185
- const rawLayout = element.getAttribute("data-layout");
9186
- let layout;
9187
- if (rawLayout === "" || rawLayout === "true") {
9188
- layout = true;
9189
- }
9190
- else if (rawLayout) {
9191
- layout = rawLayout;
9192
- }
9193
- return {
9194
- layout,
9195
- layoutId,
9196
- layoutExit: element.hasAttribute("data-layout-exit"),
9197
- };
9198
- }
9199
- function createVisualState() {
9200
- return {
9201
- latestValues: {},
9202
- renderState: {
9203
- transform: {},
9204
- transformOrigin: {},
9205
- style: {},
9206
- vars: {},
9207
- },
9208
- };
9209
- }
9210
- function getOrCreateRecord(element, parentProjection, projectionOptions) {
9211
- const existing = visualElementStore.get(element);
9212
- const visualElement = existing ??
9213
- new HTMLVisualElement({
9214
- props: {},
9215
- presenceContext: null,
9216
- visualState: createVisualState(),
9217
- }, { allowProjection: true });
9218
- if (!existing || !visualElement.projection) {
9219
- visualElement.projection = new HTMLProjectionNode(visualElement.latestValues, parentProjection);
9220
- }
9221
- visualElement.projection.setOptions({
9222
- ...projectionOptions,
9223
- visualElement,
9224
- });
9225
- if (!visualElement.current) {
9226
- visualElement.mount(element);
9227
- }
9228
- if (!existing) {
9229
- visualElementStore.set(element, visualElement);
9230
- }
9231
- return {
9232
- element,
9233
- visualElement,
9234
- projection: visualElement.projection,
9235
- };
9236
- }
9237
- function findParentRecord(element, recordMap, scope) {
9238
- let parent = element.parentElement;
9239
- while (parent) {
9240
- const record = recordMap.get(parent);
9241
- if (record)
9242
- return record;
9243
- if (parent === scope)
9244
- break;
9245
- parent = parent.parentElement;
9246
- }
9247
- return undefined;
9248
- }
9249
- function collectExitCandidates(records) {
9250
- const exitCandidates = new Map();
9251
- records.forEach((record) => {
9252
- const { layoutExit } = readLayoutAttributes(record.element);
9253
- if (!layoutExit)
9254
- return;
9255
- exitCandidates.set(record.element, {
9256
- ...record,
9257
- parent: record.element.parentNode,
9258
- nextSibling: record.element.nextSibling,
9259
- });
9260
- });
9261
- return exitCandidates;
9262
- }
9263
- function reinstateExitElement(record) {
9264
- if (!record.parent)
9265
- return;
9266
- if (record.nextSibling && record.nextSibling.parentNode === record.parent) {
9267
- record.parent.insertBefore(record.element, record.nextSibling);
9268
- }
9269
- else {
9270
- record.parent.appendChild(record.element);
9271
- }
9272
- }
9273
- function getProjectionRoot(afterRecords, beforeRecords) {
9274
- const record = afterRecords[0] || beforeRecords[0];
9275
- return record?.projection.root;
9276
- }
9277
- function collectAnimations(afterRecords, exitRecords) {
9278
- const animations = new Set();
9279
- const addAnimation = (record) => {
9280
- const animation = record.projection.currentAnimation;
9281
- if (animation)
9282
- animations.add(animation);
9283
- };
9284
- afterRecords.forEach(addAnimation);
9285
- exitRecords.forEach(addAnimation);
9286
- return Array.from(animations);
9287
- }
9288
9384
 
9289
9385
  /**
9290
9386
  * @deprecated
@@ -9348,6 +9444,7 @@ exports.applyPointDelta = applyPointDelta;
9348
9444
  exports.applyPxDefaults = applyPxDefaults;
9349
9445
  exports.applyTreeDeltas = applyTreeDeltas;
9350
9446
  exports.aspectRatio = aspectRatio;
9447
+ exports.attachFollow = attachFollow;
9351
9448
  exports.attachSpring = attachSpring;
9352
9449
  exports.attrEffect = attrEffect;
9353
9450
  exports.axisDeltaEquals = axisDeltaEquals;
@@ -9395,7 +9492,7 @@ exports.createAxisDelta = createAxisDelta;
9395
9492
  exports.createBox = createBox;
9396
9493
  exports.createDelta = createDelta;
9397
9494
  exports.createGeneratorEasing = createGeneratorEasing;
9398
- exports.createProjectionNode = createProjectionNode;
9495
+ exports.createProjectionNode = createProjectionNode$1;
9399
9496
  exports.createRenderBatcher = createRenderBatcher;
9400
9497
  exports.cubicBezierAsString = cubicBezierAsString;
9401
9498
  exports.defaultEasing = defaultEasing;
@@ -9412,6 +9509,7 @@ exports.fillWildcards = fillWildcards;
9412
9509
  exports.findDimensionValueType = findDimensionValueType;
9413
9510
  exports.findValueType = findValueType;
9414
9511
  exports.flushKeyframeResolvers = flushKeyframeResolvers;
9512
+ exports.followValue = followValue;
9415
9513
  exports.frame = frame;
9416
9514
  exports.frameData = frameData;
9417
9515
  exports.frameSteps = frameSteps;