motion-dom 12.24.11 → 12.27.0-alpha.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.
package/dist/cjs/index.js CHANGED
@@ -3734,6 +3734,811 @@ function convertAttrKey(key) {
3734
3734
  return key.replace(/^attr([A-Z])/, (_, firstChar) => firstChar.toLowerCase());
3735
3735
  }
3736
3736
 
3737
+ /**
3738
+ * Utilities for observing DOM mutations during layout animations.
3739
+ * Used to detect elements added/removed during mutation callbacks
3740
+ * for enter/exit animations.
3741
+ */
3742
+ /**
3743
+ * Selectors for elements that should participate in layout animations
3744
+ */
3745
+ const LAYOUT_SELECTORS$1 = ["[data-layout]", "[data-layout-id]"];
3746
+ /**
3747
+ * Execute a mutation callback while observing DOM changes.
3748
+ * Returns information about elements that were added or removed.
3749
+ *
3750
+ * Uses a snapshot approach since MutationObserver callbacks are async.
3751
+ *
3752
+ * @param container - The container to observe for mutations
3753
+ * @param mutation - The mutation callback to execute
3754
+ * @returns Information about elements added/removed during the mutation
3755
+ *
3756
+ * @example
3757
+ * ```typescript
3758
+ * const { addedElements, removedElements } = observeMutation(
3759
+ * document.body,
3760
+ * () => {
3761
+ * list.innerHTML = newContent
3762
+ * }
3763
+ * )
3764
+ *
3765
+ * // Handle newly added elements with enter animations
3766
+ * addedElements.forEach(el => animateEnter(el))
3767
+ *
3768
+ * // Handle removed elements with exit animations
3769
+ * removedElements.forEach(el => animateExit(el))
3770
+ * ```
3771
+ */
3772
+ function observeMutation(container, mutation) {
3773
+ // Snapshot approach: capture layout elements before and after mutation
3774
+ // MutationObserver callbacks are async microtasks, so we use direct comparison instead
3775
+ const selector = LAYOUT_SELECTORS$1.join(", ");
3776
+ // Capture elements and their bounds before mutation
3777
+ const elementsBefore = new Map();
3778
+ container.querySelectorAll(selector).forEach((el) => {
3779
+ elementsBefore.set(el, el.getBoundingClientRect());
3780
+ });
3781
+ // Execute the mutation
3782
+ mutation();
3783
+ // Capture elements after mutation
3784
+ const elementsAfter = new Set(container.querySelectorAll(selector));
3785
+ // Find added elements (in after but not in before)
3786
+ const addedElements = [];
3787
+ elementsAfter.forEach((el) => {
3788
+ if (!elementsBefore.has(el) && el instanceof HTMLElement) {
3789
+ addedElements.push(el);
3790
+ }
3791
+ });
3792
+ // Find removed elements (in before but not in after) with their pre-removal bounds
3793
+ const removedElements = [];
3794
+ elementsBefore.forEach((bounds, el) => {
3795
+ if (!elementsAfter.has(el) && el instanceof HTMLElement) {
3796
+ removedElements.push({ element: el, bounds });
3797
+ }
3798
+ });
3799
+ return { addedElements, removedElements };
3800
+ }
3801
+ /**
3802
+ * Find the common ancestor of a list of elements.
3803
+ * Used to determine the container for mutation observation.
3804
+ *
3805
+ * @param elements - Elements to find common ancestor of
3806
+ * @returns The common ancestor element, or document.body if none found
3807
+ */
3808
+ function findCommonAncestor(elements) {
3809
+ if (elements.length === 0)
3810
+ return document.body;
3811
+ if (elements.length === 1)
3812
+ return elements[0].parentElement ?? document.body;
3813
+ // Start with the first element's ancestors
3814
+ const ancestors = new Set();
3815
+ let el = elements[0];
3816
+ while (el) {
3817
+ ancestors.add(el);
3818
+ el = el.parentElement;
3819
+ }
3820
+ // Find the first ancestor that contains all elements
3821
+ for (let i = 1; i < elements.length; i++) {
3822
+ el = elements[i];
3823
+ while (el) {
3824
+ if (ancestors.has(el)) {
3825
+ // Check if this element contains all other elements
3826
+ const containsAll = elements.every((e) => el === e || el?.contains(e));
3827
+ if (containsAll) {
3828
+ return el;
3829
+ }
3830
+ }
3831
+ el = el.parentElement;
3832
+ }
3833
+ }
3834
+ return document.body;
3835
+ }
3836
+ /**
3837
+ * Keep an element in the DOM for exit animation.
3838
+ * Returns a cleanup function to remove the clone after animation.
3839
+ *
3840
+ * @param element - The element that was removed
3841
+ * @param bounds - The element's bounds before removal
3842
+ * @param container - Container to add the clone to
3843
+ * @returns Object with clone element and cleanup function
3844
+ */
3845
+ function preserveElementForExit(element, bounds, container) {
3846
+ // Clone the element to keep it in the DOM for animation
3847
+ const clone = element.cloneNode(true);
3848
+ // Position it absolutely at its last known position (from pre-captured bounds)
3849
+ clone.style.position = "fixed";
3850
+ clone.style.top = `${bounds.top}px`;
3851
+ clone.style.left = `${bounds.left}px`;
3852
+ clone.style.width = `${bounds.width}px`;
3853
+ clone.style.height = `${bounds.height}px`;
3854
+ clone.style.margin = "0";
3855
+ clone.style.pointerEvents = "none";
3856
+ clone.style.zIndex = "9999";
3857
+ // Mark as exiting to prevent re-observation
3858
+ clone.setAttribute("data-layout-exiting", "true");
3859
+ // Add to container
3860
+ container.appendChild(clone);
3861
+ return {
3862
+ clone,
3863
+ cleanup: () => {
3864
+ if (clone.parentNode) {
3865
+ clone.parentNode.removeChild(clone);
3866
+ }
3867
+ },
3868
+ };
3869
+ }
3870
+
3871
+ /**
3872
+ * Default transition for layout animations
3873
+ */
3874
+ const defaultTransition = {
3875
+ duration: 0.3,
3876
+ ease: [0.4, 0, 0.2, 1], // ease-out cubic
3877
+ };
3878
+ /**
3879
+ * Global factory for creating projection nodes and visual elements.
3880
+ * This must be set by the consuming package (e.g., framer-motion).
3881
+ */
3882
+ let globalFactory = null;
3883
+ /**
3884
+ * Set the global factory for creating layout nodes.
3885
+ * This should be called by framer-motion to provide concrete implementations.
3886
+ */
3887
+ function setLayoutNodeFactory(factory) {
3888
+ globalFactory = factory;
3889
+ }
3890
+ /**
3891
+ * Get the current layout node factory
3892
+ */
3893
+ function getLayoutNodeFactory() {
3894
+ return globalFactory;
3895
+ }
3896
+ /**
3897
+ * Internal node cache for tracking elements across animations
3898
+ */
3899
+ const nodeCache = new WeakMap();
3900
+ /**
3901
+ * Create or retrieve a projection node for an element
3902
+ */
3903
+ function getOrCreateNode(element, parent, options, factory) {
3904
+ let node = nodeCache.get(element);
3905
+ if (!node) {
3906
+ node = factory.createProjectionNode(element, parent, options);
3907
+ nodeCache.set(element, node);
3908
+ }
3909
+ return node;
3910
+ }
3911
+ /**
3912
+ * Build a projection tree from a list of elements.
3913
+ * Parents are determined by DOM ancestry.
3914
+ */
3915
+ function buildProjectionTree(elements, options, factory) {
3916
+ // Sort by DOM depth (parents first)
3917
+ const sorted = [...elements].sort((a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
3918
+ const nodes = [];
3919
+ const elementToNode = new Map();
3920
+ for (const element of sorted) {
3921
+ if (!(element instanceof HTMLElement))
3922
+ continue;
3923
+ // Find parent node from previously processed elements
3924
+ let parent;
3925
+ let ancestor = element.parentElement;
3926
+ while (ancestor) {
3927
+ const ancestorNode = elementToNode.get(ancestor);
3928
+ if (ancestorNode) {
3929
+ parent = ancestorNode;
3930
+ break;
3931
+ }
3932
+ ancestor = ancestor.parentElement;
3933
+ }
3934
+ const node = getOrCreateNode(element, parent, options, factory);
3935
+ nodes.push(node);
3936
+ elementToNode.set(element, node);
3937
+ }
3938
+ return nodes;
3939
+ }
3940
+ /**
3941
+ * Apply enter animation to an element and return the animation controller
3942
+ */
3943
+ function applyEnterAnimation(element, config, defaultDuration) {
3944
+ const { keyframes, transition } = config;
3945
+ const duration = transition?.duration ?? defaultDuration;
3946
+ // Get the animation values from keyframes
3947
+ // Enter animations typically start from the keyframes values and animate to natural state
3948
+ const entries = Object.entries(keyframes);
3949
+ const fromValues = {};
3950
+ const toValues = {};
3951
+ for (const [key, value] of entries) {
3952
+ if (Array.isArray(value)) {
3953
+ // Multi-value keyframe - use first as start, last as end
3954
+ fromValues[key] = value[0];
3955
+ toValues[key] = value[value.length - 1];
3956
+ }
3957
+ else {
3958
+ // Single value - use as target, current as start
3959
+ toValues[key] = value;
3960
+ }
3961
+ }
3962
+ // Set initial state
3963
+ for (const [key, value] of Object.entries(fromValues)) {
3964
+ if (key in element.style) {
3965
+ element.style[key] = value;
3966
+ }
3967
+ }
3968
+ // Animate to final state using WAAPI
3969
+ const animation = element.animate([fromValues, toValues], {
3970
+ duration: duration * 1000,
3971
+ easing: typeof transition?.ease === "string"
3972
+ ? transition.ease
3973
+ : "ease-out",
3974
+ fill: "forwards",
3975
+ });
3976
+ // Commit styles when animation finishes
3977
+ if (animation.finished) {
3978
+ animation.finished.then(() => {
3979
+ animation.commitStyles();
3980
+ animation.cancel();
3981
+ });
3982
+ }
3983
+ return new NativeAnimationWrapper(animation);
3984
+ }
3985
+ /**
3986
+ * Apply exit animation to an element and return the animation controller
3987
+ */
3988
+ function applyExitAnimation(element, bounds, config, defaultDuration, container) {
3989
+ const { keyframes, transition } = config;
3990
+ const duration = transition?.duration ?? defaultDuration;
3991
+ // Preserve element in DOM for animation using pre-captured bounds
3992
+ const { clone, cleanup } = preserveElementForExit(element, bounds, container);
3993
+ // Animate to exit state
3994
+ const animation = clone.animate([{}, keyframes], {
3995
+ duration: duration * 1000,
3996
+ easing: typeof transition?.ease === "string" ? transition.ease : "ease-out",
3997
+ fill: "forwards",
3998
+ });
3999
+ // Cleanup when animation finishes
4000
+ animation.finished.then(cleanup);
4001
+ return new NativeAnimationWrapper(animation);
4002
+ }
4003
+ /**
4004
+ * Wait for the next animation frame
4005
+ */
4006
+ function nextFrame() {
4007
+ return new Promise((resolve) => {
4008
+ frame.postRender(() => resolve());
4009
+ });
4010
+ }
4011
+ /**
4012
+ * Execute layout animation on the given nodes and return a GroupAnimation
4013
+ */
4014
+ async function executeLayoutAnimation(nodes, mutation, options, enterConfig, exitConfig) {
4015
+ const animations = [];
4016
+ if (nodes.length === 0 && !mutation) {
4017
+ return new GroupAnimation(animations);
4018
+ }
4019
+ // 1. Snapshot phase - capture current positions
4020
+ nodes.forEach((node) => node.willUpdate());
4021
+ // Get container for mutation observation
4022
+ const elements = nodes
4023
+ .map((n) => n.instance)
4024
+ .filter((e) => e !== undefined);
4025
+ const container = findCommonAncestor(elements);
4026
+ // 2. Execute DOM mutation while observing for changes
4027
+ let addedElements = [];
4028
+ let removedElements = [];
4029
+ if (mutation) {
4030
+ const result = observeMutation(container, mutation);
4031
+ addedElements = result.addedElements;
4032
+ removedElements = result.removedElements;
4033
+ }
4034
+ // 3. Trigger layout update and animation
4035
+ const root = nodes[0]?.root;
4036
+ if (root) {
4037
+ root.didUpdate();
4038
+ }
4039
+ // 4. Wait for next frame - animations are created in frame.update()
4040
+ await nextFrame();
4041
+ // 5. Collect all animations from projection nodes
4042
+ for (const node of nodes) {
4043
+ if (node.currentAnimation) {
4044
+ animations.push(node.currentAnimation);
4045
+ }
4046
+ }
4047
+ // 6. Handle enter animations for newly added elements
4048
+ if (enterConfig && addedElements.length > 0) {
4049
+ for (const el of addedElements) {
4050
+ const anim = applyEnterAnimation(el, enterConfig, options.duration ?? 0.3);
4051
+ animations.push(anim);
4052
+ }
4053
+ }
4054
+ // 7. Handle exit animations for removed elements
4055
+ if (exitConfig && removedElements.length > 0) {
4056
+ for (const { element, bounds } of removedElements) {
4057
+ const anim = applyExitAnimation(element, bounds, exitConfig, options.duration ?? 0.3, container);
4058
+ animations.push(anim);
4059
+ }
4060
+ }
4061
+ return new GroupAnimation(animations);
4062
+ }
4063
+ /**
4064
+ * Selectors for elements that participate in layout animations
4065
+ */
4066
+ const LAYOUT_SELECTORS = "[data-layout], [data-layout-id]";
4067
+ /**
4068
+ * Check if a value is a valid element or selector
4069
+ */
4070
+ function isElementOrSelector(value) {
4071
+ return (value instanceof Element ||
4072
+ typeof value === "string" ||
4073
+ (Array.isArray(value) && value.length > 0 && value[0] instanceof Element) ||
4074
+ value instanceof NodeList);
4075
+ }
4076
+ /**
4077
+ * Animate layout changes for elements with data-layout or data-layout-id attributes.
4078
+ * Returns a builder that resolves to a GroupAnimation implementing AnimationPlaybackControls.
4079
+ *
4080
+ * When a selector/element is provided, it acts as a **scope** - layout elements
4081
+ * (those with data-layout or data-layout-id) are searched within that scope.
4082
+ *
4083
+ * @example
4084
+ * // Document-wide layout animation (all data-layout elements in document)
4085
+ * const animation = await animateLayout(() => {
4086
+ * updateDOM()
4087
+ * }, { duration: 0.3 })
4088
+ *
4089
+ * @example
4090
+ * // Scoped layout animation - finds data-layout elements within .container
4091
+ * const animation = await animateLayout(".container", () => {
4092
+ * // Toggle classes, the underline with data-layout-id will animate
4093
+ * oldTab.classList.remove("selected")
4094
+ * newTab.classList.add("selected")
4095
+ * }, { duration: 0.3 })
4096
+ *
4097
+ * @example
4098
+ * // Builder pattern with enter/exit animations
4099
+ * const animation = await animateLayout(".cards-container", { duration: 0.3 })
4100
+ * .enter({ opacity: [0, 1], scale: [0.8, 1] }, { duration: 0.2 })
4101
+ * .exit({ opacity: 0, scale: 0.8 }, { duration: 0.15 })
4102
+ * animation.time = 0 // Seek to start
4103
+ *
4104
+ * @example
4105
+ * // Scope to specific element
4106
+ * const animation = await animateLayout(containerElement, () => {
4107
+ * containerElement.querySelector('.item').style.width = "500px"
4108
+ * })
4109
+ */
4110
+ function animateLayout(elementOrSelectorOrMutation, mutationOrOptions, options) {
4111
+ // Check if factory is configured
4112
+ if (!globalFactory) {
4113
+ throw new Error("animateLayout: No layout node factory configured. " +
4114
+ "Make sure to import from 'framer-motion' or call setLayoutNodeFactory() first.");
4115
+ }
4116
+ const factory = globalFactory;
4117
+ // Parse overloaded arguments to support:
4118
+ // animateLayout(mutation, options) - document-wide
4119
+ // animateLayout(options) - document-wide
4120
+ // animateLayout(selector, mutation, options) - scoped
4121
+ // animateLayout(selector, options) - scoped
4122
+ let elements;
4123
+ let mutation;
4124
+ let opts;
4125
+ if (!elementOrSelectorOrMutation || !isElementOrSelector(elementOrSelectorOrMutation)) {
4126
+ // No selector provided - scope to entire document
4127
+ elements = Array.from(document.querySelectorAll(LAYOUT_SELECTORS));
4128
+ if (typeof elementOrSelectorOrMutation === "function") {
4129
+ // animateLayout(mutation, options)
4130
+ mutation = elementOrSelectorOrMutation;
4131
+ opts = mutationOrOptions ?? {};
4132
+ }
4133
+ else {
4134
+ // animateLayout(options) or animateLayout()
4135
+ mutation = typeof mutationOrOptions === "function" ? mutationOrOptions : undefined;
4136
+ opts = elementOrSelectorOrMutation ??
4137
+ (typeof mutationOrOptions === "object" ? mutationOrOptions : {});
4138
+ }
4139
+ }
4140
+ else {
4141
+ // Selector provided - use as scope for finding layout elements
4142
+ const scopeElements = resolveElements(elementOrSelectorOrMutation);
4143
+ elements = [];
4144
+ for (const scope of scopeElements) {
4145
+ // Find layout elements within this scope
4146
+ const layoutElements = scope.querySelectorAll(LAYOUT_SELECTORS);
4147
+ elements.push(...Array.from(layoutElements));
4148
+ // Also include the scope element itself if it has layout attributes
4149
+ if (scope.matches(LAYOUT_SELECTORS)) {
4150
+ elements.push(scope);
4151
+ }
4152
+ }
4153
+ // Remove duplicates (in case nested scopes)
4154
+ elements = [...new Set(elements)];
4155
+ mutation = typeof mutationOrOptions === "function" ? mutationOrOptions : undefined;
4156
+ opts = typeof mutationOrOptions === "object"
4157
+ ? mutationOrOptions
4158
+ : options ?? {};
4159
+ }
4160
+ // Merge with default transition
4161
+ const mergedOptions = {
4162
+ ...opts,
4163
+ transition: {
4164
+ ...defaultTransition,
4165
+ ...opts.transition,
4166
+ duration: opts.duration ?? opts.transition?.duration ?? 0.3,
4167
+ ease: opts.ease ?? opts.transition?.ease,
4168
+ },
4169
+ };
4170
+ // Build projection tree
4171
+ const nodes = buildProjectionTree(elements, mergedOptions, factory);
4172
+ // State for builder pattern
4173
+ let enterConfig;
4174
+ let exitConfig;
4175
+ let animationPromise;
4176
+ const builder = {
4177
+ enter(keyframes, transition) {
4178
+ enterConfig = { keyframes, transition };
4179
+ return builder;
4180
+ },
4181
+ exit(keyframes, transition) {
4182
+ exitConfig = { keyframes, transition };
4183
+ return builder;
4184
+ },
4185
+ then(onResolve, onReject) {
4186
+ // Execute animation if not already started
4187
+ if (!animationPromise) {
4188
+ animationPromise = executeLayoutAnimation(nodes, mutation, mergedOptions, enterConfig, exitConfig);
4189
+ }
4190
+ return animationPromise
4191
+ .then((groupAnimation) => onResolve(groupAnimation))
4192
+ .catch((err) => {
4193
+ if (onReject)
4194
+ onReject(err);
4195
+ throw err;
4196
+ });
4197
+ },
4198
+ };
4199
+ // If mutation is provided, schedule execution on microtask
4200
+ // to allow builder methods to be called first
4201
+ if (mutation) {
4202
+ queueMicrotask(() => {
4203
+ if (!animationPromise) {
4204
+ animationPromise = executeLayoutAnimation(nodes, mutation, mergedOptions, enterConfig, exitConfig);
4205
+ }
4206
+ });
4207
+ }
4208
+ return builder;
4209
+ }
4210
+
4211
+ class NodeStack {
4212
+ constructor() {
4213
+ this.members = [];
4214
+ }
4215
+ add(node) {
4216
+ motionUtils.addUniqueItem(this.members, node);
4217
+ node.scheduleRender();
4218
+ }
4219
+ remove(node) {
4220
+ motionUtils.removeItem(this.members, node);
4221
+ if (node === this.prevLead) {
4222
+ this.prevLead = undefined;
4223
+ }
4224
+ if (node === this.lead) {
4225
+ const prevLead = this.members[this.members.length - 1];
4226
+ if (prevLead) {
4227
+ this.promote(prevLead);
4228
+ }
4229
+ }
4230
+ }
4231
+ relegate(node) {
4232
+ const indexOfNode = this.members.findIndex((member) => node === member);
4233
+ if (indexOfNode === 0)
4234
+ return false;
4235
+ /**
4236
+ * Find the next projection node that is present
4237
+ */
4238
+ let prevLead;
4239
+ for (let i = indexOfNode; i >= 0; i--) {
4240
+ const member = this.members[i];
4241
+ if (member.isPresent !== false) {
4242
+ prevLead = member;
4243
+ break;
4244
+ }
4245
+ }
4246
+ if (prevLead) {
4247
+ this.promote(prevLead);
4248
+ return true;
4249
+ }
4250
+ else {
4251
+ return false;
4252
+ }
4253
+ }
4254
+ promote(node, preserveFollowOpacity) {
4255
+ const prevLead = this.lead;
4256
+ if (node === prevLead)
4257
+ return;
4258
+ this.prevLead = prevLead;
4259
+ this.lead = node;
4260
+ node.show();
4261
+ if (prevLead) {
4262
+ prevLead.instance && prevLead.scheduleRender();
4263
+ node.scheduleRender();
4264
+ node.resumeFrom = prevLead;
4265
+ if (preserveFollowOpacity) {
4266
+ node.resumeFrom.preserveOpacity = true;
4267
+ }
4268
+ if (prevLead.snapshot) {
4269
+ node.snapshot = prevLead.snapshot;
4270
+ node.snapshot.latestValues =
4271
+ prevLead.animationValues || prevLead.latestValues;
4272
+ }
4273
+ if (node.root && node.root.isUpdating) {
4274
+ node.isLayoutDirty = true;
4275
+ }
4276
+ const { crossfade } = node.options;
4277
+ if (crossfade === false) {
4278
+ prevLead.hide();
4279
+ }
4280
+ /**
4281
+ * TODO:
4282
+ * - Test border radius when previous node was deleted
4283
+ * - boxShadow mixing
4284
+ * - Shared between element A in scrolled container and element B (scroll stays the same or changes)
4285
+ * - Shared between element A in transformed container and element B (transform stays the same or changes)
4286
+ * - Shared between element A in scrolled page and element B (scroll stays the same or changes)
4287
+ * ---
4288
+ * - Crossfade opacity of root nodes
4289
+ * - layoutId changes after animation
4290
+ * - layoutId changes mid animation
4291
+ */
4292
+ }
4293
+ }
4294
+ exitAnimationComplete() {
4295
+ this.members.forEach((node) => {
4296
+ const { options, resumingFrom } = node;
4297
+ options.onExitComplete && options.onExitComplete();
4298
+ if (resumingFrom) {
4299
+ resumingFrom.options.onExitComplete &&
4300
+ resumingFrom.options.onExitComplete();
4301
+ }
4302
+ });
4303
+ }
4304
+ scheduleRender() {
4305
+ this.members.forEach((node) => {
4306
+ node.instance && node.scheduleRender(false);
4307
+ });
4308
+ }
4309
+ /**
4310
+ * Clear any leads that have been removed this render to prevent them from being
4311
+ * used in future animations and to prevent memory leaks
4312
+ */
4313
+ removeLeadSnapshot() {
4314
+ if (this.lead && this.lead.snapshot) {
4315
+ this.lead.snapshot = undefined;
4316
+ }
4317
+ }
4318
+ }
4319
+
4320
+ /**
4321
+ * Global registry for shared layout IDs (document-scoped).
4322
+ * This enables shared layout animations between elements with matching
4323
+ * `data-layout-id` attributes across the entire document.
4324
+ *
4325
+ * @example
4326
+ * ```html
4327
+ * <!-- These elements will animate between each other -->
4328
+ * <div data-layout-id="hero">Item A</div>
4329
+ * <div data-layout-id="hero">Item B</div>
4330
+ * ```
4331
+ */
4332
+ const sharedLayoutRegistry = new Map();
4333
+ /**
4334
+ * Register a projection node with a shared layout ID.
4335
+ * When a node with the same layoutId already exists, the new node
4336
+ * will resume from the previous lead node to create a crossfade animation.
4337
+ *
4338
+ * @param layoutId - The shared layout ID
4339
+ * @param node - The projection node to register
4340
+ * @param preserveFollowOpacity - Whether to preserve opacity during crossfade
4341
+ */
4342
+ function registerSharedLayoutNode(layoutId, node, preserveFollowOpacity) {
4343
+ if (!sharedLayoutRegistry.has(layoutId)) {
4344
+ sharedLayoutRegistry.set(layoutId, new NodeStack());
4345
+ }
4346
+ const stack = sharedLayoutRegistry.get(layoutId);
4347
+ stack.add(node);
4348
+ stack.promote(node, preserveFollowOpacity);
4349
+ }
4350
+ /**
4351
+ * Unregister a projection node from the shared layout registry.
4352
+ * This should be called when the element is removed from the DOM
4353
+ * or when its layout ID changes.
4354
+ *
4355
+ * @param layoutId - The shared layout ID
4356
+ * @param node - The projection node to unregister
4357
+ */
4358
+ function unregisterSharedLayoutNode(layoutId, node) {
4359
+ const stack = sharedLayoutRegistry.get(layoutId);
4360
+ if (!stack)
4361
+ return;
4362
+ stack.remove(node);
4363
+ // Clean up empty stacks
4364
+ if (stack.members.length === 0) {
4365
+ sharedLayoutRegistry.delete(layoutId);
4366
+ }
4367
+ }
4368
+ /**
4369
+ * Get the NodeStack for a shared layout ID.
4370
+ * Useful for checking if a layout ID already has registered nodes.
4371
+ *
4372
+ * @param layoutId - The shared layout ID
4373
+ * @returns The NodeStack for this layout ID, or undefined if not registered
4374
+ */
4375
+ function getSharedLayoutStack(layoutId) {
4376
+ return sharedLayoutRegistry.get(layoutId);
4377
+ }
4378
+ /**
4379
+ * Get the current lead node for a shared layout ID.
4380
+ *
4381
+ * @param layoutId - The shared layout ID
4382
+ * @returns The lead projection node, or undefined if not registered
4383
+ */
4384
+ function getSharedLayoutLead(layoutId) {
4385
+ const stack = sharedLayoutRegistry.get(layoutId);
4386
+ return stack?.lead;
4387
+ }
4388
+ /**
4389
+ * Clear all shared layout registrations.
4390
+ * Mainly useful for testing purposes.
4391
+ */
4392
+ function clearSharedLayoutRegistry() {
4393
+ sharedLayoutRegistry.clear();
4394
+ }
4395
+ /**
4396
+ * Check if a layout ID has any registered nodes.
4397
+ *
4398
+ * @param layoutId - The shared layout ID
4399
+ * @returns True if the layout ID has registered nodes
4400
+ */
4401
+ function hasSharedLayoutNodes(layoutId) {
4402
+ const stack = sharedLayoutRegistry.get(layoutId);
4403
+ return stack !== undefined && stack.members.length > 0;
4404
+ }
4405
+ /**
4406
+ * Trigger exit animation complete callbacks for all nodes in a layout group.
4407
+ *
4408
+ * @param layoutId - The shared layout ID
4409
+ */
4410
+ function notifyExitAnimationComplete(layoutId) {
4411
+ const stack = sharedLayoutRegistry.get(layoutId);
4412
+ if (stack) {
4413
+ stack.exitAnimationComplete();
4414
+ }
4415
+ }
4416
+ /**
4417
+ * Schedule render for all nodes in a shared layout group.
4418
+ *
4419
+ * @param layoutId - The shared layout ID
4420
+ */
4421
+ function scheduleSharedLayoutRender(layoutId) {
4422
+ const stack = sharedLayoutRegistry.get(layoutId);
4423
+ if (stack) {
4424
+ stack.scheduleRender();
4425
+ }
4426
+ }
4427
+
4428
+ /**
4429
+ * Helper to create a LayoutNodeFactory from concrete implementations.
4430
+ * This is designed to be called by framer-motion to provide the concrete
4431
+ * HTMLProjectionNode and HTMLVisualElement classes.
4432
+ */
4433
+ function createLayoutNodeFactory(config) {
4434
+ const { ProjectionNode, VisualElement } = config;
4435
+ return {
4436
+ createProjectionNode(element, parent, options = {}) {
4437
+ const latestValues = {};
4438
+ // Get layoutId from options or data attribute
4439
+ const layoutId = options.layoutId ?? element.dataset?.layoutId ?? undefined;
4440
+ // Create visual element with minimal state
4441
+ const visualElement = new VisualElement({
4442
+ visualState: {
4443
+ latestValues,
4444
+ renderState: {
4445
+ transformOrigin: {},
4446
+ transform: {},
4447
+ style: {},
4448
+ vars: {},
4449
+ },
4450
+ },
4451
+ props: {},
4452
+ });
4453
+ // Create projection node
4454
+ const node = new ProjectionNode(latestValues, parent);
4455
+ // Configure the node
4456
+ node.setOptions({
4457
+ scheduleRender: () => {
4458
+ if (visualElement.scheduleRender) {
4459
+ visualElement.scheduleRender();
4460
+ }
4461
+ },
4462
+ visualElement,
4463
+ layout: true,
4464
+ layoutId,
4465
+ transition: options.transition ?? {
4466
+ duration: options.duration ?? 0.3,
4467
+ ease: options.ease,
4468
+ },
4469
+ });
4470
+ // Mount the node
4471
+ node.mount(element);
4472
+ // Link visual element to projection
4473
+ visualElement.projection = node;
4474
+ // Register with shared layout registry if layoutId is present
4475
+ if (layoutId) {
4476
+ registerSharedLayoutNode(layoutId, node);
4477
+ // Store original unmount for cleanup
4478
+ const originalUnmount = node.unmount?.bind(node);
4479
+ node.unmount = () => {
4480
+ unregisterSharedLayoutNode(layoutId, node);
4481
+ if (originalUnmount) {
4482
+ originalUnmount();
4483
+ }
4484
+ };
4485
+ }
4486
+ // Set up animation listener
4487
+ node.addEventListener("didUpdate", ({ delta, hasLayoutChanged, }) => {
4488
+ if (node.resumeFrom) {
4489
+ node.resumingFrom = node.resumeFrom;
4490
+ if (node.resumingFrom) {
4491
+ node.resumingFrom.resumingFrom = undefined;
4492
+ }
4493
+ }
4494
+ if (hasLayoutChanged) {
4495
+ node.setAnimationOrigin(delta);
4496
+ node.startAnimation(options.transition ?? {
4497
+ duration: options.duration ?? 0.3,
4498
+ ease: options.ease,
4499
+ });
4500
+ }
4501
+ });
4502
+ return node;
4503
+ },
4504
+ createVisualElement(_element, _options = {}) {
4505
+ // This is typically not called directly - visual elements
4506
+ // are created as part of createProjectionNode
4507
+ const latestValues = {};
4508
+ return new VisualElement({
4509
+ visualState: {
4510
+ latestValues,
4511
+ renderState: {
4512
+ transformOrigin: {},
4513
+ transform: {},
4514
+ style: {},
4515
+ vars: {},
4516
+ },
4517
+ },
4518
+ props: {},
4519
+ });
4520
+ },
4521
+ };
4522
+ }
4523
+ /**
4524
+ * Initialize the layout system with framer-motion's implementations.
4525
+ * Call this function once at app initialization to enable animateLayout().
4526
+ *
4527
+ * @example
4528
+ * // In framer-motion or your app initialization
4529
+ * import { HTMLProjectionNode, HTMLVisualElement } from 'framer-motion'
4530
+ * import { initLayoutSystem } from 'motion-dom'
4531
+ *
4532
+ * initLayoutSystem({
4533
+ * ProjectionNode: HTMLProjectionNode,
4534
+ * VisualElement: HTMLVisualElement,
4535
+ * })
4536
+ */
4537
+ function initLayoutSystem(config) {
4538
+ const factory = createLayoutNodeFactory(config);
4539
+ setLayoutNodeFactory(factory);
4540
+ }
4541
+
3737
4542
  const { schedule: microtask, cancel: cancelMicrotask } =
3738
4543
  /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
3739
4544
 
@@ -3981,6 +4786,609 @@ function press(targetOrSelector, onPressStart, options = {}) {
3981
4786
  return cancelEvents;
3982
4787
  }
3983
4788
 
4789
+ const borders = ["TopLeft", "TopRight", "BottomLeft", "BottomRight"];
4790
+ const numBorders = borders.length;
4791
+ const asNumber$1 = (value) => typeof value === "string" ? parseFloat(value) : value;
4792
+ const isPx = (value) => typeof value === "number" || px.test(value);
4793
+ function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {
4794
+ if (shouldCrossfadeOpacity) {
4795
+ target.opacity = mixNumber$1(0, lead.opacity ?? 1, easeCrossfadeIn(progress));
4796
+ target.opacityExit = mixNumber$1(follow.opacity ?? 1, 0, easeCrossfadeOut(progress));
4797
+ }
4798
+ else if (isOnlyMember) {
4799
+ target.opacity = mixNumber$1(follow.opacity ?? 1, lead.opacity ?? 1, progress);
4800
+ }
4801
+ /**
4802
+ * Mix border radius
4803
+ */
4804
+ for (let i = 0; i < numBorders; i++) {
4805
+ const borderLabel = `border${borders[i]}Radius`;
4806
+ let followRadius = getRadius(follow, borderLabel);
4807
+ let leadRadius = getRadius(lead, borderLabel);
4808
+ if (followRadius === undefined && leadRadius === undefined)
4809
+ continue;
4810
+ followRadius || (followRadius = 0);
4811
+ leadRadius || (leadRadius = 0);
4812
+ const canMix = followRadius === 0 ||
4813
+ leadRadius === 0 ||
4814
+ isPx(followRadius) === isPx(leadRadius);
4815
+ if (canMix) {
4816
+ target[borderLabel] = Math.max(mixNumber$1(asNumber$1(followRadius), asNumber$1(leadRadius), progress), 0);
4817
+ if (percent.test(leadRadius) || percent.test(followRadius)) {
4818
+ target[borderLabel] += "%";
4819
+ }
4820
+ }
4821
+ else {
4822
+ target[borderLabel] = leadRadius;
4823
+ }
4824
+ }
4825
+ /**
4826
+ * Mix rotation
4827
+ */
4828
+ if (follow.rotate || lead.rotate) {
4829
+ target.rotate = mixNumber$1(follow.rotate || 0, lead.rotate || 0, progress);
4830
+ }
4831
+ }
4832
+ function getRadius(values, radiusName) {
4833
+ return values[radiusName] !== undefined
4834
+ ? values[radiusName]
4835
+ : values.borderRadius;
4836
+ }
4837
+ const easeCrossfadeIn = /*@__PURE__*/ compress(0, 0.5, motionUtils.circOut);
4838
+ const easeCrossfadeOut = /*@__PURE__*/ compress(0.5, 0.95, motionUtils.noop);
4839
+ function compress(min, max, easing) {
4840
+ return (p) => {
4841
+ // Could replace ifs with clamp
4842
+ if (p < min)
4843
+ return 0;
4844
+ if (p > max)
4845
+ return 1;
4846
+ return easing(motionUtils.progress(min, max, p));
4847
+ };
4848
+ }
4849
+
4850
+ /**
4851
+ * Bounding boxes tend to be defined as top, left, right, bottom. For various operations
4852
+ * it's easier to consider each axis individually. This function returns a bounding box
4853
+ * as a map of single-axis min/max values.
4854
+ */
4855
+ function convertBoundingBoxToBox({ top, left, right, bottom, }) {
4856
+ return {
4857
+ x: { min: left, max: right },
4858
+ y: { min: top, max: bottom },
4859
+ };
4860
+ }
4861
+ function convertBoxToBoundingBox({ x, y }) {
4862
+ return { top: y.min, right: x.max, bottom: y.max, left: x.min };
4863
+ }
4864
+ /**
4865
+ * Applies a TransformPoint function to a bounding box. TransformPoint is usually a function
4866
+ * provided by Framer to allow measured points to be corrected for device scaling. This is used
4867
+ * when measuring DOM elements and DOM event points.
4868
+ */
4869
+ function transformBoxPoints(point, transformPoint) {
4870
+ if (!transformPoint)
4871
+ return point;
4872
+ const topLeft = transformPoint({ x: point.left, y: point.top });
4873
+ const bottomRight = transformPoint({ x: point.right, y: point.bottom });
4874
+ return {
4875
+ top: topLeft.y,
4876
+ left: topLeft.x,
4877
+ bottom: bottomRight.y,
4878
+ right: bottomRight.x,
4879
+ };
4880
+ }
4881
+
4882
+ /**
4883
+ * Reset an axis to the provided origin box.
4884
+ *
4885
+ * This is a mutative operation.
4886
+ */
4887
+ function copyAxisInto(axis, originAxis) {
4888
+ axis.min = originAxis.min;
4889
+ axis.max = originAxis.max;
4890
+ }
4891
+ /**
4892
+ * Reset a box to the provided origin box.
4893
+ *
4894
+ * This is a mutative operation.
4895
+ */
4896
+ function copyBoxInto(box, originBox) {
4897
+ copyAxisInto(box.x, originBox.x);
4898
+ copyAxisInto(box.y, originBox.y);
4899
+ }
4900
+ /**
4901
+ * Reset a delta to the provided origin box.
4902
+ *
4903
+ * This is a mutative operation.
4904
+ */
4905
+ function copyAxisDeltaInto(delta, originDelta) {
4906
+ delta.translate = originDelta.translate;
4907
+ delta.scale = originDelta.scale;
4908
+ delta.originPoint = originDelta.originPoint;
4909
+ delta.origin = originDelta.origin;
4910
+ }
4911
+
4912
+ function isIdentityScale(scale) {
4913
+ return scale === undefined || scale === 1;
4914
+ }
4915
+ function hasScale({ scale, scaleX, scaleY }) {
4916
+ return (!isIdentityScale(scale) ||
4917
+ !isIdentityScale(scaleX) ||
4918
+ !isIdentityScale(scaleY));
4919
+ }
4920
+ function hasTransform(values) {
4921
+ return (hasScale(values) ||
4922
+ has2DTranslate(values) ||
4923
+ values.z ||
4924
+ values.rotate ||
4925
+ values.rotateX ||
4926
+ values.rotateY ||
4927
+ values.skewX ||
4928
+ values.skewY);
4929
+ }
4930
+ function has2DTranslate(values) {
4931
+ return is2DTranslate(values.x) || is2DTranslate(values.y);
4932
+ }
4933
+ function is2DTranslate(value) {
4934
+ return value && value !== "0%";
4935
+ }
4936
+
4937
+ /**
4938
+ * Scales a point based on a factor and an originPoint
4939
+ */
4940
+ function scalePoint(point, scale, originPoint) {
4941
+ const distanceFromOrigin = point - originPoint;
4942
+ const scaled = scale * distanceFromOrigin;
4943
+ return originPoint + scaled;
4944
+ }
4945
+ /**
4946
+ * Applies a translate/scale delta to a point
4947
+ */
4948
+ function applyPointDelta(point, translate, scale, originPoint, boxScale) {
4949
+ if (boxScale !== undefined) {
4950
+ point = scalePoint(point, boxScale, originPoint);
4951
+ }
4952
+ return scalePoint(point, scale, originPoint) + translate;
4953
+ }
4954
+ /**
4955
+ * Applies a translate/scale delta to an axis
4956
+ */
4957
+ function applyAxisDelta(axis, translate = 0, scale = 1, originPoint, boxScale) {
4958
+ axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale);
4959
+ axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale);
4960
+ }
4961
+ /**
4962
+ * Applies a translate/scale delta to a box
4963
+ */
4964
+ function applyBoxDelta(box, { x, y }) {
4965
+ applyAxisDelta(box.x, x.translate, x.scale, x.originPoint);
4966
+ applyAxisDelta(box.y, y.translate, y.scale, y.originPoint);
4967
+ }
4968
+ const TREE_SCALE_SNAP_MIN = 0.999999999999;
4969
+ const TREE_SCALE_SNAP_MAX = 1.0000000000001;
4970
+ /**
4971
+ * Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms
4972
+ * in a tree upon our box before then calculating how to project it into our desired viewport-relative box
4973
+ *
4974
+ * This is the final nested loop within updateLayoutDelta for future refactoring
4975
+ */
4976
+ function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {
4977
+ const treeLength = treePath.length;
4978
+ if (!treeLength)
4979
+ return;
4980
+ // Reset the treeScale
4981
+ treeScale.x = treeScale.y = 1;
4982
+ let node;
4983
+ let delta;
4984
+ for (let i = 0; i < treeLength; i++) {
4985
+ node = treePath[i];
4986
+ delta = node.projectionDelta;
4987
+ /**
4988
+ * TODO: Prefer to remove this, but currently we have motion components with
4989
+ * display: contents in Framer.
4990
+ */
4991
+ const { visualElement } = node.options;
4992
+ if (visualElement &&
4993
+ visualElement.props.style &&
4994
+ visualElement.props.style.display === "contents") {
4995
+ continue;
4996
+ }
4997
+ if (isSharedTransition &&
4998
+ node.options.layoutScroll &&
4999
+ node.scroll &&
5000
+ node !== node.root) {
5001
+ transformBox(box, {
5002
+ x: -node.scroll.offset.x,
5003
+ y: -node.scroll.offset.y,
5004
+ });
5005
+ }
5006
+ if (delta) {
5007
+ // Incoporate each ancestor's scale into a cumulative treeScale for this component
5008
+ treeScale.x *= delta.x.scale;
5009
+ treeScale.y *= delta.y.scale;
5010
+ // Apply each ancestor's calculated delta into this component's recorded layout box
5011
+ applyBoxDelta(box, delta);
5012
+ }
5013
+ if (isSharedTransition && hasTransform(node.latestValues)) {
5014
+ transformBox(box, node.latestValues);
5015
+ }
5016
+ }
5017
+ /**
5018
+ * Snap tree scale back to 1 if it's within a non-perceivable threshold.
5019
+ * This will help reduce useless scales getting rendered.
5020
+ */
5021
+ if (treeScale.x < TREE_SCALE_SNAP_MAX &&
5022
+ treeScale.x > TREE_SCALE_SNAP_MIN) {
5023
+ treeScale.x = 1.0;
5024
+ }
5025
+ if (treeScale.y < TREE_SCALE_SNAP_MAX &&
5026
+ treeScale.y > TREE_SCALE_SNAP_MIN) {
5027
+ treeScale.y = 1.0;
5028
+ }
5029
+ }
5030
+ function translateAxis(axis, distance) {
5031
+ axis.min = axis.min + distance;
5032
+ axis.max = axis.max + distance;
5033
+ }
5034
+ /**
5035
+ * Apply a transform to an axis from the latest resolved motion values.
5036
+ * This function basically acts as a bridge between a flat motion value map
5037
+ * and applyAxisDelta
5038
+ */
5039
+ function transformAxis(axis, axisTranslate, axisScale, boxScale, axisOrigin = 0.5) {
5040
+ const originPoint = mixNumber$1(axis.min, axis.max, axisOrigin);
5041
+ // Apply the axis delta to the final axis
5042
+ applyAxisDelta(axis, axisTranslate, axisScale, originPoint, boxScale);
5043
+ }
5044
+ /**
5045
+ * Apply a transform to a box from the latest resolved motion values.
5046
+ */
5047
+ function transformBox(box, transform) {
5048
+ transformAxis(box.x, transform.x, transform.scaleX, transform.scale, transform.originX);
5049
+ transformAxis(box.y, transform.y, transform.scaleY, transform.scale, transform.originY);
5050
+ }
5051
+
5052
+ const SCALE_PRECISION = 0.0001;
5053
+ const SCALE_MIN = 1 - SCALE_PRECISION;
5054
+ const SCALE_MAX = 1 + SCALE_PRECISION;
5055
+ const TRANSLATE_PRECISION = 0.01;
5056
+ const TRANSLATE_MIN = 0 - TRANSLATE_PRECISION;
5057
+ const TRANSLATE_MAX = 0 + TRANSLATE_PRECISION;
5058
+ function calcLength(axis) {
5059
+ return axis.max - axis.min;
5060
+ }
5061
+ function isNear(value, target, maxDistance) {
5062
+ return Math.abs(value - target) <= maxDistance;
5063
+ }
5064
+ function calcAxisDelta(delta, source, target, origin = 0.5) {
5065
+ delta.origin = origin;
5066
+ delta.originPoint = mixNumber$1(source.min, source.max, delta.origin);
5067
+ delta.scale = calcLength(target) / calcLength(source);
5068
+ delta.translate =
5069
+ mixNumber$1(target.min, target.max, delta.origin) - delta.originPoint;
5070
+ if ((delta.scale >= SCALE_MIN && delta.scale <= SCALE_MAX) ||
5071
+ isNaN(delta.scale)) {
5072
+ delta.scale = 1.0;
5073
+ }
5074
+ if ((delta.translate >= TRANSLATE_MIN &&
5075
+ delta.translate <= TRANSLATE_MAX) ||
5076
+ isNaN(delta.translate)) {
5077
+ delta.translate = 0.0;
5078
+ }
5079
+ }
5080
+ function calcBoxDelta(delta, source, target, origin) {
5081
+ calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : undefined);
5082
+ calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : undefined);
5083
+ }
5084
+ function calcRelativeAxis(target, relative, parent) {
5085
+ target.min = parent.min + relative.min;
5086
+ target.max = target.min + calcLength(relative);
5087
+ }
5088
+ function calcRelativeBox(target, relative, parent) {
5089
+ calcRelativeAxis(target.x, relative.x, parent.x);
5090
+ calcRelativeAxis(target.y, relative.y, parent.y);
5091
+ }
5092
+ function calcRelativeAxisPosition(target, layout, parent) {
5093
+ target.min = layout.min - parent.min;
5094
+ target.max = target.min + calcLength(layout);
5095
+ }
5096
+ function calcRelativePosition(target, layout, parent) {
5097
+ calcRelativeAxisPosition(target.x, layout.x, parent.x);
5098
+ calcRelativeAxisPosition(target.y, layout.y, parent.y);
5099
+ }
5100
+
5101
+ /**
5102
+ * Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse
5103
+ */
5104
+ function removePointDelta(point, translate, scale, originPoint, boxScale) {
5105
+ point -= translate;
5106
+ point = scalePoint(point, 1 / scale, originPoint);
5107
+ if (boxScale !== undefined) {
5108
+ point = scalePoint(point, 1 / boxScale, originPoint);
5109
+ }
5110
+ return point;
5111
+ }
5112
+ /**
5113
+ * Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse
5114
+ */
5115
+ function removeAxisDelta(axis, translate = 0, scale = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) {
5116
+ if (percent.test(translate)) {
5117
+ translate = parseFloat(translate);
5118
+ const relativeProgress = mixNumber$1(sourceAxis.min, sourceAxis.max, translate / 100);
5119
+ translate = relativeProgress - sourceAxis.min;
5120
+ }
5121
+ if (typeof translate !== "number")
5122
+ return;
5123
+ let originPoint = mixNumber$1(originAxis.min, originAxis.max, origin);
5124
+ if (axis === originAxis)
5125
+ originPoint -= translate;
5126
+ axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale);
5127
+ axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale);
5128
+ }
5129
+ /**
5130
+ * Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse
5131
+ * and acts as a bridge between motion values and removeAxisDelta
5132
+ */
5133
+ function removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) {
5134
+ removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis);
5135
+ }
5136
+ /**
5137
+ * The names of the motion values we want to apply as translation, scale and origin.
5138
+ */
5139
+ const xKeys = ["x", "scaleX", "originX"];
5140
+ const yKeys = ["y", "scaleY", "originY"];
5141
+ /**
5142
+ * Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse
5143
+ * and acts as a bridge between motion values and removeAxisDelta
5144
+ */
5145
+ function removeBoxTransforms(box, transforms, originBox, sourceBox) {
5146
+ removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : undefined, sourceBox ? sourceBox.x : undefined);
5147
+ removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : undefined, sourceBox ? sourceBox.y : undefined);
5148
+ }
5149
+
5150
+ const createAxisDelta = () => ({
5151
+ translate: 0,
5152
+ scale: 1,
5153
+ origin: 0,
5154
+ originPoint: 0,
5155
+ });
5156
+ const createDelta = () => ({
5157
+ x: createAxisDelta(),
5158
+ y: createAxisDelta(),
5159
+ });
5160
+ const createAxis = () => ({ min: 0, max: 0 });
5161
+ const createBox = () => ({
5162
+ x: createAxis(),
5163
+ y: createAxis(),
5164
+ });
5165
+
5166
+ function isAxisDeltaZero(delta) {
5167
+ return delta.translate === 0 && delta.scale === 1;
5168
+ }
5169
+ function isDeltaZero(delta) {
5170
+ return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y);
5171
+ }
5172
+ function axisEquals(a, b) {
5173
+ return a.min === b.min && a.max === b.max;
5174
+ }
5175
+ function boxEquals(a, b) {
5176
+ return axisEquals(a.x, b.x) && axisEquals(a.y, b.y);
5177
+ }
5178
+ function axisEqualsRounded(a, b) {
5179
+ return (Math.round(a.min) === Math.round(b.min) &&
5180
+ Math.round(a.max) === Math.round(b.max));
5181
+ }
5182
+ function boxEqualsRounded(a, b) {
5183
+ return axisEqualsRounded(a.x, b.x) && axisEqualsRounded(a.y, b.y);
5184
+ }
5185
+ function aspectRatio(box) {
5186
+ return calcLength(box.x) / calcLength(box.y);
5187
+ }
5188
+ function axisDeltaEquals(a, b) {
5189
+ return (a.translate === b.translate &&
5190
+ a.scale === b.scale &&
5191
+ a.originPoint === b.originPoint);
5192
+ }
5193
+
5194
+ /**
5195
+ * This should only ever be modified on the client otherwise it'll
5196
+ * persist through server requests. If we need instanced states we
5197
+ * could lazy-init via root.
5198
+ */
5199
+ const globalProjectionState = {
5200
+ /**
5201
+ * Global flag as to whether the tree has animated since the last time
5202
+ * we resized the window
5203
+ */
5204
+ hasAnimatedSinceResize: true,
5205
+ /**
5206
+ * We set this to true once, on the first update. Any nodes added to the tree beyond that
5207
+ * update will be given a `data-projection-id` attribute.
5208
+ */
5209
+ hasEverUpdated: false,
5210
+ };
5211
+
5212
+ function pixelsToPercent(pixels, axis) {
5213
+ if (axis.max === axis.min)
5214
+ return 0;
5215
+ return (pixels / (axis.max - axis.min)) * 100;
5216
+ }
5217
+ /**
5218
+ * We always correct borderRadius as a percentage rather than pixels to reduce paints.
5219
+ * For example, if you are projecting a box that is 100px wide with a 10px borderRadius
5220
+ * into a box that is 200px wide with a 20px borderRadius, that is actually a 10%
5221
+ * borderRadius in both states. If we animate between the two in pixels that will trigger
5222
+ * a paint each time. If we animate between the two in percentage we'll avoid a paint.
5223
+ */
5224
+ const correctBorderRadius = {
5225
+ correct: (latest, node) => {
5226
+ if (!node.target)
5227
+ return latest;
5228
+ /**
5229
+ * If latest is a string, if it's a percentage we can return immediately as it's
5230
+ * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.
5231
+ */
5232
+ if (typeof latest === "string") {
5233
+ if (px.test(latest)) {
5234
+ latest = parseFloat(latest);
5235
+ }
5236
+ else {
5237
+ return latest;
5238
+ }
5239
+ }
5240
+ /**
5241
+ * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that
5242
+ * pixel value as a percentage of each axis
5243
+ */
5244
+ const x = pixelsToPercent(latest, node.target.x);
5245
+ const y = pixelsToPercent(latest, node.target.y);
5246
+ return `${x}% ${y}%`;
5247
+ },
5248
+ };
5249
+
5250
+ const correctBoxShadow = {
5251
+ correct: (latest, { treeScale, projectionDelta }) => {
5252
+ const original = latest;
5253
+ const shadow = complex.parse(latest);
5254
+ // TODO: Doesn't support multiple shadows
5255
+ if (shadow.length > 5)
5256
+ return original;
5257
+ const template = complex.createTransformer(latest);
5258
+ const offset = typeof shadow[0] !== "number" ? 1 : 0;
5259
+ // Calculate the overall context scale
5260
+ const xScale = projectionDelta.x.scale * treeScale.x;
5261
+ const yScale = projectionDelta.y.scale * treeScale.y;
5262
+ shadow[0 + offset] /= xScale;
5263
+ shadow[1 + offset] /= yScale;
5264
+ /**
5265
+ * Ideally we'd correct x and y scales individually, but because blur and
5266
+ * spread apply to both we have to take a scale average and apply that instead.
5267
+ * We could potentially improve the outcome of this by incorporating the ratio between
5268
+ * the two scales.
5269
+ */
5270
+ const averageScale = mixNumber$1(xScale, yScale, 0.5);
5271
+ // Blur
5272
+ if (typeof shadow[2 + offset] === "number")
5273
+ shadow[2 + offset] /= averageScale;
5274
+ // Spread
5275
+ if (typeof shadow[3 + offset] === "number")
5276
+ shadow[3 + offset] /= averageScale;
5277
+ return template(shadow);
5278
+ },
5279
+ };
5280
+
5281
+ const scaleCorrectors = {
5282
+ borderRadius: {
5283
+ ...correctBorderRadius,
5284
+ applyTo: [
5285
+ "borderTopLeftRadius",
5286
+ "borderTopRightRadius",
5287
+ "borderBottomLeftRadius",
5288
+ "borderBottomRightRadius",
5289
+ ],
5290
+ },
5291
+ borderTopLeftRadius: correctBorderRadius,
5292
+ borderTopRightRadius: correctBorderRadius,
5293
+ borderBottomLeftRadius: correctBorderRadius,
5294
+ borderBottomRightRadius: correctBorderRadius,
5295
+ boxShadow: correctBoxShadow,
5296
+ };
5297
+ function addScaleCorrector(correctors) {
5298
+ for (const key in correctors) {
5299
+ scaleCorrectors[key] = correctors[key];
5300
+ if (isCSSVariableName(key)) {
5301
+ scaleCorrectors[key].isCSSVariable = true;
5302
+ }
5303
+ }
5304
+ }
5305
+
5306
+ function buildProjectionTransform(delta, treeScale, latestTransform) {
5307
+ let transform = "";
5308
+ /**
5309
+ * The translations we use to calculate are always relative to the viewport coordinate space.
5310
+ * But when we apply scales, we also scale the coordinate space of an element and its children.
5311
+ * For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need
5312
+ * to move an element 100 pixels, we actually need to move it 200 in within that scaled space.
5313
+ */
5314
+ const xTranslate = delta.x.translate / treeScale.x;
5315
+ const yTranslate = delta.y.translate / treeScale.y;
5316
+ const zTranslate = latestTransform?.z || 0;
5317
+ if (xTranslate || yTranslate || zTranslate) {
5318
+ transform = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `;
5319
+ }
5320
+ /**
5321
+ * Apply scale correction for the tree transform.
5322
+ * This will apply scale to the screen-orientated axes.
5323
+ */
5324
+ if (treeScale.x !== 1 || treeScale.y !== 1) {
5325
+ transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
5326
+ }
5327
+ if (latestTransform) {
5328
+ const { transformPerspective, rotate, rotateX, rotateY, skewX, skewY } = latestTransform;
5329
+ if (transformPerspective)
5330
+ transform = `perspective(${transformPerspective}px) ${transform}`;
5331
+ if (rotate)
5332
+ transform += `rotate(${rotate}deg) `;
5333
+ if (rotateX)
5334
+ transform += `rotateX(${rotateX}deg) `;
5335
+ if (rotateY)
5336
+ transform += `rotateY(${rotateY}deg) `;
5337
+ if (skewX)
5338
+ transform += `skewX(${skewX}deg) `;
5339
+ if (skewY)
5340
+ transform += `skewY(${skewY}deg) `;
5341
+ }
5342
+ /**
5343
+ * Apply scale to match the size of the element to the size we want it.
5344
+ * This will apply scale to the element-orientated axes.
5345
+ */
5346
+ const elementScaleX = delta.x.scale * treeScale.x;
5347
+ const elementScaleY = delta.y.scale * treeScale.y;
5348
+ if (elementScaleX !== 1 || elementScaleY !== 1) {
5349
+ transform += `scale(${elementScaleX}, ${elementScaleY})`;
5350
+ }
5351
+ return transform || "none";
5352
+ }
5353
+
5354
+ function eachAxis(callback) {
5355
+ return [callback("x"), callback("y")];
5356
+ }
5357
+
5358
+ function measureViewportBox(instance, transformPoint) {
5359
+ return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint));
5360
+ }
5361
+ function measurePageBox(element, rootProjectionNode, transformPagePoint) {
5362
+ const viewportBox = measureViewportBox(element, transformPagePoint);
5363
+ const { scroll } = rootProjectionNode;
5364
+ if (scroll) {
5365
+ translateAxis(viewportBox.x, scroll.offset.x);
5366
+ translateAxis(viewportBox.y, scroll.offset.y);
5367
+ }
5368
+ return viewportBox;
5369
+ }
5370
+
5371
+ const compareByDepth = (a, b) => a.depth - b.depth;
5372
+ class FlatTree {
5373
+ constructor() {
5374
+ this.children = [];
5375
+ this.isDirty = false;
5376
+ }
5377
+ add(child) {
5378
+ motionUtils.addUniqueItem(this.children, child);
5379
+ this.isDirty = true;
5380
+ }
5381
+ remove(child) {
5382
+ motionUtils.removeItem(this.children, child);
5383
+ this.isDirty = true;
5384
+ }
5385
+ forEach(callback) {
5386
+ this.isDirty && this.children.sort(compareByDepth);
5387
+ this.isDirty = false;
5388
+ this.children.forEach(callback);
5389
+ }
5390
+ }
5391
+
3984
5392
  function getComputedStyle$1(element, name) {
3985
5393
  const computedStyle = window.getComputedStyle(element);
3986
5394
  return isCSSVar(name)
@@ -4216,6 +5624,25 @@ function recordStats() {
4216
5624
  return reportStats;
4217
5625
  }
4218
5626
 
5627
+ /**
5628
+ * Timeout defined in ms
5629
+ */
5630
+ function delay(callback, timeout) {
5631
+ const start = time.now();
5632
+ const checkElapsed = ({ timestamp }) => {
5633
+ const elapsed = timestamp - start;
5634
+ if (elapsed >= timeout) {
5635
+ cancelFrame(checkElapsed);
5636
+ callback(elapsed - timeout);
5637
+ }
5638
+ };
5639
+ frame.setup(checkElapsed, true);
5640
+ return () => cancelFrame(checkElapsed);
5641
+ }
5642
+ function delayInSeconds(callback, timeout) {
5643
+ return delay(callback, motionUtils.secondsToMilliseconds(timeout));
5644
+ }
5645
+
4219
5646
  /**
4220
5647
  * Checks if an element is specifically an SVGSVGElement (the root SVG element)
4221
5648
  * in a way that works across iframes
@@ -4755,6 +6182,7 @@ const cancelSync = stepsOrder.reduce((acc, key) => {
4755
6182
 
4756
6183
  exports.AsyncMotionValueAnimation = AsyncMotionValueAnimation;
4757
6184
  exports.DOMKeyframesResolver = DOMKeyframesResolver;
6185
+ exports.FlatTree = FlatTree;
4758
6186
  exports.GroupAnimation = GroupAnimation;
4759
6187
  exports.GroupAnimationWithThen = GroupAnimationWithThen;
4760
6188
  exports.JSAnimation = JSAnimation;
@@ -4763,30 +6191,64 @@ exports.MotionValue = MotionValue;
4763
6191
  exports.NativeAnimation = NativeAnimation;
4764
6192
  exports.NativeAnimationExtended = NativeAnimationExtended;
4765
6193
  exports.NativeAnimationWrapper = NativeAnimationWrapper;
6194
+ exports.NodeStack = NodeStack;
4766
6195
  exports.ViewTransitionBuilder = ViewTransitionBuilder;
4767
6196
  exports.acceleratedValues = acceleratedValues;
4768
6197
  exports.activeAnimations = activeAnimations;
4769
6198
  exports.addAttrValue = addAttrValue;
6199
+ exports.addScaleCorrector = addScaleCorrector;
4770
6200
  exports.addStyleValue = addStyleValue;
4771
6201
  exports.alpha = alpha;
4772
6202
  exports.analyseComplexValue = analyseComplexValue;
4773
6203
  exports.animateValue = animateValue;
4774
6204
  exports.animateView = animateView;
4775
6205
  exports.animationMapKey = animationMapKey;
6206
+ exports.applyAxisDelta = applyAxisDelta;
6207
+ exports.applyBoxDelta = applyBoxDelta;
4776
6208
  exports.applyGeneratorOptions = applyGeneratorOptions;
6209
+ exports.applyPointDelta = applyPointDelta;
4777
6210
  exports.applyPxDefaults = applyPxDefaults;
6211
+ exports.applyTreeDeltas = applyTreeDeltas;
6212
+ exports.aspectRatio = aspectRatio;
4778
6213
  exports.attachSpring = attachSpring;
4779
6214
  exports.attrEffect = attrEffect;
6215
+ exports.axisDeltaEquals = axisDeltaEquals;
6216
+ exports.axisEquals = axisEquals;
6217
+ exports.axisEqualsRounded = axisEqualsRounded;
6218
+ exports.boxEquals = boxEquals;
6219
+ exports.boxEqualsRounded = boxEqualsRounded;
6220
+ exports.buildProjectionTransform = buildProjectionTransform;
6221
+ exports.calcAxisDelta = calcAxisDelta;
6222
+ exports.calcBoxDelta = calcBoxDelta;
4780
6223
  exports.calcGeneratorDuration = calcGeneratorDuration;
6224
+ exports.calcLength = calcLength;
6225
+ exports.calcRelativeAxis = calcRelativeAxis;
6226
+ exports.calcRelativeAxisPosition = calcRelativeAxisPosition;
6227
+ exports.calcRelativeBox = calcRelativeBox;
6228
+ exports.calcRelativePosition = calcRelativePosition;
4781
6229
  exports.cancelFrame = cancelFrame;
4782
6230
  exports.cancelMicrotask = cancelMicrotask;
4783
6231
  exports.cancelSync = cancelSync;
6232
+ exports.clearSharedLayoutRegistry = clearSharedLayoutRegistry;
4784
6233
  exports.collectMotionValues = collectMotionValues;
4785
6234
  exports.color = color;
6235
+ exports.compareByDepth = compareByDepth;
4786
6236
  exports.complex = complex;
4787
6237
  exports.containsCSSVariable = containsCSSVariable;
6238
+ exports.convertBoundingBoxToBox = convertBoundingBoxToBox;
6239
+ exports.convertBoxToBoundingBox = convertBoxToBoundingBox;
4788
6240
  exports.convertOffsetToTimes = convertOffsetToTimes;
6241
+ exports.copyAxisDeltaInto = copyAxisDeltaInto;
6242
+ exports.copyAxisInto = copyAxisInto;
6243
+ exports.copyBoxInto = copyBoxInto;
6244
+ exports.correctBorderRadius = correctBorderRadius;
6245
+ exports.correctBoxShadow = correctBoxShadow;
6246
+ exports.createAxis = createAxis;
6247
+ exports.createAxisDelta = createAxisDelta;
6248
+ exports.createBox = createBox;
6249
+ exports.createDelta = createDelta;
4789
6250
  exports.createGeneratorEasing = createGeneratorEasing;
6251
+ exports.createLayoutNodeFactory = createLayoutNodeFactory;
4790
6252
  exports.createRenderBatcher = createRenderBatcher;
4791
6253
  exports.cubicBezierAsString = cubicBezierAsString;
4792
6254
  exports.defaultEasing = defaultEasing;
@@ -4794,9 +6256,13 @@ exports.defaultOffset = defaultOffset;
4794
6256
  exports.defaultTransformValue = defaultTransformValue;
4795
6257
  exports.defaultValueTypes = defaultValueTypes;
4796
6258
  exports.degrees = degrees;
6259
+ exports.delay = delay;
6260
+ exports.delayInSeconds = delayInSeconds;
4797
6261
  exports.dimensionValueTypes = dimensionValueTypes;
6262
+ exports.eachAxis = eachAxis;
4798
6263
  exports.fillOffset = fillOffset;
4799
6264
  exports.fillWildcards = fillWildcards;
6265
+ exports.findCommonAncestor = findCommonAncestor;
4800
6266
  exports.findDimensionValueType = findDimensionValueType;
4801
6267
  exports.findValueType = findValueType;
4802
6268
  exports.flushKeyframeResolvers = flushKeyframeResolvers;
@@ -4808,28 +6274,39 @@ exports.getAnimatableNone = getAnimatableNone;
4808
6274
  exports.getAnimationMap = getAnimationMap;
4809
6275
  exports.getComputedStyle = getComputedStyle$1;
4810
6276
  exports.getDefaultValueType = getDefaultValueType;
6277
+ exports.getLayoutNodeFactory = getLayoutNodeFactory;
4811
6278
  exports.getMixer = getMixer;
4812
6279
  exports.getOriginIndex = getOriginIndex;
6280
+ exports.getSharedLayoutLead = getSharedLayoutLead;
6281
+ exports.getSharedLayoutStack = getSharedLayoutStack;
4813
6282
  exports.getValueAsType = getValueAsType;
4814
6283
  exports.getValueTransition = getValueTransition;
4815
6284
  exports.getVariableValue = getVariableValue;
4816
6285
  exports.getViewAnimationLayerInfo = getViewAnimationLayerInfo;
4817
6286
  exports.getViewAnimations = getViewAnimations;
6287
+ exports.globalProjectionState = globalProjectionState;
6288
+ exports.has2DTranslate = has2DTranslate;
6289
+ exports.hasScale = hasScale;
6290
+ exports.hasSharedLayoutNodes = hasSharedLayoutNodes;
6291
+ exports.hasTransform = hasTransform;
4818
6292
  exports.hex = hex;
4819
6293
  exports.hover = hover;
4820
6294
  exports.hsla = hsla;
4821
6295
  exports.hslaToRgba = hslaToRgba;
4822
6296
  exports.inertia = inertia;
6297
+ exports.initLayoutSystem = initLayoutSystem;
4823
6298
  exports.interpolate = interpolate;
4824
6299
  exports.invisibleValues = invisibleValues;
4825
6300
  exports.isCSSVariableName = isCSSVariableName;
4826
6301
  exports.isCSSVariableToken = isCSSVariableToken;
6302
+ exports.isDeltaZero = isDeltaZero;
4827
6303
  exports.isDragActive = isDragActive;
4828
6304
  exports.isDragging = isDragging;
4829
6305
  exports.isElementKeyboardAccessible = isElementKeyboardAccessible;
4830
6306
  exports.isGenerator = isGenerator;
4831
6307
  exports.isHTMLElement = isHTMLElement;
4832
6308
  exports.isMotionValue = isMotionValue;
6309
+ exports.isNear = isNear;
4833
6310
  exports.isNodeOrChild = isNodeOrChild;
4834
6311
  exports.isPrimaryPointer = isPrimaryPointer;
4835
6312
  exports.isSVGElement = isSVGElement;
@@ -4840,6 +6317,8 @@ exports.makeAnimationInstant = makeAnimationInstant;
4840
6317
  exports.mapEasingToNativeEasing = mapEasingToNativeEasing;
4841
6318
  exports.mapValue = mapValue;
4842
6319
  exports.maxGeneratorDuration = maxGeneratorDuration;
6320
+ exports.measurePageBox = measurePageBox;
6321
+ exports.measureViewportBox = measureViewportBox;
4843
6322
  exports.microtask = microtask;
4844
6323
  exports.mix = mix;
4845
6324
  exports.mixArray = mixArray;
@@ -4849,27 +6328,41 @@ exports.mixImmediate = mixImmediate;
4849
6328
  exports.mixLinearColor = mixLinearColor;
4850
6329
  exports.mixNumber = mixNumber$1;
4851
6330
  exports.mixObject = mixObject;
6331
+ exports.mixValues = mixValues;
4852
6332
  exports.mixVisibility = mixVisibility;
4853
6333
  exports.motionValue = motionValue;
6334
+ exports.notifyExitAnimationComplete = notifyExitAnimationComplete;
4854
6335
  exports.number = number;
4855
6336
  exports.numberValueTypes = numberValueTypes;
6337
+ exports.observeMutation = observeMutation;
4856
6338
  exports.observeTimeline = observeTimeline;
4857
6339
  exports.parseCSSVariable = parseCSSVariable;
4858
6340
  exports.parseValueFromTransform = parseValueFromTransform;
4859
6341
  exports.percent = percent;
6342
+ exports.pixelsToPercent = pixelsToPercent;
4860
6343
  exports.positionalKeys = positionalKeys;
6344
+ exports.preserveElementForExit = preserveElementForExit;
4861
6345
  exports.press = press;
4862
6346
  exports.progressPercentage = progressPercentage;
4863
6347
  exports.propEffect = propEffect;
4864
6348
  exports.px = px;
4865
6349
  exports.readTransformValue = readTransformValue;
4866
6350
  exports.recordStats = recordStats;
6351
+ exports.registerSharedLayoutNode = registerSharedLayoutNode;
6352
+ exports.removeAxisDelta = removeAxisDelta;
6353
+ exports.removeAxisTransforms = removeAxisTransforms;
6354
+ exports.removeBoxTransforms = removeBoxTransforms;
6355
+ exports.removePointDelta = removePointDelta;
4867
6356
  exports.resize = resize;
4868
6357
  exports.resolveElements = resolveElements;
4869
6358
  exports.rgbUnit = rgbUnit;
4870
6359
  exports.rgba = rgba;
4871
6360
  exports.scale = scale;
6361
+ exports.scaleCorrectors = scaleCorrectors;
6362
+ exports.scalePoint = scalePoint;
6363
+ exports.scheduleSharedLayoutRender = scheduleSharedLayoutRender;
4872
6364
  exports.setDragLock = setDragLock;
6365
+ exports.setLayoutNodeFactory = setLayoutNodeFactory;
4873
6366
  exports.setStyle = setStyle;
4874
6367
  exports.spring = spring;
4875
6368
  exports.springValue = springValue;
@@ -4888,9 +6381,15 @@ exports.sync = sync;
4888
6381
  exports.testValueType = testValueType;
4889
6382
  exports.time = time;
4890
6383
  exports.transform = transform;
6384
+ exports.transformAxis = transformAxis;
6385
+ exports.transformBox = transformBox;
6386
+ exports.transformBoxPoints = transformBoxPoints;
4891
6387
  exports.transformPropOrder = transformPropOrder;
4892
6388
  exports.transformProps = transformProps;
4893
6389
  exports.transformValue = transformValue;
4894
6390
  exports.transformValueTypes = transformValueTypes;
6391
+ exports.translateAxis = translateAxis;
6392
+ exports.unregisterSharedLayoutNode = unregisterSharedLayoutNode;
6393
+ exports.unstable_animateLayout = animateLayout;
4895
6394
  exports.vh = vh;
4896
6395
  exports.vw = vw;