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