motion-dom 12.28.1-alpha.0 → 12.28.1

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