motion-dom 12.40.0 → 12.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/cjs/index.js +1023 -458
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/es/animation/JSAnimation.mjs +0 -3
  4. package/dist/es/animation/JSAnimation.mjs.map +1 -1
  5. package/dist/es/animation/waapi/start-waapi-animation.mjs +1 -12
  6. package/dist/es/animation/waapi/start-waapi-animation.mjs.map +1 -1
  7. package/dist/es/events/add-dom-event.mjs +1 -1
  8. package/dist/es/events/add-dom-event.mjs.map +1 -1
  9. package/dist/es/frameloop/batcher.mjs +1 -1
  10. package/dist/es/frameloop/batcher.mjs.map +1 -1
  11. package/dist/es/frameloop/render-step.mjs +1 -12
  12. package/dist/es/frameloop/render-step.mjs.map +1 -1
  13. package/dist/es/gestures/press/index.mjs +11 -4
  14. package/dist/es/gestures/press/index.mjs.map +1 -1
  15. package/dist/es/index.mjs +0 -1
  16. package/dist/es/index.mjs.map +1 -1
  17. package/dist/es/layout/LayoutAnimationBuilder.mjs +299 -214
  18. package/dist/es/layout/LayoutAnimationBuilder.mjs.map +1 -1
  19. package/dist/es/projection/node/create-projection-node.mjs +0 -6
  20. package/dist/es/projection/node/create-projection-node.mjs.map +1 -1
  21. package/dist/es/stats/buffer.mjs.map +1 -1
  22. package/dist/es/stats/index.mjs +4 -93
  23. package/dist/es/stats/index.mjs.map +1 -1
  24. package/dist/es/view/index.mjs +90 -13
  25. package/dist/es/view/index.mjs.map +1 -1
  26. package/dist/es/view/queue.mjs +9 -3
  27. package/dist/es/view/queue.mjs.map +1 -1
  28. package/dist/es/view/start.mjs +484 -83
  29. package/dist/es/view/start.mjs.map +1 -1
  30. package/dist/es/view/utils/assign-names.mjs +118 -0
  31. package/dist/es/view/utils/assign-names.mjs.map +1 -0
  32. package/dist/es/view/utils/choose-layer-type.mjs +1 -3
  33. package/dist/es/view/utils/choose-layer-type.mjs.map +1 -1
  34. package/dist/es/view/utils/get-layer-info.mjs +3 -1
  35. package/dist/es/view/utils/get-layer-info.mjs.map +1 -1
  36. package/dist/es/view/utils/get-view-animations.mjs +6 -8
  37. package/dist/es/view/utils/get-view-animations.mjs.map +1 -1
  38. package/dist/index.d.ts +105 -52
  39. package/dist/motion-dom.dev.js +1023 -458
  40. package/dist/motion-dom.js +1 -1
  41. package/dist/size-rollup-motion-value.js.map +1 -1
  42. package/dist/size-rollup-style-effect.js.map +1 -1
  43. package/package.json +2 -2
  44. package/dist/es/stats/animation-count.mjs +0 -8
  45. package/dist/es/stats/animation-count.mjs.map +0 -1
package/dist/cjs/index.js CHANGED
@@ -15,12 +15,7 @@ const stepsOrder = [
15
15
  "postRender", // Compute
16
16
  ];
17
17
 
18
- const statsBuffer = {
19
- value: null,
20
- addProjectionMetrics: null,
21
- };
22
-
23
- function createRenderStep(runNextFrame, stepName) {
18
+ function createRenderStep(runNextFrame) {
24
19
  /**
25
20
  * We create and reuse two queues, one to queue jobs for the current frame
26
21
  * and one for the next. We reuse to avoid triggering GC after x frames.
@@ -42,13 +37,11 @@ function createRenderStep(runNextFrame, stepName) {
42
37
  timestamp: 0.0,
43
38
  isProcessing: false,
44
39
  };
45
- let numCalls = 0;
46
40
  function triggerCallback(callback) {
47
41
  if (toKeepAlive.has(callback)) {
48
42
  step.schedule(callback);
49
43
  runNextFrame();
50
44
  }
51
- numCalls++;
52
45
  callback(latestFrameData);
53
46
  }
54
47
  const step = {
@@ -91,13 +84,6 @@ function createRenderStep(runNextFrame, stepName) {
91
84
  nextFrame = prevFrame;
92
85
  // Execute this frame
93
86
  thisFrame.forEach(triggerCallback);
94
- /**
95
- * If we're recording stats then
96
- */
97
- if (stepName && statsBuffer.value) {
98
- statsBuffer.value.frameloop[stepName].push(numCalls);
99
- }
100
- numCalls = 0;
101
87
  // Clear the frame so no callbacks remain. This is to avoid
102
88
  // memory leaks should this render step not run for a while.
103
89
  thisFrame.clear();
@@ -122,7 +108,7 @@ function createRenderBatcher(scheduleNextBatch, allowKeepAlive) {
122
108
  };
123
109
  const flagRunNextFrame = () => (runNextFrame = true);
124
110
  const steps = stepsOrder.reduce((acc, key) => {
125
- acc[key] = createRenderStep(flagRunNextFrame, allowKeepAlive ? key : undefined);
111
+ acc[key] = createRenderStep(flagRunNextFrame);
126
112
  return acc;
127
113
  }, {});
128
114
  const { setup, read, resolveKeyframes, preUpdate, update, preRender, render, postRender, } = steps;
@@ -207,12 +193,6 @@ const time = {
207
193
  },
208
194
  };
209
195
 
210
- const activeAnimations = {
211
- layout: 0,
212
- mainThread: 0,
213
- waapi: 0,
214
- };
215
-
216
196
  const checkStringStartsWith = (token) => (key) => typeof key === "string" && key.startsWith(token);
217
197
  const isCSSVariableName =
218
198
  /*@__PURE__*/ checkStringStartsWith("--");
@@ -1414,7 +1394,6 @@ class JSAnimation extends WithPromise {
1414
1394
  this.teardown();
1415
1395
  this.options.onStop?.();
1416
1396
  };
1417
- activeAnimations.mainThread++;
1418
1397
  this.options = options;
1419
1398
  this.initAnimation();
1420
1399
  this.play();
@@ -1720,7 +1699,6 @@ class JSAnimation extends WithPromise {
1720
1699
  this.state = "idle";
1721
1700
  this.stopDriver();
1722
1701
  this.startTime = this.holdTime = null;
1723
- activeAnimations.mainThread--;
1724
1702
  }
1725
1703
  stopDriver() {
1726
1704
  if (!this.driver)
@@ -2132,9 +2110,6 @@ function startWaapiAnimation(element, valueName, keyframes, { delay = 0, duratio
2132
2110
  */
2133
2111
  if (Array.isArray(easing))
2134
2112
  keyframeOptions.easing = easing;
2135
- if (statsBuffer.value) {
2136
- activeAnimations.waapi++;
2137
- }
2138
2113
  const options = {
2139
2114
  delay,
2140
2115
  duration,
@@ -2145,13 +2120,7 @@ function startWaapiAnimation(element, valueName, keyframes, { delay = 0, duratio
2145
2120
  };
2146
2121
  if (pseudoElement)
2147
2122
  options.pseudoElement = pseudoElement;
2148
- const animation = element.animate(keyframeOptions, options);
2149
- if (statsBuffer.value) {
2150
- animation.finished.finally(() => {
2151
- activeAnimations.waapi--;
2152
- });
2153
- }
2154
- return animation;
2123
+ return element.animate(keyframeOptions, options);
2155
2124
  }
2156
2125
 
2157
2126
  function isGenerator(type) {
@@ -4861,9 +4830,16 @@ function press(targetOrSelector, onPressStart, options = {}) {
4861
4830
  claimedPointerDownEvents.add(startEvent);
4862
4831
  }
4863
4832
  const onPressEnd = onPressStart(target, startEvent);
4833
+ /**
4834
+ * End listeners run in the capture phase so a descendant calling
4835
+ * stopPropagation() in its own pointerup handler can't prevent the
4836
+ * press gesture from ending. This also keeps the gesture-end
4837
+ * ordering consistent with the drag gesture. See #2794.
4838
+ */
4839
+ const endEventOptions = { ...eventOptions, capture: true };
4864
4840
  const onPointerEnd = (endEvent, success) => {
4865
- window.removeEventListener("pointerup", onPointerUp);
4866
- window.removeEventListener("pointercancel", onPointerCancel);
4841
+ window.removeEventListener("pointerup", onPointerUp, endEventOptions);
4842
+ window.removeEventListener("pointercancel", onPointerCancel, endEventOptions);
4867
4843
  if (isPressing.has(target)) {
4868
4844
  isPressing.delete(target);
4869
4845
  }
@@ -4883,8 +4859,8 @@ function press(targetOrSelector, onPressStart, options = {}) {
4883
4859
  const onPointerCancel = (cancelEvent) => {
4884
4860
  onPointerEnd(cancelEvent, false);
4885
4861
  };
4886
- window.addEventListener("pointerup", onPointerUp, eventOptions);
4887
- window.addEventListener("pointercancel", onPointerCancel, eventOptions);
4862
+ window.addEventListener("pointerup", onPointerUp, endEventOptions);
4863
+ window.addEventListener("pointercancel", onPointerCancel, endEventOptions);
4888
4864
  };
4889
4865
  targets.forEach((target) => {
4890
4866
  const pointerDownTarget = options.useGlobalTarget ? window : target;
@@ -5023,116 +4999,34 @@ function observeTimeline(update, timeline) {
5023
4999
  return () => cancelFrame(onFrame);
5024
5000
  }
5025
5001
 
5026
- function record() {
5027
- const { value } = statsBuffer;
5028
- if (value === null) {
5029
- cancelFrame(record);
5030
- return;
5031
- }
5032
- value.frameloop.rate.push(frameData.delta);
5033
- value.animations.mainThread.push(activeAnimations.mainThread);
5034
- value.animations.waapi.push(activeAnimations.waapi);
5035
- value.animations.layout.push(activeAnimations.layout);
5036
- }
5037
- function mean(values) {
5038
- return values.reduce((acc, value) => acc + value, 0) / values.length;
5039
- }
5040
- function summarise(values, calcAverage = mean) {
5041
- if (values.length === 0) {
5042
- return {
5043
- min: 0,
5044
- max: 0,
5045
- avg: 0,
5046
- };
5047
- }
5048
- return {
5049
- min: Math.min(...values),
5050
- max: Math.max(...values),
5051
- avg: calcAverage(values),
5052
- };
5053
- }
5054
- const msToFps = (ms) => Math.round(1000 / ms);
5002
+ const statsBuffer = {
5003
+ value: null,
5004
+ addProjectionMetrics: null,
5005
+ };
5006
+
5055
5007
  function clearStatsBuffer() {
5056
5008
  statsBuffer.value = null;
5057
5009
  statsBuffer.addProjectionMetrics = null;
5058
5010
  }
5059
- function reportStats() {
5060
- const { value } = statsBuffer;
5061
- if (!value) {
5062
- throw new Error("Stats are not being measured");
5063
- }
5064
- clearStatsBuffer();
5065
- cancelFrame(record);
5066
- const summary = {
5067
- frameloop: {
5068
- setup: summarise(value.frameloop.setup),
5069
- rate: summarise(value.frameloop.rate),
5070
- read: summarise(value.frameloop.read),
5071
- resolveKeyframes: summarise(value.frameloop.resolveKeyframes),
5072
- preUpdate: summarise(value.frameloop.preUpdate),
5073
- update: summarise(value.frameloop.update),
5074
- preRender: summarise(value.frameloop.preRender),
5075
- render: summarise(value.frameloop.render),
5076
- postRender: summarise(value.frameloop.postRender),
5077
- },
5078
- animations: {
5079
- mainThread: summarise(value.animations.mainThread),
5080
- waapi: summarise(value.animations.waapi),
5081
- layout: summarise(value.animations.layout),
5082
- },
5083
- layoutProjection: {
5084
- nodes: summarise(value.layoutProjection.nodes),
5085
- calculatedTargetDeltas: summarise(value.layoutProjection.calculatedTargetDeltas),
5086
- calculatedProjections: summarise(value.layoutProjection.calculatedProjections),
5087
- },
5088
- };
5089
- /**
5090
- * Convert the rate to FPS
5091
- */
5092
- const { rate } = summary.frameloop;
5093
- rate.min = msToFps(rate.min);
5094
- rate.max = msToFps(rate.max);
5095
- rate.avg = msToFps(rate.avg);
5096
- [rate.min, rate.max] = [rate.max, rate.min];
5097
- return summary;
5098
- }
5099
5011
  function recordStats() {
5100
5012
  if (statsBuffer.value) {
5101
5013
  clearStatsBuffer();
5102
5014
  throw new Error("Stats are already being measured");
5103
5015
  }
5104
- const newStatsBuffer = statsBuffer;
5105
- newStatsBuffer.value = {
5106
- frameloop: {
5107
- setup: [],
5108
- rate: [],
5109
- read: [],
5110
- resolveKeyframes: [],
5111
- preUpdate: [],
5112
- update: [],
5113
- preRender: [],
5114
- render: [],
5115
- postRender: [],
5116
- },
5117
- animations: {
5118
- mainThread: [],
5119
- waapi: [],
5120
- layout: [],
5121
- },
5016
+ const buffer = statsBuffer;
5017
+ buffer.value = {
5122
5018
  layoutProjection: {
5123
5019
  nodes: [],
5124
5020
  calculatedTargetDeltas: [],
5125
5021
  calculatedProjections: [],
5126
5022
  },
5127
5023
  };
5128
- newStatsBuffer.addProjectionMetrics = (metrics) => {
5129
- const { layoutProjection } = newStatsBuffer.value;
5024
+ buffer.addProjectionMetrics = (metrics) => {
5025
+ const { layoutProjection } = buffer.value;
5130
5026
  layoutProjection.nodes.push(metrics.nodes);
5131
5027
  layoutProjection.calculatedTargetDeltas.push(metrics.calculatedTargetDeltas);
5132
5028
  layoutProjection.calculatedProjections.push(metrics.calculatedProjections);
5133
5029
  };
5134
- frame.postRender(record, true);
5135
- return reportStats;
5136
5030
  }
5137
5031
 
5138
5032
  /**
@@ -5418,14 +5312,126 @@ const valueTypes = [...dimensionValueTypes, color, complex];
5418
5312
  */
5419
5313
  const findValueType = (v) => valueTypes.find(testValueType(v));
5420
5314
 
5315
+ let nameCount = 0;
5316
+ /**
5317
+ * Generated names live in their own namespace so we can tell a name we own
5318
+ * (and must clean up) from an author-defined one - and so a stale generated
5319
+ * name left behind by an interrupted transition is re-owned, not mistaken for
5320
+ * the author's and leaked.
5321
+ */
5322
+ const generatedName = () => `motion-view-${nameCount++}`;
5323
+ const isGeneratedName = (name) => name.startsWith("motion-view-");
5324
+ /**
5325
+ * Tag a captured element with a `view-transition-class` so authors can target
5326
+ * its generated layer from CSS (e.g. `::view-transition-group(.hero)`) without
5327
+ * the opaque generated name. Tracked in `classed` - separate from the generated
5328
+ * names in `assigned` - so cleanup removes the class without ever stripping an
5329
+ * author's own inline `view-transition-name`.
5330
+ */
5331
+ function tagClass(element, className, classed) {
5332
+ if (!className)
5333
+ return;
5334
+ element.style?.setProperty("view-transition-class", className);
5335
+ classed.push(element);
5336
+ }
5337
+ /**
5338
+ * Resolve a selector/Element to elements and ensure each one carries a
5339
+ * `view-transition-name` we can target from script.
5340
+ *
5341
+ * Author-defined names are reused as-is. Elements that are unnamed (or use
5342
+ * the browser's `auto`/`match-element`, whose generated name is not exposed
5343
+ * to script) are given a unique generated name, set inline so it's captured,
5344
+ * and tracked in `assigned` for later cleanup.
5345
+ *
5346
+ * `registry` maps each Element to its name so the same element keeps its name
5347
+ * across both captures (before and after the update), which is what allows a
5348
+ * persistent element to animate as a single `group` layer.
5349
+ */
5350
+ function assignViewTransitionNames(definition, registry, assigned, forcedNames, className, classed = []) {
5351
+ const elements = resolveElements(definition);
5352
+ /**
5353
+ * The new end of a paired morph: give each element the matching name from
5354
+ * the old end (by index) so the two share one layer and morph. If the new
5355
+ * end resolves to *more* elements than the old end named, the extras have no
5356
+ * counterpart - give them a fresh name so they animate as newcomers rather
5357
+ * than being silently left unnamed. We return the names actually assigned
5358
+ * (sized to the resolved elements), not the raw `forcedNames`, so stagger
5359
+ * totals and the layer set stay in step with what's on the page.
5360
+ */
5361
+ if (forcedNames) {
5362
+ return elements.map((element, i) => {
5363
+ const existing = registry.get(element);
5364
+ if (existing)
5365
+ return existing;
5366
+ const name = forcedNames[i] ?? generatedName();
5367
+ element.style?.setProperty("view-transition-name", name);
5368
+ assigned.push(element);
5369
+ registry.set(element, name);
5370
+ tagClass(element, className, classed);
5371
+ return name;
5372
+ });
5373
+ }
5374
+ /**
5375
+ * Read every current name up front, before assigning any. Interleaving the
5376
+ * reads with the inline `setProperty` writes below would dirty styles
5377
+ * between reads and force a style recalc per element; batching the reads
5378
+ * keeps it to one. Elements already in the registry keep their name and
5379
+ * need no read.
5380
+ */
5381
+ const currentNames = elements.map((element) => registry.has(element)
5382
+ ? undefined
5383
+ : getComputedStyle(element).getPropertyValue("view-transition-name"));
5384
+ return elements.map((element, i) => {
5385
+ const existing = registry.get(element);
5386
+ if (existing)
5387
+ return existing;
5388
+ const current = currentNames[i];
5389
+ let name;
5390
+ if (current &&
5391
+ current !== "none" &&
5392
+ current !== "auto" &&
5393
+ current !== "match-element" &&
5394
+ !isGeneratedName(current)) {
5395
+ /**
5396
+ * The author already named this layer - target it as-is and leave
5397
+ * it to them to clean up. `auto`/`match-element` are overridden
5398
+ * because their generated name is not exposed to script, and a
5399
+ * stale `motion-view-*` (e.g. left by an interrupted transition) is
5400
+ * re-owned rather than adopted as an author name and leaked.
5401
+ */
5402
+ name = current;
5403
+ }
5404
+ else {
5405
+ name = generatedName();
5406
+ element.style?.setProperty("view-transition-name", name);
5407
+ assigned.push(element);
5408
+ }
5409
+ registry.set(element, name);
5410
+ tagClass(element, className, classed);
5411
+ return name;
5412
+ });
5413
+ }
5414
+ /**
5415
+ * Remove the `view-transition-name`s we generated and the
5416
+ * `view-transition-class`es we applied. Author-defined names are never touched
5417
+ * (they're not in `assigned`). Safe to call more than once (e.g. on both a
5418
+ * finished and an interrupted transition).
5419
+ */
5420
+ function releaseViewTransitionNames(assigned, classed = []) {
5421
+ for (const element of assigned) {
5422
+ element.style?.removeProperty("view-transition-name");
5423
+ }
5424
+ for (const element of classed) {
5425
+ element.style?.removeProperty("view-transition-class");
5426
+ }
5427
+ }
5428
+
5421
5429
  function chooseLayerType(valueName) {
5422
5430
  if (valueName === "layout")
5423
5431
  return "group";
5424
5432
  if (valueName === "enter" || valueName === "new")
5425
5433
  return "new";
5426
- if (valueName === "exit" || valueName === "old")
5427
- return "old";
5428
- return "group";
5434
+ return "old";
5429
5435
  }
5430
5436
 
5431
5437
  let pendingRules = {};
@@ -5460,21 +5466,21 @@ const css = {
5460
5466
  };
5461
5467
 
5462
5468
  function getViewAnimationLayerInfo(pseudoElement) {
5463
- const match = pseudoElement.match(/::view-transition-(old|new|group|image-pair)\((.*?)\)/);
5469
+ const match = pseudoElement.match(
5470
+ // `group-children` (nested transitions) before `group` so it wins.
5471
+ /::view-transition-(old|new|group-children|group|image-pair)\((.*?)\)/);
5464
5472
  if (!match)
5465
5473
  return null;
5466
5474
  return { layer: match[2], type: match[1] };
5467
5475
  }
5468
5476
 
5469
- function filterViewAnimations(animation) {
5470
- const { effect } = animation;
5471
- if (!effect)
5472
- return false;
5473
- return (effect.target === document.documentElement &&
5474
- effect.pseudoElement?.startsWith("::view-transition"));
5475
- }
5476
5477
  function getViewAnimations() {
5477
- return document.getAnimations().filter(filterViewAnimations);
5478
+ return document.getAnimations().filter((animation) => {
5479
+ const { effect } = animation;
5480
+ return (!!effect &&
5481
+ effect.target === document.documentElement &&
5482
+ effect.pseudoElement?.startsWith("::view-transition"));
5483
+ });
5478
5484
  }
5479
5485
 
5480
5486
  function hasTarget(target, targets) {
@@ -5482,87 +5488,370 @@ function hasTarget(target, targets) {
5482
5488
  }
5483
5489
 
5484
5490
  const definitionNames = ["layout", "enter", "exit", "new", "old"];
5491
+ /**
5492
+ * The `ViewTransitionTarget` buckets driving each generated layer type, in
5493
+ * priority order - the inverse of `chooseLayerType`. The new view is driven by
5494
+ * `new`/`enter`, the old by `old`/`exit`. `group-children`/`image-pair` have no
5495
+ * bucket; they follow the default layout timing.
5496
+ */
5497
+ const typeBuckets = {
5498
+ group: ["layout"],
5499
+ new: ["new", "enter"],
5500
+ old: ["old", "exit"],
5501
+ };
5502
+ /**
5503
+ * Default "absent" origin for a single-value keyframe, by pseudo type, so e.g.
5504
+ * `enter({ scale: 1 })` grows in from 0.85 and `exit({ opacity: 0 })` fades
5505
+ * from 1. `enter` prefers the matching `exit` value over these (see below).
5506
+ */
5507
+ const ORIGIN_DEFAULTS = {
5508
+ new: { opacity: 0, scale: 0.85 },
5509
+ old: { opacity: 1, scale: 1 },
5510
+ };
5511
+ const cornerProps = [
5512
+ "borderTopLeftRadius",
5513
+ "borderTopRightRadius",
5514
+ "borderBottomRightRadius",
5515
+ "borderBottomLeftRadius",
5516
+ ];
5485
5517
  function startViewAnimation(builder) {
5486
- const { update, targets, options: defaultOptions } = builder;
5518
+ const { update, targets, resolveDefs, noCrop, pairs, classNames, options: defaultOptions, } = builder;
5487
5519
  if (!document.startViewTransition) {
5488
- return new Promise(async (resolve) => {
5520
+ // An async IIFE (not `new Promise(async …)`) so a throwing/rejecting
5521
+ // update rejects this promise rather than leaving it unsettled.
5522
+ return (async () => {
5489
5523
  await update();
5490
- resolve(new GroupAnimation([]));
5491
- });
5524
+ return new GroupAnimation([]);
5525
+ })();
5492
5526
  }
5493
- // TODO: Go over existing targets and ensure they all have ids
5494
5527
  /**
5495
- * If we don't have any animations defined for the root target,
5496
- * remove it from being captured.
5528
+ * Resolve any selector/Element targets to layer names, assigning a
5529
+ * `view-transition-name` to each element as we go. We run this before the
5530
+ * update (so the elements are captured in the old snapshot) and again
5531
+ * after it (for the new snapshot). An element present in both keeps the
5532
+ * same name and animates as a single `group` layer.
5533
+ */
5534
+ const nameRegistry = new Map();
5535
+ const assigned = [];
5536
+ /**
5537
+ * Elements we tagged with a `view-transition-class` (via `.class()`),
5538
+ * tracked separately from `assigned` so cleanup removes the class without
5539
+ * ever stripping an author's own inline `view-transition-name`.
5497
5540
  */
5498
- if (!hasTarget("root", targets)) {
5499
- css.set(":root", {
5500
- "view-transition-name": "none",
5541
+ const classed = [];
5542
+ const layerTargets = new Map();
5543
+ const croppedNames = new Set();
5544
+ /**
5545
+ * Each layer's stagger position (index + total) within its subject, per
5546
+ * snapshot. Resolving against the snapshot the layer belongs to keeps
5547
+ * stagger correct when `update()` replaces the matched elements, and lets
5548
+ * us skip a layer that's absent from a snapshot (e.g. an exited element
5549
+ * has no `new` pseudo-element).
5550
+ */
5551
+ const layerStagger = new Map();
5552
+ /**
5553
+ * Names allocated for a paired subject in the old snapshot, replayed onto
5554
+ * its new-snapshot target so both ends share a layer and morph.
5555
+ */
5556
+ const pairNames = new Map();
5557
+ /**
5558
+ * The old (`from`) elements of each paired subject, so their names can be
5559
+ * transferred off before the new (`to`) elements inherit them.
5560
+ */
5561
+ const pairFrom = new Map();
5562
+ const resolveLayers = (phase) => {
5563
+ targets.forEach((target, definition) => {
5564
+ const className = classNames.get(definition);
5565
+ let names;
5566
+ if (definition === "root" || !resolveDefs.has(definition)) {
5567
+ names = [definition];
5568
+ }
5569
+ else if (pairs.has(definition)) {
5570
+ /**
5571
+ * Paired morph: name the old target in the old snapshot, then
5572
+ * force the same name(s) onto the new target in the new one, so
5573
+ * two different elements morph as a single layer.
5574
+ */
5575
+ if (phase === "old") {
5576
+ pairFrom.set(definition, resolveElements(definition));
5577
+ names = assignViewTransitionNames(definition, nameRegistry, assigned, undefined, className, classed);
5578
+ pairNames.set(definition, names);
5579
+ }
5580
+ else {
5581
+ /**
5582
+ * Transfer the name(s) off the `from` elements before the
5583
+ * `to` elements inherit them. A `from` that survives into
5584
+ * the new snapshot (e.g. hidden with `visibility: hidden`
5585
+ * rather than removed) would otherwise keep the name and
5586
+ * collide - "duplicate view-transition-name".
5587
+ */
5588
+ for (const el of pairFrom.get(definition) ?? []) {
5589
+ el.style?.removeProperty("view-transition-name");
5590
+ /**
5591
+ * Drop the old end from the registry too, so the new
5592
+ * end alone supplies this name's `new` crop radii - we
5593
+ * neither re-measure nor get ordered by a stale element.
5594
+ */
5595
+ nameRegistry.delete(el);
5596
+ }
5597
+ names = assignViewTransitionNames(pairs.get(definition), nameRegistry, assigned, pairNames.get(definition), className, classed);
5598
+ }
5599
+ }
5600
+ else {
5601
+ names = assignViewTransitionNames(definition, nameRegistry, assigned, undefined, className, classed);
5602
+ }
5603
+ const cropped = definition !== "root" && !noCrop.has(definition);
5604
+ names.forEach((name, index) => {
5605
+ /**
5606
+ * If two subjects resolve to the same element, merge their
5607
+ * definitions so neither subject's animations are dropped.
5608
+ */
5609
+ const existing = layerTargets.get(name);
5610
+ layerTargets.set(name, existing && existing !== target
5611
+ ? { ...existing, ...target }
5612
+ : target);
5613
+ if (cropped)
5614
+ croppedNames.add(name);
5615
+ const stagger = layerStagger.get(name) ?? {};
5616
+ stagger[phase] = [index, names.length];
5617
+ layerStagger.set(name, stagger);
5618
+ });
5501
5619
  });
5502
- }
5620
+ };
5621
+ /**
5622
+ * The stagger index/total for a layer, resolved against the snapshot it
5623
+ * belongs to. Returns index -1 when the layer is absent from that snapshot
5624
+ * so the caller can skip a pseudo-element that doesn't exist.
5625
+ */
5626
+ const staggerPosition = (name, type) => {
5627
+ const stagger = layerStagger.get(name);
5628
+ const position = type === "old"
5629
+ ? stagger?.old
5630
+ : type === "new"
5631
+ ? stagger?.new
5632
+ : // group / group-children / image-pair persist across both.
5633
+ stagger?.new ?? stagger?.old;
5634
+ return position ?? [-1, 1];
5635
+ };
5636
+ /**
5637
+ * Merge default + per-layer transition options for a generated layer and
5638
+ * resolve any stagger/delay function against this element's position. Used
5639
+ * by both the morph-retiming and crop corner-radius passes.
5640
+ */
5641
+ const resolveLayerTransition = (target, type, transitionName, index, total) => {
5642
+ const transition = mergeTransition(getValueTransition(defaultOptions, transitionName), getValueTransition((layerOptions(target, type) ?? {}), transitionName));
5643
+ if (typeof transition.delay === "function") {
5644
+ transition.delay = transition.delay(index, total);
5645
+ }
5646
+ return transition;
5647
+ };
5648
+ /**
5649
+ * Measured corner radii per cropped layer, so the clip can animate each
5650
+ * corner between the old and new elements. Per-corner (rather than the
5651
+ * shorthand) so mismatched/individual radii interpolate cleanly.
5652
+ */
5653
+ const cropRadii = new Map();
5654
+ const recordRadii = (style, name, phase) => {
5655
+ const corners = {};
5656
+ for (const corner of cornerProps)
5657
+ corners[corner] = style[corner];
5658
+ const entry = cropRadii.get(name) ?? {};
5659
+ entry[phase] = corners;
5660
+ cropRadii.set(name, entry);
5661
+ };
5662
+ /**
5663
+ * Cropped layers all come from `.add()`, so their elements are in the
5664
+ * registry - read each one's corner radii directly. For a paired morph both
5665
+ * ends share a name; the new-snapshot element is registered last, so it
5666
+ * wins the `new` reading (and the old end the `old` reading).
5667
+ */
5668
+ const measureCrop = (phase) => {
5669
+ if (!croppedNames.size)
5670
+ return;
5671
+ nameRegistry.forEach((name, element) => {
5672
+ if (croppedNames.has(name)) {
5673
+ recordRadii(getComputedStyle(element), name, phase);
5674
+ }
5675
+ });
5676
+ };
5503
5677
  /**
5504
- * Set the timing curve to linear for all view transition layers.
5505
- * This gets baked into the keyframes, which can't be changed
5506
- * without breaking the generated animation.
5678
+ * Write the persistent view-transition CSS: suppress root capture when the
5679
+ * root has no animations of its own; force linear timing (baked into the
5680
+ * keyframes, so we can retime later via updateTiming); and clip +
5681
+ * object-fit: cover every cropped morph (the UA default overflows on
5682
+ * aspect-ratio change), with an animated border-radius added below.
5507
5683
  *
5508
- * This allows us to set easing via updateTiming - which can be changed.
5684
+ * `css.commit` replaces rather than appends, so we re-set the full rule set
5685
+ * each call - the second call (in the update callback) then picks up cropped
5686
+ * layers that only exist in the new snapshot.
5509
5687
  */
5510
- css.set("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)", { "animation-timing-function": "linear !important" });
5511
- css.commit(); // Write
5512
- const transition = document.startViewTransition(async () => {
5513
- await update();
5514
- // TODO: Go over new targets and ensure they all have ids
5515
- });
5516
- transition.finished.finally(() => {
5688
+ const commitViewCSS = () => {
5689
+ if (!hasTarget("root", targets)) {
5690
+ css.set(":root", { "view-transition-name": "none" });
5691
+ }
5692
+ css.set("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)", { "animation-timing-function": "linear !important" });
5693
+ croppedNames.forEach((name) => {
5694
+ css.set(`::view-transition-group(${name})`, { overflow: "clip" });
5695
+ css.set(`::view-transition-old(${name}), ::view-transition-new(${name})`, { width: "100%", height: "100%", "object-fit": "cover" });
5696
+ });
5697
+ css.commit(); // Write
5698
+ };
5699
+ const cleanup = () => {
5700
+ releaseViewTransitionNames(assigned, classed);
5517
5701
  css.remove(); // Write
5518
- });
5519
- return new Promise((resolve) => {
5520
- transition.ready.then(() => {
5702
+ };
5703
+ const callback = async () => {
5704
+ await update();
5705
+ /**
5706
+ * Re-resolve so elements created by the update are named for the new
5707
+ * snapshot, then measure the cropped layers' new border-radius.
5708
+ */
5709
+ const croppedBefore = croppedNames.size;
5710
+ resolveLayers("new");
5711
+ measureCrop("new");
5712
+ /**
5713
+ * Re-commit the crop CSS only if the new snapshot introduced cropped
5714
+ * layers, so a layer that exists only in the new snapshot is clipped
5715
+ * too - without forcing a redundant style write on the common path.
5716
+ */
5717
+ if (croppedNames.size > croppedBefore)
5718
+ commitViewCSS();
5719
+ };
5720
+ let transition;
5721
+ try {
5722
+ resolveLayers("old");
5723
+ measureCrop("old");
5724
+ commitViewCSS();
5725
+ transition = document.startViewTransition(callback);
5726
+ }
5727
+ catch (error) {
5728
+ /**
5729
+ * The prelude writes inline names before the transition exists. If it
5730
+ * throws (e.g. startViewTransition rejects in a bad UA state), release
5731
+ * them so we neither leak DOM state nor stall the queue on a promise
5732
+ * that never settles - hand back a rejection it can advance past.
5733
+ */
5734
+ cleanup();
5735
+ return Promise.reject(error);
5736
+ }
5737
+ transition.finished.finally(cleanup);
5738
+ return new Promise((resolve, reject) => {
5739
+ transition.ready
5740
+ .then(() => {
5521
5741
  const generatedViewAnimations = getViewAnimations();
5522
5742
  const animations = [];
5523
5743
  /**
5524
5744
  * Create animations for each of our explicitly-defined subjects.
5745
+ * `opacityAnimated` additionally tracks which `${name}:${type}`
5746
+ * we faded, so we can keep the UA `plus-lighter` blend only for a
5747
+ * genuine opacity crossfade (both sides fading) and drop it for a
5748
+ * slide/transform, where additive compositing would flash bright.
5525
5749
  */
5526
- targets.forEach((definition, target) => {
5527
- // TODO: If target is not "root", resolve elements
5528
- // and iterate over each
5750
+ const explicitlyAnimated = new Set();
5751
+ const opacityAnimated = new Set();
5752
+ layerTargets.forEach((target, name) => {
5753
+ const stagger = layerStagger.get(name);
5754
+ /**
5755
+ * Presence: `enter` only fires for a pure newcomer (a new
5756
+ * view with no old), `exit` only for a pure leaver. A
5757
+ * survivor (both) gets neither - it just morphs.
5758
+ */
5759
+ const enterApplies = !!stagger?.new && !stagger?.old;
5760
+ const exitApplies = !!stagger?.old && !stagger?.new;
5529
5761
  for (const key of definitionNames) {
5530
- if (!definition[key])
5762
+ if (!target[key])
5763
+ continue;
5764
+ if (key === "enter" && !enterApplies)
5765
+ continue;
5766
+ if (key === "exit" && !exitApplies)
5767
+ continue;
5768
+ const type = chooseLayerType(key);
5769
+ const [index, total] = staggerPosition(name, type);
5770
+ // Skip a layer absent from its snapshot.
5771
+ if (index === -1)
5531
5772
  continue;
5532
- const { keyframes, options } = definition[key];
5773
+ const { keyframes, options } = target[key];
5533
5774
  for (let [valueName, valueKeyframes] of Object.entries(keyframes)) {
5534
- if (!valueKeyframes)
5775
+ // Skip only missing values - `0` (e.g. opacity: 0)
5776
+ // is valid and must reach the from-value inference.
5777
+ if (valueKeyframes == null)
5535
5778
  continue;
5536
- const valueOptions = {
5537
- ...getValueTransition(defaultOptions, valueName),
5538
- ...getValueTransition(options, valueName),
5539
- };
5540
- const type = chooseLayerType(key);
5541
5779
  /**
5542
- * If this is an opacity animation, and keyframes are not an array,
5543
- * we need to convert them into an array and set an initial value.
5780
+ * The view path hands keyframes straight to WAAPI,
5781
+ * so Motion's `x`/`y` shorthands (compiled to
5782
+ * `transform` only via the value pipeline) have no
5783
+ * effect. Warn and skip - use `transform`/`translate`.
5784
+ */
5785
+ if (valueName === "x" || valueName === "y") {
5786
+ motionUtils.warnOnce(false, `animateView() animates view-transition layers with CSS properties; the "${valueName}" shorthand has no effect - use transform, e.g. { transform: "translateX(40px)" }.`);
5787
+ continue;
5788
+ }
5789
+ /**
5790
+ * enter/exit win over new/old on a shared property -
5791
+ * skip it here when the gated bucket also defines it.
5792
+ */
5793
+ if (key === "new" &&
5794
+ enterApplies &&
5795
+ target.enter?.keyframes[valueName] != null) {
5796
+ continue;
5797
+ }
5798
+ if (key === "old" &&
5799
+ exitApplies &&
5800
+ target.exit?.keyframes[valueName] != null) {
5801
+ continue;
5802
+ }
5803
+ const valueOptions = mergeTransition(getValueTransition(defaultOptions, valueName), getValueTransition(options, valueName));
5804
+ /**
5805
+ * Infer an origin for a single-value keyframe. An
5806
+ * `enter` mirrors the matching `exit` value (a
5807
+ * defined exit reverses into the enter for free);
5808
+ * otherwise the per-type default (opacity 0/1, scale
5809
+ * 0.85). No default -> left as-is (animates from the
5810
+ * live value).
5811
+ *
5812
+ * `new`/`old` fire for survivors too, where only the
5813
+ * opacity crossfade default applies - a transform
5814
+ * default like scale 0.85 would pop a persisting
5815
+ * element, so gate it on the layer actually
5816
+ * entering/leaving.
5544
5817
  */
5545
- if (valueName === "opacity" &&
5546
- !Array.isArray(valueKeyframes)) {
5547
- const initialValue = type === "new" ? 0 : 1;
5548
- valueKeyframes = [initialValue, valueKeyframes];
5818
+ if (!Array.isArray(valueKeyframes)) {
5819
+ const exitValue = key === "enter"
5820
+ ? target.exit?.keyframes[valueName]
5821
+ : undefined;
5822
+ const allowDefault = valueName === "opacity" ||
5823
+ (type === "new" ? enterApplies : exitApplies);
5824
+ const from = exitValue != null
5825
+ ? Array.isArray(exitValue)
5826
+ ? exitValue[exitValue.length - 1]
5827
+ : exitValue
5828
+ : allowDefault
5829
+ ? ORIGIN_DEFAULTS[type]?.[valueName]
5830
+ : undefined;
5831
+ if (from !== undefined) {
5832
+ valueKeyframes = [from, valueKeyframes];
5833
+ }
5549
5834
  }
5550
5835
  /**
5551
- * Resolve stagger function if provided.
5836
+ * Resolve stagger function if provided, per element
5837
+ * across this subject's resolved layers.
5552
5838
  */
5553
5839
  if (typeof valueOptions.delay === "function") {
5554
- valueOptions.delay = valueOptions.delay(0, 1);
5840
+ valueOptions.delay = valueOptions.delay(index, total);
5555
5841
  }
5556
5842
  valueOptions.duration && (valueOptions.duration = motionUtils.secondsToMilliseconds(valueOptions.duration));
5557
5843
  valueOptions.delay && (valueOptions.delay = motionUtils.secondsToMilliseconds(valueOptions.delay));
5558
- const animation = new NativeAnimation({
5844
+ animations.push(new NativeAnimation({
5559
5845
  ...valueOptions,
5560
5846
  element: document.documentElement,
5561
5847
  name: valueName,
5562
- pseudoElement: `::view-transition-${type}(${target})`,
5848
+ pseudoElement: `::view-transition-${type}(${name})`,
5563
5849
  keyframes: valueKeyframes,
5564
- });
5565
- animations.push(animation);
5850
+ }));
5851
+ explicitlyAnimated.add(`${name}:${type}`);
5852
+ if (valueName === "opacity") {
5853
+ opacityAnimated.add(`${name}:${type}`);
5854
+ }
5566
5855
  }
5567
5856
  }
5568
5857
  });
@@ -5581,45 +5870,161 @@ function startViewAnimation(builder) {
5581
5870
  const name = getViewAnimationLayerInfo(pseudoElement);
5582
5871
  if (!name)
5583
5872
  continue;
5584
- const targetDefinition = targets.get(name.layer);
5585
- if (!targetDefinition) {
5586
- /**
5587
- * If transition name is group then update the timing of the animation
5588
- * whereas if it's old or new then we could possibly replace it using
5589
- * the above method.
5590
- */
5591
- const transitionName = name.type === "group" ? "layout" : "";
5592
- let animationTransition = {
5593
- ...getValueTransition(defaultOptions, transitionName),
5594
- };
5595
- animationTransition.duration && (animationTransition.duration = motionUtils.secondsToMilliseconds(animationTransition.duration));
5596
- animationTransition =
5597
- applyGeneratorOptions(animationTransition);
5598
- const easing = mapEasingToNativeEasing(animationTransition.ease, animationTransition.duration);
5599
- effect.updateTiming({
5600
- delay: motionUtils.secondsToMilliseconds(animationTransition.delay ?? 0),
5601
- duration: animationTransition.duration,
5602
- easing,
5603
- });
5604
- animations.push(new NativeAnimationWrapper(animation));
5605
- }
5606
- else if (hasOpacity(targetDefinition, "enter") &&
5607
- hasOpacity(targetDefinition, "exit") &&
5608
- effect
5609
- .getKeyframes()
5610
- .some((keyframe) => keyframe.mixBlendMode)) {
5611
- animations.push(new NativeAnimationWrapper(animation));
5612
- }
5613
- else {
5614
- animation.cancel();
5873
+ const targetDefinition = layerTargets.get(name.layer);
5874
+ /**
5875
+ * We built our own animation for this layer, so drop the
5876
+ * browser-generated fade we're replacing. The UA
5877
+ * `plus-lighter` blend is a *separate* generated animation on
5878
+ * the same pseudo (it sets `mix-blend-mode` in its keyframes):
5879
+ * keep it *only* for a true opacity crossfade - both sides
5880
+ * fading - so a symmetric crossfade composites without
5881
+ * darkening, but a slide/transform (where both layers stay
5882
+ * opaque and overlap) doesn't flash bright from the addition.
5883
+ */
5884
+ if (explicitlyAnimated.has(`${name.layer}:${name.type}`)) {
5885
+ const isCrossfade = opacityAnimated.has(`${name.layer}:new`) &&
5886
+ opacityAnimated.has(`${name.layer}:old`);
5887
+ if (isCrossfade &&
5888
+ effect
5889
+ .getKeyframes()
5890
+ .some((keyframe) => keyframe.mixBlendMode)) {
5891
+ animations.push(new NativeAnimationWrapper(animation));
5892
+ }
5893
+ else {
5894
+ animation.cancel();
5895
+ }
5896
+ continue;
5615
5897
  }
5898
+ /**
5899
+ * Otherwise retime the browser-generated animation to
5900
+ * Motion's timing. This auto-enables the layout (group)
5901
+ * morph for any resolved/named target, and applies the
5902
+ * default timing to old/new layers we haven't explicitly
5903
+ * overridden.
5904
+ *
5905
+ * group + group-children both follow the layout timing so
5906
+ * the nesting container stays in sync with the morph.
5907
+ */
5908
+ /**
5909
+ * A survivor's old + new are the two halves of one
5910
+ * `plus-lighter` crossfade. They must share identical timing
5911
+ * (so their opacities stay mirrored and sum to 1 - else the
5912
+ * additive blend flashes bright wherever both are partly
5913
+ * visible) and fade linearly (the bounce belongs on the
5914
+ * group's geometry, not the opacity). So time them as the
5915
+ * group, rather than via their own - potentially staggered,
5916
+ * or enter/exit-derived - old/new options.
5917
+ */
5918
+ const stagger = layerStagger.get(name.layer);
5919
+ const isMorphCrossfade = (name.type === "old" || name.type === "new") &&
5920
+ !!stagger?.old &&
5921
+ !!stagger?.new;
5922
+ const timingType = name.type.startsWith("group") || isMorphCrossfade
5923
+ ? "group"
5924
+ : name.type;
5925
+ const [index, total] = staggerPosition(name.layer, timingType);
5926
+ const transitionName = timingType === "group" ? "layout" : "";
5927
+ let animationTransition = resolveLayerTransition(targetDefinition, timingType, transitionName, index === -1 ? 0 : index, total);
5928
+ /**
5929
+ * The crossfade should resolve at the spring's *perceptual*
5930
+ * (visual) duration - the geometry can keep bouncing, but the
5931
+ * opacity shouldn't drag through the settle. So capture
5932
+ * `visualDuration` before `applyGeneratorOptions` replaces it
5933
+ * with the full overshoot duration, and use it for the fade.
5934
+ */
5935
+ const visualDuration = animationTransition.visualDuration;
5936
+ animationTransition.duration && (animationTransition.duration = motionUtils.secondsToMilliseconds(animationTransition.duration));
5937
+ animationTransition =
5938
+ applyGeneratorOptions(animationTransition);
5939
+ const duration = isMorphCrossfade && visualDuration !== undefined
5940
+ ? motionUtils.secondsToMilliseconds(visualDuration)
5941
+ : animationTransition.duration;
5942
+ const easing = isMorphCrossfade
5943
+ ? "linear"
5944
+ : mapEasingToNativeEasing(animationTransition.ease, animationTransition.duration);
5945
+ effect.updateTiming({
5946
+ delay: motionUtils.secondsToMilliseconds(animationTransition.delay ?? 0),
5947
+ duration,
5948
+ easing,
5949
+ });
5950
+ animations.push(new NativeAnimationWrapper(animation));
5616
5951
  }
5952
+ /**
5953
+ * Animate each cropped layer's clip corners between the old and
5954
+ * new elements, so a cropped morph keeps rounded corners
5955
+ * (handling individual per-corner radii).
5956
+ */
5957
+ cropRadii.forEach((radii, name) => {
5958
+ if (!radii.old && !radii.new)
5959
+ return;
5960
+ const target = layerTargets.get(name);
5961
+ const [index, total] = staggerPosition(name, "group");
5962
+ const radiusOptions = resolveLayerTransition(target, "group", "layout", index === -1 ? 0 : index, total);
5963
+ radiusOptions.duration && (radiusOptions.duration = motionUtils.secondsToMilliseconds(radiusOptions.duration));
5964
+ radiusOptions.delay && (radiusOptions.delay = motionUtils.secondsToMilliseconds(radiusOptions.delay));
5965
+ for (const corner of cornerProps) {
5966
+ // `||` (not `??`) so an empty measurement (e.g. an
5967
+ // un-rendered element) falls back rather than producing
5968
+ // an invalid keyframe.
5969
+ const from = radii.old?.[corner] || radii.new?.[corner] || "0px";
5970
+ const to = radii.new?.[corner] || radii.old?.[corner] || "0px";
5971
+ // Skip square corners - nothing to round.
5972
+ if (parseFloat(from) === 0 && parseFloat(to) === 0) {
5973
+ continue;
5974
+ }
5975
+ animations.push(new NativeAnimation({
5976
+ ...radiusOptions,
5977
+ element: document.documentElement,
5978
+ name: corner,
5979
+ pseudoElement: `::view-transition-group(${name})`,
5980
+ keyframes: [from, to],
5981
+ }));
5982
+ }
5983
+ });
5617
5984
  resolve(new GroupAnimation(animations));
5618
- });
5985
+ })
5986
+ .catch(() =>
5987
+ /**
5988
+ * `ready` rejects when the transition is skipped - no visual
5989
+ * change, or superseded by an interrupting transition. The DOM
5990
+ * update still applied, so settle with no animations rather than
5991
+ * surfacing it as an error to an awaiting caller. A genuine
5992
+ * failure in `update()` rejects `updateCallbackDone` (already
5993
+ * settled by now), so propagate that instead.
5994
+ */
5995
+ transition.updateCallbackDone.then(() => resolve(new GroupAnimation([])), reject));
5619
5996
  });
5620
5997
  }
5621
- function hasOpacity(target, key) {
5622
- return target?.[key]?.keyframes.opacity;
5998
+ /**
5999
+ * The options that should time a given generated layer type, so a retimed
6000
+ * group/old/new picks up any per-target transition the user provided. Checks
6001
+ * the type's buckets in priority order (e.g. `new` before `enter`).
6002
+ */
6003
+ function layerOptions(target, type) {
6004
+ for (const bucket of typeBuckets[type] ?? []) {
6005
+ const options = target?.[bucket]?.options;
6006
+ if (options)
6007
+ return options;
6008
+ }
6009
+ }
6010
+ /**
6011
+ * Merge a base transition (e.g. the default `options`) with a per-layer/value
6012
+ * override. An explicit `duration` on the override must win over an inherited
6013
+ * generator's own timing: a spring prefers `visualDuration`, and
6014
+ * `spring.applyToOptions` overwrites `duration` with the computed settle time -
6015
+ * so without this the override is silently discarded. Dropping the inherited
6016
+ * `type`/`visualDuration` makes the layer a plain tween of that duration, unless
6017
+ * it asked for its own generator `type`/`visualDuration`.
6018
+ */
6019
+ function mergeTransition(base, override) {
6020
+ const merged = { ...base, ...override };
6021
+ if (override.duration !== undefined) {
6022
+ if (override.visualDuration === undefined)
6023
+ delete merged.visualDuration;
6024
+ if (override.type === undefined)
6025
+ delete merged.type;
6026
+ }
6027
+ return merged;
5623
6028
  }
5624
6029
 
5625
6030
  let builders = [];
@@ -5633,10 +6038,16 @@ function next() {
5633
6038
  function start(builder) {
5634
6039
  motionUtils.removeItem(builders, builder);
5635
6040
  current = builder;
5636
- startViewAnimation(builder).then((animation) => {
6041
+ startViewAnimation(builder)
6042
+ .then((animation) => {
5637
6043
  builder.notifyReady(animation);
5638
- animation.finished.finally(next);
5639
- });
6044
+ return animation.finished;
6045
+ })
6046
+ // A genuinely failed transition (a throwing update) rejects the
6047
+ // builder; a skipped/interrupted one resolves with no animations (see
6048
+ // start.ts). Either way, advance the queue - else later transitions hang.
6049
+ .catch((error) => builder.notifyReject(error))
6050
+ .finally(next);
5640
6051
  }
5641
6052
  function processQueue() {
5642
6053
  /**
@@ -5673,31 +6084,96 @@ class ViewTransitionBuilder {
5673
6084
  constructor(update, options = {}) {
5674
6085
  this.currentSubject = "root";
5675
6086
  this.targets = new Map();
6087
+ /**
6088
+ * Definitions that must be resolved to elements (and assigned a
6089
+ * `view-transition-name`) rather than treated as pre-named layers.
6090
+ */
6091
+ this.resolveDefs = new Set();
6092
+ /**
6093
+ * Subjects opted out of the default crop (clip + object-fit: cover +
6094
+ * animated corner radii) via `.crop(false)`.
6095
+ */
6096
+ this.noCrop = new Set();
6097
+ /**
6098
+ * Subjects paired with a different new-snapshot target (the second `.add()`
6099
+ * argument), so two distinct elements share one name and morph into each
6100
+ * other - a shared-element transition.
6101
+ */
6102
+ this.pairs = new Map();
6103
+ /**
6104
+ * A `view-transition-class` to apply to each subject's resolved elements,
6105
+ * so authors can target the generated layers from CSS by class rather than
6106
+ * the opaque generated name.
6107
+ */
6108
+ this.classNames = new Map();
5676
6109
  this.notifyReady = motionUtils.noop;
5677
- this.readyPromise = new Promise((resolve) => {
6110
+ this.notifyReject = motionUtils.noop;
6111
+ this.readyPromise = new Promise((resolve, reject) => {
5678
6112
  this.notifyReady = resolve;
6113
+ this.notifyReject = reject;
5679
6114
  });
5680
6115
  this.update = update;
5681
6116
  this.options = {
5682
6117
  interrupt: "wait",
5683
6118
  ...options,
5684
6119
  };
6120
+ // Avoid an unhandled rejection when a failed transition has no
6121
+ // `.then(_, reject)` handler attached (e.g. fire-and-forget).
6122
+ this.readyPromise.catch(motionUtils.noop);
5685
6123
  addToQueue(this);
5686
6124
  }
5687
- get(subject) {
6125
+ /**
6126
+ * Target elements resolved from a selector or Element, each assigned a
6127
+ * `view-transition-name` automatically.
6128
+ *
6129
+ * Passing a second target pairs them: the first is resolved in the old
6130
+ * snapshot and the second in the new, sharing one name so two *different*
6131
+ * elements morph into each other (e.g. `.add(card, ".modal")`). Symmetric -
6132
+ * pass them the other way round to morph back.
6133
+ */
6134
+ add(subject, newSubject) {
5688
6135
  this.currentSubject = subject;
6136
+ this.resolveDefs.add(subject);
6137
+ if (newSubject !== undefined)
6138
+ this.pairs.set(subject, newSubject);
6139
+ // Register the subject so it participates (and gets an automatic
6140
+ // layout/morph animation) even without an explicit enter/exit/layout.
6141
+ if (!this.targets.has(subject))
6142
+ this.targets.set(subject, {});
5689
6143
  return this;
5690
6144
  }
5691
- layout(keyframes, options) {
5692
- this.updateTarget("layout", keyframes, options);
6145
+ /**
6146
+ * Morphs are clipped + `object-fit: cover` (and their corners animate)
6147
+ * by default. Call `.crop(false)` to opt this subject out and fall back
6148
+ * to the browser default (which overflows on aspect-ratio change).
6149
+ */
6150
+ crop(enabled = true) {
6151
+ enabled
6152
+ ? this.noCrop.delete(this.currentSubject)
6153
+ : this.noCrop.add(this.currentSubject);
5693
6154
  return this;
5694
6155
  }
5695
- new(keyframes, options) {
5696
- this.updateTarget("new", keyframes, options);
6156
+ /**
6157
+ * Tag this subject's generated layers with a `view-transition-class`, so
6158
+ * they can be targeted from CSS - `::view-transition-group(.name)`,
6159
+ * `::view-transition-old/new(.name)`, `::view-transition-image-pair(.name)`
6160
+ * - without the opaque generated `view-transition-name`. Because `.add()`
6161
+ * can match many elements, a shared class targets them all at once (and,
6162
+ * for a pair, both ends). The escape hatch for z-index / custom keyframes
6163
+ * on a morph layer.
6164
+ */
6165
+ class(name) {
6166
+ this.classNames.set(this.currentSubject, name);
5697
6167
  return this;
5698
6168
  }
5699
- old(keyframes, options) {
5700
- this.updateTarget("old", keyframes, options);
6169
+ /**
6170
+ * Set the transition for this subject's morph. The morph is enabled
6171
+ * automatically by `.add()`; this just customises its timing (duration,
6172
+ * easing, a `delay`/`stagger`, …). On the implicit `root` subject it also
6173
+ * opts the page into the transition (the root crossfade).
6174
+ */
6175
+ layout(options = {}) {
6176
+ this.updateTarget("layout", {}, options);
5701
6177
  return this;
5702
6178
  }
5703
6179
  enter(keyframes, options) {
@@ -5708,9 +6184,21 @@ class ViewTransitionBuilder {
5708
6184
  this.updateTarget("exit", keyframes, options);
5709
6185
  return this;
5710
6186
  }
5711
- crossfade(options) {
5712
- this.updateTarget("enter", { opacity: 1 }, options);
5713
- this.updateTarget("exit", { opacity: 0 }, options);
6187
+ /**
6188
+ * Animate the new view directly, whether the element is appearing or
6189
+ * persisting (unlike `.enter()`, which only fires for a pure newcomer).
6190
+ * Pair with `.old()` for a crossfade or slide-through.
6191
+ */
6192
+ new(keyframes, options) {
6193
+ this.updateTarget("new", keyframes, options);
6194
+ return this;
6195
+ }
6196
+ /**
6197
+ * Animate the old view directly, whether the element is leaving or
6198
+ * persisting (unlike `.exit()`, which only fires for a pure leaver).
6199
+ */
6200
+ old(keyframes, options) {
6201
+ this.updateTarget("old", keyframes, options);
5714
6202
  return this;
5715
6203
  }
5716
6204
  updateTarget(target, keyframes, options = {}) {
@@ -5725,8 +6213,8 @@ class ViewTransitionBuilder {
5725
6213
  return this.readyPromise.then(resolve, reject);
5726
6214
  }
5727
6215
  }
5728
- function animateView(update, defaultOptions = {}) {
5729
- return new ViewTransitionBuilder(update, defaultOptions);
6216
+ function animateView(update, options = {}) {
6217
+ return new ViewTransitionBuilder(update, options);
5730
6218
  }
5731
6219
 
5732
6220
  const createAxisDelta = () => ({
@@ -7846,7 +8334,7 @@ function animateSingleValue(value, keyframes, options) {
7846
8334
 
7847
8335
  function addDomEvent(target, eventName, handler, options = { passive: true }) {
7848
8336
  target.addEventListener(eventName, handler, options);
7849
- return () => target.removeEventListener(eventName, handler);
8337
+ return () => target.removeEventListener(eventName, handler, options);
7850
8338
  }
7851
8339
 
7852
8340
  const compareByDepth = (a, b) => a.depth - b.depth;
@@ -9116,7 +9604,6 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
9116
9604
  */
9117
9605
  this.pendingAnimation = frame.update(() => {
9118
9606
  globalProjectionState.hasAnimatedSinceResize = true;
9119
- activeAnimations.layout++;
9120
9607
  this.motionValue || (this.motionValue = motionValue(0));
9121
9608
  this.motionValue.jump(0, false);
9122
9609
  this.currentAnimation = animateSingleValue(this.motionValue, [0, 1000], {
@@ -9127,11 +9614,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
9127
9614
  this.mixTargetDelta(latest);
9128
9615
  options.onUpdate && options.onUpdate(latest);
9129
9616
  },
9130
- onStop: () => {
9131
- activeAnimations.layout--;
9132
- },
9133
9617
  onComplete: () => {
9134
- activeAnimations.layout--;
9135
9618
  options.onComplete && options.onComplete();
9136
9619
  this.completeAnimation();
9137
9620
  },
@@ -9720,39 +10203,221 @@ const HTMLProjectionNode = createProjectionNode({
9720
10203
  checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"),
9721
10204
  });
9722
10205
 
9723
- const layoutSelector = "[data-layout], [data-layout-id]";
9724
- const noop = () => { };
9725
- function snapshotFromTarget(projection) {
9726
- const target = projection.targetWithTransforms || projection.target;
9727
- if (!target)
9728
- return undefined;
9729
- const measuredBox = createBox();
9730
- const layoutBox = createBox();
9731
- copyBoxInto(measuredBox, target);
9732
- copyBoxInto(layoutBox, target);
10206
+ const layoutSelector = "[data-layout],[data-layout-id]";
10207
+ /**
10208
+ * All imperatively-created projection nodes live in one persistent tree,
10209
+ * shared across animateLayout() calls (and with any React-created nodes,
10210
+ * via the singleton document root). Keyed by element for reuse.
10211
+ */
10212
+ const layoutNodes = new WeakMap();
10213
+ /**
10214
+ * Builders created within the same synchronous tick are flushed together
10215
+ * as a single "commit": every node is snapshotted before any updateDom
10216
+ * runs, mirroring React batching renders from different parts of the tree.
10217
+ */
10218
+ let pendingBuilders;
10219
+ function collectLayoutElements(scope) {
10220
+ const elements = [];
10221
+ if (scope instanceof HTMLElement && scope.matches(layoutSelector)) {
10222
+ elements.push(scope);
10223
+ }
10224
+ scope.querySelectorAll(layoutSelector).forEach((element) => {
10225
+ if (element instanceof HTMLElement)
10226
+ elements.push(element);
10227
+ });
10228
+ return elements;
10229
+ }
10230
+ /**
10231
+ * Process any work scheduled on the frameloop now. A previous animation
10232
+ * may have been seeked while paused (controls.time = x) without a frame
10233
+ * having rendered it - we must materialise that state into the DOM
10234
+ * before taking snapshots.
10235
+ */
10236
+ function flushPendingFrame() {
10237
+ if (frameData.isProcessing)
10238
+ return;
10239
+ const now = time.now();
10240
+ frameData.delta = motionUtils.clamp(0, 1000 / 60, now - frameData.timestamp);
10241
+ frameData.timestamp = now;
10242
+ frameData.isProcessing = true;
10243
+ frameSteps.update.process(frameData);
10244
+ frameSteps.preRender.process(frameData);
10245
+ frameSteps.render.process(frameData);
10246
+ frameData.isProcessing = false;
10247
+ }
10248
+ function getProjectionParent(element) {
10249
+ let ancestor = element.parentElement;
10250
+ while (ancestor) {
10251
+ const node = layoutNodes.get(ancestor);
10252
+ if (node && node.instance)
10253
+ return node;
10254
+ ancestor = ancestor.parentElement;
10255
+ }
10256
+ return undefined;
10257
+ }
10258
+ function createVisualElement() {
10259
+ return new HTMLVisualElement({
10260
+ props: {},
10261
+ presenceContext: null,
10262
+ visualState: {
10263
+ latestValues: {},
10264
+ renderState: {
10265
+ transform: {},
10266
+ transformOrigin: {},
10267
+ style: {},
10268
+ vars: {},
10269
+ },
10270
+ },
10271
+ }, { allowProjection: true });
10272
+ }
10273
+ function readNodeOptions(element, transition) {
10274
+ const layoutAttr = element.getAttribute("data-layout");
10275
+ const layoutId = element.getAttribute("data-layout-id") ?? undefined;
9733
10276
  return {
9734
- animationId: projection.root?.animationId ?? 0,
9735
- measuredBox,
9736
- layoutBox,
9737
- latestValues: projection.animationValues || projection.latestValues || {},
9738
- source: projection.id,
10277
+ layoutId,
10278
+ layout: layoutAttr !== null ? true : undefined,
10279
+ animationType: (!layoutAttr || layoutAttr === "true"
10280
+ ? "both"
10281
+ : layoutAttr),
10282
+ transition,
9739
10283
  };
9740
10284
  }
10285
+ function prepareNode(element, transition) {
10286
+ let node = layoutNodes.get(element);
10287
+ if (!node) {
10288
+ let visualElement = visualElementStore.get(element);
10289
+ if (!visualElement)
10290
+ visualElement = createVisualElement();
10291
+ /**
10292
+ * A first-time element may carry a projection transform in its
10293
+ * inline style (e.g. it was cloned from an element mid-animation).
10294
+ * That transform isn't tracked in latestValues so the engine can't
10295
+ * reset it before measuring - clear it now so the first layout
10296
+ * measurement isn't inflated.
10297
+ */
10298
+ if (element.style.transform &&
10299
+ !hasTransform(visualElement.latestValues)) {
10300
+ element.style.transform = "";
10301
+ }
10302
+ node = new HTMLProjectionNode(visualElement.latestValues, getProjectionParent(element));
10303
+ visualElement.projection = node;
10304
+ node.setOptions({
10305
+ ...readNodeOptions(element, transition),
10306
+ visualElement,
10307
+ });
10308
+ node.mount(element);
10309
+ layoutNodes.set(element, node);
10310
+ }
10311
+ else {
10312
+ node.setOptions(readNodeOptions(element, transition));
10313
+ }
10314
+ node.isPresent = true;
10315
+ if (node.options.onExitComplete) {
10316
+ node.setOptions({ onExitComplete: undefined });
10317
+ }
10318
+ return node;
10319
+ }
10320
+ function sortDocumentOrder(elements) {
10321
+ return [...elements].sort((a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
10322
+ }
10323
+ function dropNode(element, node) {
10324
+ node.setOptions({ onExitComplete: undefined });
10325
+ /**
10326
+ * Stop any lingering animation so it can't leak into future updates.
10327
+ * A follow node can share its currentAnimation with a surviving lead
10328
+ * (via resumingFrom), in which case it isn't ours to stop.
10329
+ */
10330
+ const stack = node.getStack();
10331
+ if (!stack || node.isLead())
10332
+ node.currentAnimation?.stop();
10333
+ node.unmount();
10334
+ layoutNodes.delete(element);
10335
+ }
10336
+ function flushPendingBuilders() {
10337
+ const builders = pendingBuilders;
10338
+ pendingBuilders = undefined;
10339
+ flushPendingFrame();
10340
+ /**
10341
+ * Discover and mount every node across all builders before snapshotting
10342
+ * any of them. Mounting during an active update flags isLayoutDirty,
10343
+ * which would make that node's own willUpdate skip its snapshot.
10344
+ * Document order guarantees ancestors mount before descendants, even
10345
+ * when they're discovered by different builders.
10346
+ */
10347
+ const targets = new Map();
10348
+ for (const builder of builders) {
10349
+ for (const element of builder.collectTargets()) {
10350
+ const owners = targets.get(element);
10351
+ owners ? owners.push(builder) : targets.set(element, [builder]);
10352
+ }
10353
+ }
10354
+ const union = new Map();
10355
+ for (const element of sortDocumentOrder(targets.keys())) {
10356
+ const owners = targets.get(element);
10357
+ const node = prepareNode(element, owners[owners.length - 1].transitionFor(element));
10358
+ for (const owner of owners)
10359
+ owner.adopt(element, node);
10360
+ union.set(element, node);
10361
+ }
10362
+ union.forEach((node) => {
10363
+ node.isLayoutDirty = false;
10364
+ node.willUpdate();
10365
+ });
10366
+ const updatePromises = [];
10367
+ for (const builder of builders) {
10368
+ const result = builder.runUpdate();
10369
+ if (result)
10370
+ updatePromises.push(result);
10371
+ }
10372
+ const commit = () => {
10373
+ /**
10374
+ * Process all additions before any removals so that, even across
10375
+ * builders, a removed member knows whether a replacement with the
10376
+ * same layoutId was added in this commit.
10377
+ */
10378
+ const newMemberIds = new Set();
10379
+ for (const builder of builders) {
10380
+ builder.reconcileAdditions(newMemberIds);
10381
+ }
10382
+ for (const builder of builders) {
10383
+ builder.reconcileRemovals(newMemberIds);
10384
+ }
10385
+ let root;
10386
+ union.forEach((node) => (root || (root = node.root)));
10387
+ for (const builder of builders)
10388
+ root || (root = builder.getRoot());
10389
+ root?.didUpdate();
10390
+ /**
10391
+ * The root flushes the update on a microtask, synchronously
10392
+ * processing the frame that creates the layout animations. Collect
10393
+ * them in a later microtask step of the same pass.
10394
+ */
10395
+ microtask.render(() => {
10396
+ for (const builder of builders)
10397
+ builder.finalize();
10398
+ });
10399
+ };
10400
+ updatePromises.length ? Promise.all(updatePromises).then(commit) : commit();
10401
+ }
9741
10402
  class LayoutAnimationBuilder {
9742
10403
  constructor(scope, updateDom, defaultOptions) {
9743
- this.sharedTransitions = new Map();
9744
- this.notifyReady = noop;
9745
- this.rejectReady = noop;
9746
10404
  this.scope = scope;
9747
10405
  this.updateDom = updateDom;
9748
10406
  this.defaultOptions = defaultOptions;
10407
+ this.sharedTransitions = new Map();
10408
+ this.notifyReady = () => { };
10409
+ this.rejectReady = () => { };
10410
+ this.tracked = new Map();
10411
+ this.restorePoints = new Map();
9749
10412
  this.readyPromise = new Promise((resolve, reject) => {
9750
10413
  this.notifyReady = resolve;
9751
10414
  this.rejectReady = reject;
9752
10415
  });
9753
- frame.postRender(() => {
9754
- this.start().then(this.notifyReady).catch(this.rejectReady);
9755
- });
10416
+ if (!pendingBuilders) {
10417
+ pendingBuilders = [];
10418
+ queueMicrotask(flushPendingBuilders);
10419
+ }
10420
+ pendingBuilders.push(this);
9756
10421
  }
9757
10422
  shared(id, transition) {
9758
10423
  this.sharedTransitions.set(id, transition);
@@ -9761,114 +10426,107 @@ class LayoutAnimationBuilder {
9761
10426
  then(resolve, reject) {
9762
10427
  return this.readyPromise.then(resolve, reject);
9763
10428
  }
9764
- async start() {
9765
- const beforeElements = collectLayoutElements(this.scope);
9766
- const beforeRecords = this.buildRecords(beforeElements);
9767
- beforeRecords.forEach(({ projection }) => {
9768
- const hasCurrentAnimation = Boolean(projection.currentAnimation);
9769
- const isSharedLayout = Boolean(projection.options.layoutId);
9770
- if (hasCurrentAnimation && isSharedLayout) {
9771
- const snapshot = snapshotFromTarget(projection);
9772
- if (snapshot) {
9773
- projection.snapshot = snapshot;
9774
- }
9775
- else if (projection.snapshot) {
9776
- projection.snapshot = undefined;
9777
- }
9778
- }
9779
- else if (projection.snapshot &&
9780
- (projection.currentAnimation || projection.isProjecting())) {
9781
- projection.snapshot = undefined;
9782
- }
9783
- projection.isPresent = true;
9784
- projection.willUpdate();
10429
+ transitionFor(element) {
10430
+ const layoutId = element.getAttribute("data-layout-id");
10431
+ return ((layoutId && this.sharedTransitions.get(layoutId)) ||
10432
+ this.defaultOptions);
10433
+ }
10434
+ adopt(element, node) {
10435
+ this.tracked.set(element, node);
10436
+ this.restorePoints.set(element, {
10437
+ parent: element.parentElement,
10438
+ next: element.nextSibling,
9785
10439
  });
9786
- await this.updateDom();
9787
- const afterElements = collectLayoutElements(this.scope);
9788
- const afterRecords = this.buildRecords(afterElements);
9789
- this.handleExitingElements(beforeRecords, afterRecords);
9790
- afterRecords.forEach(({ projection }) => {
9791
- const instance = projection.instance;
9792
- const resumeFromInstance = projection.resumeFrom
9793
- ?.instance;
9794
- if (!instance || !resumeFromInstance)
9795
- return;
9796
- if (!("style" in instance))
9797
- return;
9798
- const currentTransform = instance.style.transform;
9799
- const resumeFromTransform = resumeFromInstance.style.transform;
9800
- if (currentTransform &&
9801
- resumeFromTransform &&
9802
- currentTransform === resumeFromTransform) {
9803
- instance.style.transform = "";
9804
- instance.style.transformOrigin = "";
10440
+ }
10441
+ collectTargets() {
10442
+ return collectLayoutElements(this.scope);
10443
+ }
10444
+ runUpdate() {
10445
+ try {
10446
+ const result = this.updateDom();
10447
+ if (result && typeof result.then === "function") {
10448
+ return result.then(undefined, (error) => {
10449
+ this.updateError = error;
10450
+ });
9805
10451
  }
9806
- });
9807
- afterRecords.forEach(({ projection }) => {
9808
- projection.isPresent = true;
9809
- });
9810
- const root = getProjectionRoot(afterRecords, beforeRecords);
9811
- root?.didUpdate();
9812
- await new Promise((resolve) => {
9813
- frame.postRender(() => resolve());
9814
- });
9815
- const animations = collectAnimations(afterRecords);
9816
- const animation = new GroupAnimation(animations);
9817
- return animation;
10452
+ }
10453
+ catch (error) {
10454
+ this.updateError = error;
10455
+ }
10456
+ return undefined;
9818
10457
  }
9819
- buildRecords(elements) {
9820
- const records = [];
9821
- const recordMap = new Map();
9822
- for (const element of elements) {
9823
- const parentRecord = findParentRecord(element, recordMap, this.scope);
9824
- const { layout, layoutId } = readLayoutAttributes(element);
9825
- const override = layoutId
9826
- ? this.sharedTransitions.get(layoutId)
9827
- : undefined;
9828
- const transition = override || this.defaultOptions;
9829
- const record = getOrCreateRecord(element, parentRecord?.projection, {
9830
- layout,
9831
- layoutId,
9832
- animationType: typeof layout === "string" ? layout : "both",
9833
- transition: transition,
9834
- });
9835
- recordMap.set(element, record);
9836
- records.push(record);
10458
+ reconcileAdditions(newMemberIds) {
10459
+ for (const element of collectLayoutElements(this.scope)) {
10460
+ if (this.tracked.has(element))
10461
+ continue;
10462
+ const node = prepareNode(element, this.transitionFor(element));
10463
+ this.adopt(element, node);
10464
+ node.options.layoutId && newMemberIds.add(node.options.layoutId);
9837
10465
  }
9838
- return records;
9839
10466
  }
9840
- handleExitingElements(beforeRecords, afterRecords) {
9841
- const afterElementsSet = new Set(afterRecords.map((record) => record.element));
9842
- beforeRecords.forEach((record) => {
9843
- if (afterElementsSet.has(record.element))
10467
+ reconcileRemovals(newMemberIds) {
10468
+ this.tracked.forEach((node, element) => {
10469
+ if (element.isConnected)
9844
10470
  return;
9845
- // For shared layout elements, relegate to set up resumeFrom
9846
- // so the remaining element animates from this position
9847
- if (record.projection.options.layoutId) {
9848
- record.projection.isPresent = false;
9849
- record.projection.relegate();
9850
- }
9851
- record.visualElement.unmount();
9852
- visualElementStore.delete(record.element);
10471
+ const restore = this.restorePoints.get(element);
10472
+ this.restorePoints.delete(element);
10473
+ const { layoutId } = node.options;
10474
+ const stack = node.getStack();
10475
+ const hasSurvivor = stack &&
10476
+ stack.members.some((member) => member !== node &&
10477
+ member.instance
10478
+ ?.isConnected);
10479
+ /**
10480
+ * A removed lead with a surviving stack member - and no
10481
+ * replacement member added this commit - runs an exit
10482
+ * crossfade: restore the element to its old position in the
10483
+ * DOM, relegate it and let the survivor take over. It's
10484
+ * removed again once the animation completes.
10485
+ */
10486
+ if (layoutId &&
10487
+ node.isLead() &&
10488
+ hasSurvivor &&
10489
+ !newMemberIds.has(layoutId)) {
10490
+ if (restore && restore.parent.isConnected) {
10491
+ restore.parent.insertBefore(element, restore.next && restore.next.parentNode === restore.parent
10492
+ ? restore.next
10493
+ : null);
10494
+ node.isPresent = false;
10495
+ node.setOptions({
10496
+ onExitComplete: () => {
10497
+ element.remove();
10498
+ dropNode(element, node);
10499
+ },
10500
+ });
10501
+ if (node.relegate())
10502
+ return;
10503
+ element.remove();
10504
+ }
10505
+ }
10506
+ dropNode(element, node);
10507
+ this.tracked.delete(element);
9853
10508
  });
9854
- // Clear resumeFrom on EXISTING nodes that point to unmounted projections
9855
- // This prevents crossfade animation when the source element was removed entirely
9856
- // But preserve resumeFrom for NEW nodes so they can animate from the old position
9857
- // Also preserve resumeFrom for lead nodes that were just promoted via relegate
9858
- const beforeElementsSet = new Set(beforeRecords.map((record) => record.element));
9859
- afterRecords.forEach(({ element, projection }) => {
9860
- if (beforeElementsSet.has(element) &&
9861
- projection.resumeFrom &&
9862
- !projection.resumeFrom.instance &&
9863
- !projection.isLead()) {
9864
- projection.resumeFrom = undefined;
9865
- projection.snapshot = undefined;
10509
+ }
10510
+ getRoot() {
10511
+ let root;
10512
+ this.tracked.forEach((node) => (root || (root = node.root)));
10513
+ return root;
10514
+ }
10515
+ finalize() {
10516
+ if (this.updateError) {
10517
+ this.rejectReady(this.updateError);
10518
+ return;
10519
+ }
10520
+ const animations = new Set();
10521
+ this.tracked.forEach((node) => {
10522
+ if (node.instance && node.currentAnimation) {
10523
+ animations.add(node.currentAnimation);
9866
10524
  }
9867
10525
  });
10526
+ this.notifyReady(new GroupAnimation([...animations]));
9868
10527
  }
9869
10528
  }
9870
10529
  function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9871
- // animateLayout(updateDom)
9872
10530
  if (typeof scopeOrUpdateDom === "function") {
9873
10531
  return {
9874
10532
  scope: document,
@@ -9876,107 +10534,15 @@ function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9876
10534
  defaultOptions: updateDomOrOptions,
9877
10535
  };
9878
10536
  }
9879
- // animateLayout(scope, updateDom, options?)
9880
- const elements = resolveElements(scopeOrUpdateDom);
9881
- const scope = elements[0] || document;
10537
+ const scope = scopeOrUpdateDom instanceof Document
10538
+ ? scopeOrUpdateDom
10539
+ : resolveElements(scopeOrUpdateDom)[0] ?? document;
9882
10540
  return {
9883
10541
  scope,
9884
10542
  updateDom: updateDomOrOptions,
9885
10543
  defaultOptions: options,
9886
10544
  };
9887
10545
  }
9888
- function collectLayoutElements(scope) {
9889
- const elements = Array.from(scope.querySelectorAll(layoutSelector));
9890
- if (scope instanceof Element && scope.matches(layoutSelector)) {
9891
- if (!elements.includes(scope)) {
9892
- elements.unshift(scope);
9893
- }
9894
- }
9895
- return elements;
9896
- }
9897
- function readLayoutAttributes(element) {
9898
- const layoutId = element.getAttribute("data-layout-id") || undefined;
9899
- const rawLayout = element.getAttribute("data-layout");
9900
- let layout;
9901
- if (rawLayout === "" || rawLayout === "true") {
9902
- layout = true;
9903
- }
9904
- else if (rawLayout) {
9905
- layout = rawLayout;
9906
- }
9907
- return {
9908
- layout,
9909
- layoutId,
9910
- };
9911
- }
9912
- function createVisualState() {
9913
- return {
9914
- latestValues: {},
9915
- renderState: {
9916
- transform: {},
9917
- transformOrigin: {},
9918
- style: {},
9919
- vars: {},
9920
- },
9921
- };
9922
- }
9923
- function getOrCreateRecord(element, parentProjection, projectionOptions) {
9924
- const existing = visualElementStore.get(element);
9925
- const visualElement = existing ??
9926
- new HTMLVisualElement({
9927
- props: {},
9928
- presenceContext: null,
9929
- visualState: createVisualState(),
9930
- }, { allowProjection: true });
9931
- if (!existing || !visualElement.projection) {
9932
- visualElement.projection = new HTMLProjectionNode(visualElement.latestValues, parentProjection);
9933
- }
9934
- visualElement.projection.setOptions({
9935
- ...projectionOptions,
9936
- visualElement,
9937
- });
9938
- if (!visualElement.current) {
9939
- visualElement.mount(element);
9940
- }
9941
- else if (!visualElement.projection.instance) {
9942
- // Mount projection if VisualElement is already mounted but projection isn't
9943
- // This happens when animate() was called before animateLayout()
9944
- visualElement.projection.mount(element);
9945
- }
9946
- if (!existing) {
9947
- visualElementStore.set(element, visualElement);
9948
- }
9949
- return {
9950
- element,
9951
- visualElement,
9952
- projection: visualElement.projection,
9953
- };
9954
- }
9955
- function findParentRecord(element, recordMap, scope) {
9956
- let parent = element.parentElement;
9957
- while (parent) {
9958
- const record = recordMap.get(parent);
9959
- if (record)
9960
- return record;
9961
- if (parent === scope)
9962
- break;
9963
- parent = parent.parentElement;
9964
- }
9965
- return undefined;
9966
- }
9967
- function getProjectionRoot(afterRecords, beforeRecords) {
9968
- const record = afterRecords[0] || beforeRecords[0];
9969
- return record?.projection.root;
9970
- }
9971
- function collectAnimations(afterRecords) {
9972
- const animations = new Set();
9973
- afterRecords.forEach((record) => {
9974
- const animation = record.projection.currentAnimation;
9975
- if (animation)
9976
- animations.add(animation);
9977
- });
9978
- return Array.from(animations);
9979
- }
9980
10546
 
9981
10547
  /**
9982
10548
  * @deprecated
@@ -10017,7 +10583,6 @@ exports.SVGVisualElement = SVGVisualElement;
10017
10583
  exports.ViewTransitionBuilder = ViewTransitionBuilder;
10018
10584
  exports.VisualElement = VisualElement;
10019
10585
  exports.acceleratedValues = acceleratedValues;
10020
- exports.activeAnimations = activeAnimations;
10021
10586
  exports.addAttrValue = addAttrValue;
10022
10587
  exports.addDomEvent = addDomEvent;
10023
10588
  exports.addScaleCorrector = addScaleCorrector;