motion-dom 12.40.0 → 12.42.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 +1114 -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 +123 -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 +514 -83
  29. package/dist/es/view/start.mjs.map +1 -1
  30. package/dist/es/view/utils/assign-names.mjs +146 -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 +135 -52
  39. package/dist/motion-dom.dev.js +1114 -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,154 @@ 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
+ * Set the element's `view-transition-group` so its layer reconstructs the DOM
5339
+ * hierarchy in the pseudo-tree (`contain`) - or stays flat (`none`). Tracked in
5340
+ * `grouped` for cleanup. When the element clips (any non-`visible` overflow) its
5341
+ * name is recorded in `clipChildren` so the caller can clip the nested children
5342
+ * (`::view-transition-group-children(name)`), mirroring the live clip through
5343
+ * the whole transition rather than only at the live-DOM handoff.
5344
+ *
5345
+ * Ignored by browsers without nested view-transition groups, where it harmlessly
5346
+ * degrades to the flat default.
5347
+ */
5348
+ function applyGroup(element, name, group, grouped, clipChildren) {
5349
+ if (!group)
5350
+ return;
5351
+ element.style?.setProperty("view-transition-group", group);
5352
+ grouped.push(element);
5353
+ if (group !== "none" && clipChildren) {
5354
+ const style = getComputedStyle(element);
5355
+ if (style.overflowX !== "visible" || style.overflowY !== "visible") {
5356
+ clipChildren.add(name);
5357
+ }
5358
+ }
5359
+ }
5360
+ /**
5361
+ * Resolve a selector/Element to elements and ensure each one carries a
5362
+ * `view-transition-name` we can target from script.
5363
+ *
5364
+ * Author-defined names are reused as-is. Elements that are unnamed (or use
5365
+ * the browser's `auto`/`match-element`, whose generated name is not exposed
5366
+ * to script) are given a unique generated name, set inline so it's captured,
5367
+ * and tracked in `assigned` for later cleanup.
5368
+ *
5369
+ * `registry` maps each Element to its name so the same element keeps its name
5370
+ * across both captures (before and after the update), which is what allows a
5371
+ * persistent element to animate as a single `group` layer.
5372
+ */
5373
+ function assignViewTransitionNames(definition, registry, assigned, forcedNames, className, classed = [], group, grouped = [], clipChildren) {
5374
+ const elements = resolveElements(definition);
5375
+ /**
5376
+ * The new end of a paired morph: give each element the matching name from
5377
+ * the old end (by index) so the two share one layer and morph. If the new
5378
+ * end resolves to *more* elements than the old end named, the extras have no
5379
+ * counterpart - give them a fresh name so they animate as newcomers rather
5380
+ * than being silently left unnamed. We return the names actually assigned
5381
+ * (sized to the resolved elements), not the raw `forcedNames`, so stagger
5382
+ * totals and the layer set stay in step with what's on the page.
5383
+ */
5384
+ if (forcedNames) {
5385
+ return elements.map((element, i) => {
5386
+ const existing = registry.get(element);
5387
+ if (existing)
5388
+ return existing;
5389
+ const name = forcedNames[i] ?? generatedName();
5390
+ element.style?.setProperty("view-transition-name", name);
5391
+ assigned.push(element);
5392
+ registry.set(element, name);
5393
+ tagClass(element, className, classed);
5394
+ applyGroup(element, name, group, grouped, clipChildren);
5395
+ return name;
5396
+ });
5397
+ }
5398
+ /**
5399
+ * Read every current name up front, before assigning any. Interleaving the
5400
+ * reads with the inline `setProperty` writes below would dirty styles
5401
+ * between reads and force a style recalc per element; batching the reads
5402
+ * keeps it to one. Elements already in the registry keep their name and
5403
+ * need no read.
5404
+ */
5405
+ const currentNames = elements.map((element) => registry.has(element)
5406
+ ? undefined
5407
+ : getComputedStyle(element).getPropertyValue("view-transition-name"));
5408
+ return elements.map((element, i) => {
5409
+ const existing = registry.get(element);
5410
+ if (existing)
5411
+ return existing;
5412
+ const current = currentNames[i];
5413
+ let name;
5414
+ if (current &&
5415
+ current !== "none" &&
5416
+ current !== "auto" &&
5417
+ current !== "match-element" &&
5418
+ !isGeneratedName(current)) {
5419
+ /**
5420
+ * The author already named this layer - target it as-is and leave
5421
+ * it to them to clean up. `auto`/`match-element` are overridden
5422
+ * because their generated name is not exposed to script, and a
5423
+ * stale `motion-view-*` (e.g. left by an interrupted transition) is
5424
+ * re-owned rather than adopted as an author name and leaked.
5425
+ */
5426
+ name = current;
5427
+ }
5428
+ else {
5429
+ name = generatedName();
5430
+ element.style?.setProperty("view-transition-name", name);
5431
+ assigned.push(element);
5432
+ }
5433
+ registry.set(element, name);
5434
+ tagClass(element, className, classed);
5435
+ applyGroup(element, name, group, grouped, clipChildren);
5436
+ return name;
5437
+ });
5438
+ }
5439
+ /**
5440
+ * Remove the `view-transition-name`s we generated and the
5441
+ * `view-transition-class`es we applied. Author-defined names are never touched
5442
+ * (they're not in `assigned`). Safe to call more than once (e.g. on both a
5443
+ * finished and an interrupted transition).
5444
+ */
5445
+ function releaseViewTransitionNames(assigned, classed = [], grouped = []) {
5446
+ for (const element of assigned) {
5447
+ element.style?.removeProperty("view-transition-name");
5448
+ }
5449
+ for (const element of classed) {
5450
+ element.style?.removeProperty("view-transition-class");
5451
+ }
5452
+ for (const element of grouped) {
5453
+ element.style?.removeProperty("view-transition-group");
5454
+ }
5455
+ }
5456
+
5421
5457
  function chooseLayerType(valueName) {
5422
5458
  if (valueName === "layout")
5423
5459
  return "group";
5424
5460
  if (valueName === "enter" || valueName === "new")
5425
5461
  return "new";
5426
- if (valueName === "exit" || valueName === "old")
5427
- return "old";
5428
- return "group";
5462
+ return "old";
5429
5463
  }
5430
5464
 
5431
5465
  let pendingRules = {};
@@ -5460,21 +5494,21 @@ const css = {
5460
5494
  };
5461
5495
 
5462
5496
  function getViewAnimationLayerInfo(pseudoElement) {
5463
- const match = pseudoElement.match(/::view-transition-(old|new|group|image-pair)\((.*?)\)/);
5497
+ const match = pseudoElement.match(
5498
+ // `group-children` (nested transitions) before `group` so it wins.
5499
+ /::view-transition-(old|new|group-children|group|image-pair)\((.*?)\)/);
5464
5500
  if (!match)
5465
5501
  return null;
5466
5502
  return { layer: match[2], type: match[1] };
5467
5503
  }
5468
5504
 
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
5505
  function getViewAnimations() {
5477
- return document.getAnimations().filter(filterViewAnimations);
5506
+ return document.getAnimations().filter((animation) => {
5507
+ const { effect } = animation;
5508
+ return (!!effect &&
5509
+ effect.target === document.documentElement &&
5510
+ effect.pseudoElement?.startsWith("::view-transition"));
5511
+ });
5478
5512
  }
5479
5513
 
5480
5514
  function hasTarget(target, targets) {
@@ -5482,87 +5516,432 @@ function hasTarget(target, targets) {
5482
5516
  }
5483
5517
 
5484
5518
  const definitionNames = ["layout", "enter", "exit", "new", "old"];
5519
+ /**
5520
+ * The `ViewTransitionTarget` buckets driving each generated layer type, in
5521
+ * priority order - the inverse of `chooseLayerType`. The new view is driven by
5522
+ * `new`/`enter`, the old by `old`/`exit`. `group-children`/`image-pair` have no
5523
+ * bucket; they follow the default layout timing.
5524
+ */
5525
+ const typeBuckets = {
5526
+ group: ["layout"],
5527
+ new: ["new", "enter"],
5528
+ old: ["old", "exit"],
5529
+ };
5530
+ /**
5531
+ * Default "absent" origin for a single-value keyframe, by pseudo type, so e.g.
5532
+ * `enter({ scale: 1 })` grows in from 0.85 and `exit({ opacity: 0 })` fades
5533
+ * from 1. `enter` prefers the matching `exit` value over these (see below).
5534
+ */
5535
+ const ORIGIN_DEFAULTS = {
5536
+ new: { opacity: 0, scale: 0.85 },
5537
+ old: { opacity: 1, scale: 1 },
5538
+ };
5539
+ /**
5540
+ * How much two box aspect ratios must differ before a morph is treated as
5541
+ * aspect-changing (and so worth cropping). Matches the projection engine's
5542
+ * `preserve-aspect` threshold, so small layout jitter doesn't trigger a crop.
5543
+ */
5544
+ const ASPECT_TOLERANCE = 0.2;
5485
5545
  function startViewAnimation(builder) {
5486
- const { update, targets, options: defaultOptions } = builder;
5546
+ const { update, targets, resolveDefs, cropOverride, pairs, classNames, flatGroups, options: defaultOptions, } = builder;
5487
5547
  if (!document.startViewTransition) {
5488
- return new Promise(async (resolve) => {
5548
+ // An async IIFE (not `new Promise(async …)`) so a throwing/rejecting
5549
+ // update rejects this promise rather than leaving it unsettled.
5550
+ return (async () => {
5489
5551
  await update();
5490
- resolve(new GroupAnimation([]));
5491
- });
5552
+ return new GroupAnimation([]);
5553
+ })();
5492
5554
  }
5493
- // TODO: Go over existing targets and ensure they all have ids
5494
5555
  /**
5495
- * If we don't have any animations defined for the root target,
5496
- * remove it from being captured.
5556
+ * Resolve any selector/Element targets to layer names, assigning a
5557
+ * `view-transition-name` to each element as we go. We run this before the
5558
+ * update (so the elements are captured in the old snapshot) and again
5559
+ * after it (for the new snapshot). An element present in both keeps the
5560
+ * same name and animates as a single `group` layer.
5561
+ */
5562
+ const nameRegistry = new Map();
5563
+ const assigned = [];
5564
+ /**
5565
+ * Elements we tagged with a `view-transition-class` (via `.class()`),
5566
+ * tracked separately from `assigned` so cleanup removes the class without
5567
+ * ever stripping an author's own inline `view-transition-name`.
5568
+ */
5569
+ const classed = [];
5570
+ /**
5571
+ * Elements we set a `view-transition-group` on (for nesting), tracked for
5572
+ * cleanup. `clipChildren` collects the names of nested parents that clip in
5573
+ * the live layout, so their `::view-transition-group-children` is clipped
5574
+ * through the transition - not just once the live DOM takes back over.
5575
+ */
5576
+ const grouped = [];
5577
+ const clipChildren = new Set();
5578
+ const layerTargets = new Map();
5579
+ const croppedNames = new Set();
5580
+ /**
5581
+ * Each layer's explicit `.crop(true | false)` override (by resolved name),
5582
+ * so `finalizeCrop` can let an author's choice win over the morph default.
5583
+ */
5584
+ const cropForName = new Map();
5585
+ /**
5586
+ * Each layer's stagger position (index + total) within its subject, per
5587
+ * snapshot. Resolving against the snapshot the layer belongs to keeps
5588
+ * stagger correct when `update()` replaces the matched elements, and lets
5589
+ * us skip a layer that's absent from a snapshot (e.g. an exited element
5590
+ * has no `new` pseudo-element).
5591
+ */
5592
+ const layerStagger = new Map();
5593
+ /**
5594
+ * Names allocated for a paired subject in the old snapshot, replayed onto
5595
+ * its new-snapshot target so both ends share a layer and morph.
5497
5596
  */
5498
- if (!hasTarget("root", targets)) {
5499
- css.set(":root", {
5500
- "view-transition-name": "none",
5597
+ const pairNames = new Map();
5598
+ /**
5599
+ * The old (`from`) elements of each paired subject, so their names can be
5600
+ * transferred off before the new (`to`) elements inherit them.
5601
+ */
5602
+ const pairFrom = new Map();
5603
+ const resolveLayers = (phase) => {
5604
+ targets.forEach((target, definition) => {
5605
+ const className = classNames.get(definition);
5606
+ /**
5607
+ * Nest each resolved layer under its DOM-ancestor layer by default
5608
+ * (`contain`), so an ancestor's clip/transform/opacity reach it
5609
+ * through the transition; `.group(false)` opts a subject out (`none`)
5610
+ * to stay flat and escape. Skipped for root / pre-named layers, which
5611
+ * aren't elements we resolve and style.
5612
+ */
5613
+ const group = definition === "root" || !resolveDefs.has(definition)
5614
+ ? undefined
5615
+ : flatGroups.has(definition)
5616
+ ? "none"
5617
+ : "contain";
5618
+ let names;
5619
+ if (definition === "root" || !resolveDefs.has(definition)) {
5620
+ names = [definition];
5621
+ }
5622
+ else if (pairs.has(definition)) {
5623
+ /**
5624
+ * Paired morph: name the old target in the old snapshot, then
5625
+ * force the same name(s) onto the new target in the new one, so
5626
+ * two different elements morph as a single layer.
5627
+ */
5628
+ if (phase === "old") {
5629
+ pairFrom.set(definition, resolveElements(definition));
5630
+ names = assignViewTransitionNames(definition, nameRegistry, assigned, undefined, className, classed, group, grouped, clipChildren);
5631
+ pairNames.set(definition, names);
5632
+ }
5633
+ else {
5634
+ /**
5635
+ * Transfer the name(s) off the `from` elements before the
5636
+ * `to` elements inherit them. A `from` that survives into
5637
+ * the new snapshot (e.g. hidden with `visibility: hidden`
5638
+ * rather than removed) would otherwise keep the name and
5639
+ * collide - "duplicate view-transition-name".
5640
+ */
5641
+ for (const el of pairFrom.get(definition) ?? []) {
5642
+ el.style?.removeProperty("view-transition-name");
5643
+ /**
5644
+ * Drop the old end from the registry too, so the new
5645
+ * end alone supplies this name's `new` crop radii - we
5646
+ * neither re-measure nor get ordered by a stale element.
5647
+ */
5648
+ nameRegistry.delete(el);
5649
+ }
5650
+ names = assignViewTransitionNames(pairs.get(definition), nameRegistry, assigned, pairNames.get(definition), className, classed, group, grouped, clipChildren);
5651
+ }
5652
+ }
5653
+ else {
5654
+ names = assignViewTransitionNames(definition, nameRegistry, assigned, undefined, className, classed, group, grouped, clipChildren);
5655
+ }
5656
+ // Record any explicit `.crop(true | false)` per resolved name; the
5657
+ // crop set itself is computed later by `finalizeCrop` (it needs both
5658
+ // snapshots to know which morphs change aspect ratio).
5659
+ const override = cropOverride.get(definition);
5660
+ names.forEach((name, index) => {
5661
+ /**
5662
+ * If two subjects resolve to the same element, merge their
5663
+ * definitions so neither subject's animations are dropped.
5664
+ */
5665
+ const existing = layerTargets.get(name);
5666
+ layerTargets.set(name, existing && existing !== target
5667
+ ? { ...existing, ...target }
5668
+ : target);
5669
+ if (override !== undefined)
5670
+ cropForName.set(name, override);
5671
+ const stagger = layerStagger.get(name) ?? {};
5672
+ stagger[phase] = [index, names.length];
5673
+ layerStagger.set(name, stagger);
5674
+ });
5501
5675
  });
5502
- }
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.
5507
- *
5508
- * This allows us to set easing via updateTiming - which can be changed.
5678
+ * The stagger index/total for a layer, resolved against the snapshot it
5679
+ * belongs to. Returns index -1 when the layer is absent from that snapshot
5680
+ * so the caller can skip a pseudo-element that doesn't exist.
5509
5681
  */
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
5682
+ const staggerPosition = (name, type) => {
5683
+ const stagger = layerStagger.get(name);
5684
+ const position = type === "old"
5685
+ ? stagger?.old
5686
+ : type === "new"
5687
+ ? stagger?.new
5688
+ : // group / group-children / image-pair persist across both.
5689
+ stagger?.new ?? stagger?.old;
5690
+ return position ?? [-1, 1];
5691
+ };
5692
+ /**
5693
+ * Merge default + per-layer transition options for a generated layer and
5694
+ * resolve any stagger/delay function against this element's position. Used
5695
+ * by both the morph-retiming and crop corner-radius passes.
5696
+ */
5697
+ const resolveLayerTransition = (target, type, transitionName, index, total) => {
5698
+ const transition = mergeTransition(getValueTransition(defaultOptions, transitionName), getValueTransition((layerOptions(target, type) ?? {}), transitionName));
5699
+ if (typeof transition.delay === "function") {
5700
+ transition.delay = transition.delay(index, total);
5701
+ }
5702
+ return transition;
5703
+ };
5704
+ /**
5705
+ * Each layer's box size per snapshot, so `finalizeCrop` can tell whether a
5706
+ * morph's aspect ratio changed (the only case worth cropping).
5707
+ */
5708
+ const cropBox = new Map();
5709
+ const measureLayers = (phase) => nameRegistry.forEach((name, element) => {
5710
+ const rect = element.getBoundingClientRect?.();
5711
+ if (rect && rect.height) {
5712
+ const entry = cropBox.get(name) ?? {};
5713
+ entry[phase] = { width: rect.width, height: rect.height };
5714
+ cropBox.set(name, entry);
5715
+ }
5515
5716
  });
5516
- transition.finished.finally(() => {
5717
+ /**
5718
+ * With both snapshots measured, settle which layers crop. The default crops
5719
+ * only a morph whose aspect ratio *changes* between snapshots - the one case
5720
+ * where `object-fit: cover` does real work. A same-aspect morph or a
5721
+ * fade-only layer is left uncropped: its corners scale naturally (no flash
5722
+ * from squaring, no `overflow: clip` eating its shadow) and a backdrop can't
5723
+ * be clipped to nothing. An explicit `.crop(true | false)` overrides either
5724
+ * way. Runs after both snapshots are measured, since aspect needs both.
5725
+ */
5726
+ const finalizeCrop = () => {
5727
+ croppedNames.clear();
5728
+ for (const name of layerStagger.keys()) {
5729
+ if (name === "root")
5730
+ continue;
5731
+ // An explicit `.crop(true | false)` wins; otherwise crop a morph
5732
+ // whose aspect ratio changed.
5733
+ if (cropForName.get(name) ?? aspectChanged(name)) {
5734
+ croppedNames.add(name);
5735
+ }
5736
+ }
5737
+ };
5738
+ /**
5739
+ * Whether a layer is a morph whose box aspect ratio changed between
5740
+ * snapshots (beyond a small tolerance). Fade-only layers (one snapshot) are
5741
+ * never "changed".
5742
+ */
5743
+ const aspectChanged = (name) => {
5744
+ const box = cropBox.get(name);
5745
+ if (!box?.old || !box?.new || !box.old.height || !box.new.height) {
5746
+ return false;
5747
+ }
5748
+ return (Math.abs(box.old.width / box.old.height -
5749
+ box.new.width / box.new.height) > ASPECT_TOLERANCE);
5750
+ };
5751
+ /**
5752
+ * Write the persistent view-transition CSS: suppress root capture when the
5753
+ * root has no animations of its own; force linear timing (baked into the
5754
+ * keyframes, so we can retime later via updateTiming); and clip +
5755
+ * object-fit: cover every cropped morph (the UA default overflows on
5756
+ * aspect-ratio change).
5757
+ *
5758
+ * `css.commit` replaces rather than appends, so we re-set the full rule set
5759
+ * each call - the crop rules are only known after `finalizeCrop` runs in the
5760
+ * update callback, so the second call writes them.
5761
+ */
5762
+ const commitViewCSS = () => {
5763
+ if (!hasTarget("root", targets)) {
5764
+ css.set(":root", { "view-transition-name": "none" });
5765
+ }
5766
+ css.set("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)", { "animation-timing-function": "linear !important" });
5767
+ croppedNames.forEach((name) => {
5768
+ css.set(`::view-transition-group(${name})`, { overflow: "clip" });
5769
+ css.set(`::view-transition-old(${name}), ::view-transition-new(${name})`, { width: "100%", height: "100%", "object-fit": "cover" });
5770
+ });
5771
+ /**
5772
+ * Clip the nested children of any layer that clips in the live layout,
5773
+ * so a wrapper crops its child for the whole morph (mirroring the DOM)
5774
+ * rather than only at the live-DOM handoff. No-op on browsers without
5775
+ * nested view-transition groups.
5776
+ */
5777
+ clipChildren.forEach((name) => {
5778
+ css.set(`::view-transition-group-children(${name})`, {
5779
+ overflow: "clip",
5780
+ });
5781
+ });
5782
+ css.commit(); // Write
5783
+ };
5784
+ const cleanup = () => {
5785
+ releaseViewTransitionNames(assigned, classed, grouped);
5517
5786
  css.remove(); // Write
5518
- });
5519
- return new Promise((resolve) => {
5520
- transition.ready.then(() => {
5787
+ };
5788
+ const callback = async () => {
5789
+ await update();
5790
+ /**
5791
+ * Re-resolve so elements created by the update are named for the new
5792
+ * snapshot, then measure them. With both snapshots measured we can
5793
+ * settle the crop set (aspect-changing morphs + forced).
5794
+ */
5795
+ resolveLayers("new");
5796
+ measureLayers("new");
5797
+ finalizeCrop();
5798
+ /**
5799
+ * Re-commit the crop CSS unconditionally: `finalizeCrop` is computed
5800
+ * here (after both snapshots are measured), so the clip rules must be
5801
+ * (re)written to match the settled set.
5802
+ */
5803
+ commitViewCSS();
5804
+ };
5805
+ let transition;
5806
+ try {
5807
+ resolveLayers("old");
5808
+ /**
5809
+ * Measure the old snapshot against the optimistic crop set (the new
5810
+ * snapshot doesn't exist yet, so aspect change can't be known here;
5811
+ * `finalizeCrop` settles it post-update).
5812
+ */
5813
+ measureLayers("old");
5814
+ commitViewCSS();
5815
+ transition = document.startViewTransition(callback);
5816
+ }
5817
+ catch (error) {
5818
+ /**
5819
+ * The prelude writes inline names before the transition exists. If it
5820
+ * throws (e.g. startViewTransition rejects in a bad UA state), release
5821
+ * them so we neither leak DOM state nor stall the queue on a promise
5822
+ * that never settles - hand back a rejection it can advance past.
5823
+ */
5824
+ cleanup();
5825
+ return Promise.reject(error);
5826
+ }
5827
+ transition.finished.finally(cleanup);
5828
+ return new Promise((resolve, reject) => {
5829
+ transition.ready
5830
+ .then(() => {
5521
5831
  const generatedViewAnimations = getViewAnimations();
5522
5832
  const animations = [];
5523
5833
  /**
5524
5834
  * Create animations for each of our explicitly-defined subjects.
5835
+ * `opacityAnimated` additionally tracks which `${name}:${type}`
5836
+ * we faded, so we can keep the UA `plus-lighter` blend only for a
5837
+ * genuine opacity crossfade (both sides fading) and drop it for a
5838
+ * slide/transform, where additive compositing would flash bright.
5525
5839
  */
5526
- targets.forEach((definition, target) => {
5527
- // TODO: If target is not "root", resolve elements
5528
- // and iterate over each
5840
+ const explicitlyAnimated = new Set();
5841
+ const opacityAnimated = new Set();
5842
+ layerTargets.forEach((target, name) => {
5843
+ const stagger = layerStagger.get(name);
5844
+ /**
5845
+ * Presence: `enter` only fires for a pure newcomer (a new
5846
+ * view with no old), `exit` only for a pure leaver. A
5847
+ * survivor (both) gets neither - it just morphs.
5848
+ */
5849
+ const enterApplies = !!stagger?.new && !stagger?.old;
5850
+ const exitApplies = !!stagger?.old && !stagger?.new;
5529
5851
  for (const key of definitionNames) {
5530
- if (!definition[key])
5852
+ if (!target[key])
5853
+ continue;
5854
+ if (key === "enter" && !enterApplies)
5855
+ continue;
5856
+ if (key === "exit" && !exitApplies)
5857
+ continue;
5858
+ const type = chooseLayerType(key);
5859
+ const [index, total] = staggerPosition(name, type);
5860
+ // Skip a layer absent from its snapshot.
5861
+ if (index === -1)
5531
5862
  continue;
5532
- const { keyframes, options } = definition[key];
5863
+ const { keyframes, options } = target[key];
5533
5864
  for (let [valueName, valueKeyframes] of Object.entries(keyframes)) {
5534
- if (!valueKeyframes)
5865
+ // Skip only missing values - `0` (e.g. opacity: 0)
5866
+ // is valid and must reach the from-value inference.
5867
+ if (valueKeyframes == null)
5535
5868
  continue;
5536
- const valueOptions = {
5537
- ...getValueTransition(defaultOptions, valueName),
5538
- ...getValueTransition(options, valueName),
5539
- };
5540
- const type = chooseLayerType(key);
5541
5869
  /**
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.
5870
+ * The view path hands keyframes straight to WAAPI,
5871
+ * so Motion's `x`/`y` shorthands (compiled to
5872
+ * `transform` only via the value pipeline) have no
5873
+ * effect. Warn and skip - use `transform`/`translate`.
5874
+ */
5875
+ if (valueName === "x" || valueName === "y") {
5876
+ motionUtils.warnOnce(false, `animateView() animates view-transition layers with CSS properties; the "${valueName}" shorthand has no effect - use transform, e.g. { transform: "translateX(40px)" }.`);
5877
+ continue;
5878
+ }
5879
+ /**
5880
+ * enter/exit win over new/old on a shared property -
5881
+ * skip it here when the gated bucket also defines it.
5882
+ */
5883
+ if (key === "new" &&
5884
+ enterApplies &&
5885
+ target.enter?.keyframes[valueName] != null) {
5886
+ continue;
5887
+ }
5888
+ if (key === "old" &&
5889
+ exitApplies &&
5890
+ target.exit?.keyframes[valueName] != null) {
5891
+ continue;
5892
+ }
5893
+ const valueOptions = mergeTransition(getValueTransition(defaultOptions, valueName), getValueTransition(options, valueName));
5894
+ /**
5895
+ * Infer an origin for a single-value keyframe. An
5896
+ * `enter` mirrors the matching `exit` value (a
5897
+ * defined exit reverses into the enter for free);
5898
+ * otherwise the per-type default (opacity 0/1, scale
5899
+ * 0.85). No default -> left as-is (animates from the
5900
+ * live value).
5901
+ *
5902
+ * `new`/`old` fire for survivors too, where only the
5903
+ * opacity crossfade default applies - a transform
5904
+ * default like scale 0.85 would pop a persisting
5905
+ * element, so gate it on the layer actually
5906
+ * entering/leaving.
5544
5907
  */
5545
- if (valueName === "opacity" &&
5546
- !Array.isArray(valueKeyframes)) {
5547
- const initialValue = type === "new" ? 0 : 1;
5548
- valueKeyframes = [initialValue, valueKeyframes];
5908
+ if (!Array.isArray(valueKeyframes)) {
5909
+ const exitValue = key === "enter"
5910
+ ? target.exit?.keyframes[valueName]
5911
+ : undefined;
5912
+ const allowDefault = valueName === "opacity" ||
5913
+ (type === "new" ? enterApplies : exitApplies);
5914
+ const from = exitValue != null
5915
+ ? Array.isArray(exitValue)
5916
+ ? exitValue[exitValue.length - 1]
5917
+ : exitValue
5918
+ : allowDefault
5919
+ ? ORIGIN_DEFAULTS[type]?.[valueName]
5920
+ : undefined;
5921
+ if (from !== undefined) {
5922
+ valueKeyframes = [from, valueKeyframes];
5923
+ }
5549
5924
  }
5550
5925
  /**
5551
- * Resolve stagger function if provided.
5926
+ * Resolve stagger function if provided, per element
5927
+ * across this subject's resolved layers.
5552
5928
  */
5553
5929
  if (typeof valueOptions.delay === "function") {
5554
- valueOptions.delay = valueOptions.delay(0, 1);
5930
+ valueOptions.delay = valueOptions.delay(index, total);
5555
5931
  }
5556
5932
  valueOptions.duration && (valueOptions.duration = motionUtils.secondsToMilliseconds(valueOptions.duration));
5557
5933
  valueOptions.delay && (valueOptions.delay = motionUtils.secondsToMilliseconds(valueOptions.delay));
5558
- const animation = new NativeAnimation({
5934
+ animations.push(new NativeAnimation({
5559
5935
  ...valueOptions,
5560
5936
  element: document.documentElement,
5561
5937
  name: valueName,
5562
- pseudoElement: `::view-transition-${type}(${target})`,
5938
+ pseudoElement: `::view-transition-${type}(${name})`,
5563
5939
  keyframes: valueKeyframes,
5564
- });
5565
- animations.push(animation);
5940
+ }));
5941
+ explicitlyAnimated.add(`${name}:${type}`);
5942
+ if (valueName === "opacity") {
5943
+ opacityAnimated.add(`${name}:${type}`);
5944
+ }
5566
5945
  }
5567
5946
  }
5568
5947
  });
@@ -5581,45 +5960,129 @@ function startViewAnimation(builder) {
5581
5960
  const name = getViewAnimationLayerInfo(pseudoElement);
5582
5961
  if (!name)
5583
5962
  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();
5963
+ const targetDefinition = layerTargets.get(name.layer);
5964
+ /**
5965
+ * We built our own animation for this layer, so drop the
5966
+ * browser-generated fade we're replacing. The UA
5967
+ * `plus-lighter` blend is a *separate* generated animation on
5968
+ * the same pseudo (it sets `mix-blend-mode` in its keyframes):
5969
+ * keep it *only* for a true opacity crossfade - both sides
5970
+ * fading - so a symmetric crossfade composites without
5971
+ * darkening, but a slide/transform (where both layers stay
5972
+ * opaque and overlap) doesn't flash bright from the addition.
5973
+ */
5974
+ if (explicitlyAnimated.has(`${name.layer}:${name.type}`)) {
5975
+ const isCrossfade = opacityAnimated.has(`${name.layer}:new`) &&
5976
+ opacityAnimated.has(`${name.layer}:old`);
5977
+ if (isCrossfade &&
5978
+ effect
5979
+ .getKeyframes()
5980
+ .some((keyframe) => keyframe.mixBlendMode)) {
5981
+ animations.push(new NativeAnimationWrapper(animation));
5982
+ }
5983
+ else {
5984
+ animation.cancel();
5985
+ }
5986
+ continue;
5615
5987
  }
5988
+ /**
5989
+ * Otherwise retime the browser-generated animation to
5990
+ * Motion's timing. This auto-enables the layout (group)
5991
+ * morph for any resolved/named target, and applies the
5992
+ * default timing to old/new layers we haven't explicitly
5993
+ * overridden.
5994
+ *
5995
+ * group + group-children both follow the layout timing so
5996
+ * the nesting container stays in sync with the morph.
5997
+ */
5998
+ /**
5999
+ * A survivor's old + new are the two halves of one
6000
+ * `plus-lighter` crossfade. They must share identical timing
6001
+ * (so their opacities stay mirrored and sum to 1 - else the
6002
+ * additive blend flashes bright wherever both are partly
6003
+ * visible) and fade linearly (the bounce belongs on the
6004
+ * group's geometry, not the opacity). So time them as the
6005
+ * group, rather than via their own - potentially staggered,
6006
+ * or enter/exit-derived - old/new options.
6007
+ */
6008
+ const stagger = layerStagger.get(name.layer);
6009
+ const isMorphCrossfade = (name.type === "old" || name.type === "new") &&
6010
+ !!stagger?.old &&
6011
+ !!stagger?.new;
6012
+ const timingType = name.type.startsWith("group") || isMorphCrossfade
6013
+ ? "group"
6014
+ : name.type;
6015
+ const [index, total] = staggerPosition(name.layer, timingType);
6016
+ const transitionName = timingType === "group" ? "layout" : "";
6017
+ let animationTransition = resolveLayerTransition(targetDefinition, timingType, transitionName, index === -1 ? 0 : index, total);
6018
+ /**
6019
+ * The crossfade should resolve at the spring's *perceptual*
6020
+ * (visual) duration - the geometry can keep bouncing, but the
6021
+ * opacity shouldn't drag through the settle. So capture
6022
+ * `visualDuration` before `applyGeneratorOptions` replaces it
6023
+ * with the full overshoot duration, and use it for the fade.
6024
+ */
6025
+ const visualDuration = animationTransition.visualDuration;
6026
+ animationTransition.duration && (animationTransition.duration = motionUtils.secondsToMilliseconds(animationTransition.duration));
6027
+ animationTransition =
6028
+ applyGeneratorOptions(animationTransition);
6029
+ const duration = isMorphCrossfade && visualDuration !== undefined
6030
+ ? motionUtils.secondsToMilliseconds(visualDuration)
6031
+ : animationTransition.duration;
6032
+ const easing = isMorphCrossfade
6033
+ ? "linear"
6034
+ : mapEasingToNativeEasing(animationTransition.ease, animationTransition.duration);
6035
+ effect.updateTiming({
6036
+ delay: motionUtils.secondsToMilliseconds(animationTransition.delay ?? 0),
6037
+ duration,
6038
+ easing,
6039
+ });
6040
+ animations.push(new NativeAnimationWrapper(animation));
5616
6041
  }
5617
6042
  resolve(new GroupAnimation(animations));
5618
- });
6043
+ })
6044
+ .catch(() =>
6045
+ /**
6046
+ * `ready` rejects when the transition is skipped - no visual
6047
+ * change, or superseded by an interrupting transition. The DOM
6048
+ * update still applied, so settle with no animations rather than
6049
+ * surfacing it as an error to an awaiting caller. A genuine
6050
+ * failure in `update()` rejects `updateCallbackDone` (already
6051
+ * settled by now), so propagate that instead.
6052
+ */
6053
+ transition.updateCallbackDone.then(() => resolve(new GroupAnimation([])), reject));
5619
6054
  });
5620
6055
  }
5621
- function hasOpacity(target, key) {
5622
- return target?.[key]?.keyframes.opacity;
6056
+ /**
6057
+ * The options that should time a given generated layer type, so a retimed
6058
+ * group/old/new picks up any per-target transition the user provided. Checks
6059
+ * the type's buckets in priority order (e.g. `new` before `enter`).
6060
+ */
6061
+ function layerOptions(target, type) {
6062
+ for (const bucket of typeBuckets[type] ?? []) {
6063
+ const options = target?.[bucket]?.options;
6064
+ if (options)
6065
+ return options;
6066
+ }
6067
+ }
6068
+ /**
6069
+ * Merge a base transition (e.g. the default `options`) with a per-layer/value
6070
+ * override. An explicit `duration` on the override must win over an inherited
6071
+ * generator's own timing: a spring prefers `visualDuration`, and
6072
+ * `spring.applyToOptions` overwrites `duration` with the computed settle time -
6073
+ * so without this the override is silently discarded. Dropping the inherited
6074
+ * `type`/`visualDuration` makes the layer a plain tween of that duration, unless
6075
+ * it asked for its own generator `type`/`visualDuration`.
6076
+ */
6077
+ function mergeTransition(base, override) {
6078
+ const merged = { ...base, ...override };
6079
+ if (override.duration !== undefined) {
6080
+ if (override.visualDuration === undefined)
6081
+ delete merged.visualDuration;
6082
+ if (override.type === undefined)
6083
+ delete merged.type;
6084
+ }
6085
+ return merged;
5623
6086
  }
5624
6087
 
5625
6088
  let builders = [];
@@ -5633,10 +6096,16 @@ function next() {
5633
6096
  function start(builder) {
5634
6097
  motionUtils.removeItem(builders, builder);
5635
6098
  current = builder;
5636
- startViewAnimation(builder).then((animation) => {
6099
+ startViewAnimation(builder)
6100
+ .then((animation) => {
5637
6101
  builder.notifyReady(animation);
5638
- animation.finished.finally(next);
5639
- });
6102
+ return animation.finished;
6103
+ })
6104
+ // A genuinely failed transition (a throwing update) rejects the
6105
+ // builder; a skipped/interrupted one resolves with no animations (see
6106
+ // start.ts). Either way, advance the queue - else later transitions hang.
6107
+ .catch((error) => builder.notifyReject(error))
6108
+ .finally(next);
5640
6109
  }
5641
6110
  function processQueue() {
5642
6111
  /**
@@ -5673,31 +6142,129 @@ class ViewTransitionBuilder {
5673
6142
  constructor(update, options = {}) {
5674
6143
  this.currentSubject = "root";
5675
6144
  this.targets = new Map();
6145
+ /**
6146
+ * Definitions that must be resolved to elements (and assigned a
6147
+ * `view-transition-name`) rather than treated as pre-named layers.
6148
+ */
6149
+ this.resolveDefs = new Set();
6150
+ /**
6151
+ * Per-subject crop override: `true` forces the crop (clip + object-fit:
6152
+ * cover + animated corner radii) on, `false` forces it off. A subject with
6153
+ * no entry uses the default - crop only a genuine morph (a layer present in
6154
+ * both snapshots), so a fade-only enter/exit isn't clipped to nothing.
6155
+ */
6156
+ this.cropOverride = new Map();
6157
+ /**
6158
+ * Subjects paired with a different new-snapshot target (the second `.add()`
6159
+ * argument), so two distinct elements share one name and morph into each
6160
+ * other - a shared-element transition.
6161
+ */
6162
+ this.pairs = new Map();
6163
+ /**
6164
+ * A `view-transition-class` to apply to each subject's resolved elements,
6165
+ * so authors can target the generated layers from CSS by class rather than
6166
+ * the opaque generated name.
6167
+ */
6168
+ this.classNames = new Map();
6169
+ /**
6170
+ * Subjects opted out of automatic group nesting via `.group(false)`. Their
6171
+ * layer stays a flat top-level group (`view-transition-group: none`) instead
6172
+ * of nesting under its DOM-ancestor layer - so it animates independently and
6173
+ * escapes an ancestor's clip/transform (e.g. an element that lifts out of a
6174
+ * card and flies across, which nesting would clip to the card).
6175
+ */
6176
+ this.flatGroups = new Set();
5676
6177
  this.notifyReady = motionUtils.noop;
5677
- this.readyPromise = new Promise((resolve) => {
6178
+ this.notifyReject = motionUtils.noop;
6179
+ this.readyPromise = new Promise((resolve, reject) => {
5678
6180
  this.notifyReady = resolve;
6181
+ this.notifyReject = reject;
5679
6182
  });
5680
6183
  this.update = update;
5681
6184
  this.options = {
5682
6185
  interrupt: "wait",
5683
6186
  ...options,
5684
6187
  };
6188
+ // Avoid an unhandled rejection when a failed transition has no
6189
+ // `.then(_, reject)` handler attached (e.g. fire-and-forget).
6190
+ this.readyPromise.catch(motionUtils.noop);
5685
6191
  addToQueue(this);
5686
6192
  }
5687
- get(subject) {
6193
+ /**
6194
+ * Target elements resolved from a selector or Element, each assigned a
6195
+ * `view-transition-name` automatically.
6196
+ *
6197
+ * Passing a second target pairs them: the first is resolved in the old
6198
+ * snapshot and the second in the new, sharing one name so two *different*
6199
+ * elements morph into each other (e.g. `.add(card, ".modal")`). Symmetric -
6200
+ * pass them the other way round to morph back.
6201
+ */
6202
+ add(subject, newSubject) {
5688
6203
  this.currentSubject = subject;
6204
+ this.resolveDefs.add(subject);
6205
+ if (newSubject !== undefined)
6206
+ this.pairs.set(subject, newSubject);
6207
+ // Register the subject so it participates (and gets an automatic
6208
+ // layout/morph animation) even without an explicit enter/exit/layout.
6209
+ if (!this.targets.has(subject))
6210
+ this.targets.set(subject, {});
5689
6211
  return this;
5690
6212
  }
5691
- layout(keyframes, options) {
5692
- this.updateTarget("layout", keyframes, options);
6213
+ /**
6214
+ * Control this subject's crop (clip + `object-fit: cover` + animated
6215
+ * corners). By default a subject auto-crops only when it actually morphs -
6216
+ * present in both snapshots (a survivor, or an `.add(a, b)` pair). A
6217
+ * fade-only enter/exit has no second box to crop against, so it's left to
6218
+ * the browser default; in particular the `overflow: clip` a crop adds would
6219
+ * otherwise clip a mis-sized enter/exit layer to nothing.
6220
+ *
6221
+ * `.crop(false)` forces the crop off (e.g. a text morph, where
6222
+ * `object-fit: cover` clips glyphs as the box grows); `.crop(true)` forces
6223
+ * it on for a non-morph the default wouldn't otherwise crop.
6224
+ */
6225
+ crop(enabled = true) {
6226
+ this.cropOverride.set(this.currentSubject, enabled);
5693
6227
  return this;
5694
6228
  }
5695
- new(keyframes, options) {
5696
- this.updateTarget("new", keyframes, options);
6229
+ /**
6230
+ * By default a subject's layer nests under its nearest DOM-ancestor layer
6231
+ * (`view-transition-group: contain`), so the ancestor's clip/transform/opacity
6232
+ * apply to it through the transition - mirroring how the DOM actually paints,
6233
+ * and letting a wrapper crop its child for the whole morph rather than only
6234
+ * once the live DOM takes back over. (Needs a browser that supports nested
6235
+ * view-transition groups; elsewhere it degrades to the flat default.)
6236
+ *
6237
+ * Call `.group(false)` to opt out: the layer stays flat and top-level, so it
6238
+ * animates independently and escapes an ancestor's clip - e.g. an element
6239
+ * that should lift out of a card and fly across, which nesting would clip.
6240
+ */
6241
+ group(enabled = true) {
6242
+ enabled
6243
+ ? this.flatGroups.delete(this.currentSubject)
6244
+ : this.flatGroups.add(this.currentSubject);
5697
6245
  return this;
5698
6246
  }
5699
- old(keyframes, options) {
5700
- this.updateTarget("old", keyframes, options);
6247
+ /**
6248
+ * Tag this subject's generated layers with a `view-transition-class`, so
6249
+ * they can be targeted from CSS - `::view-transition-group(.name)`,
6250
+ * `::view-transition-old/new(.name)`, `::view-transition-image-pair(.name)`
6251
+ * - without the opaque generated `view-transition-name`. Because `.add()`
6252
+ * can match many elements, a shared class targets them all at once (and,
6253
+ * for a pair, both ends). The escape hatch for z-index / custom keyframes
6254
+ * on a morph layer.
6255
+ */
6256
+ class(name) {
6257
+ this.classNames.set(this.currentSubject, name);
6258
+ return this;
6259
+ }
6260
+ /**
6261
+ * Set the transition for this subject's morph. The morph is enabled
6262
+ * automatically by `.add()`; this just customises its timing (duration,
6263
+ * easing, a `delay`/`stagger`, …). On the implicit `root` subject it also
6264
+ * opts the page into the transition (the root crossfade).
6265
+ */
6266
+ layout(options = {}) {
6267
+ this.updateTarget("layout", {}, options);
5701
6268
  return this;
5702
6269
  }
5703
6270
  enter(keyframes, options) {
@@ -5708,9 +6275,21 @@ class ViewTransitionBuilder {
5708
6275
  this.updateTarget("exit", keyframes, options);
5709
6276
  return this;
5710
6277
  }
5711
- crossfade(options) {
5712
- this.updateTarget("enter", { opacity: 1 }, options);
5713
- this.updateTarget("exit", { opacity: 0 }, options);
6278
+ /**
6279
+ * Animate the new view directly, whether the element is appearing or
6280
+ * persisting (unlike `.enter()`, which only fires for a pure newcomer).
6281
+ * Pair with `.old()` for a crossfade or slide-through.
6282
+ */
6283
+ new(keyframes, options) {
6284
+ this.updateTarget("new", keyframes, options);
6285
+ return this;
6286
+ }
6287
+ /**
6288
+ * Animate the old view directly, whether the element is leaving or
6289
+ * persisting (unlike `.exit()`, which only fires for a pure leaver).
6290
+ */
6291
+ old(keyframes, options) {
6292
+ this.updateTarget("old", keyframes, options);
5714
6293
  return this;
5715
6294
  }
5716
6295
  updateTarget(target, keyframes, options = {}) {
@@ -5725,8 +6304,8 @@ class ViewTransitionBuilder {
5725
6304
  return this.readyPromise.then(resolve, reject);
5726
6305
  }
5727
6306
  }
5728
- function animateView(update, defaultOptions = {}) {
5729
- return new ViewTransitionBuilder(update, defaultOptions);
6307
+ function animateView(update, options = {}) {
6308
+ return new ViewTransitionBuilder(update, options);
5730
6309
  }
5731
6310
 
5732
6311
  const createAxisDelta = () => ({
@@ -7846,7 +8425,7 @@ function animateSingleValue(value, keyframes, options) {
7846
8425
 
7847
8426
  function addDomEvent(target, eventName, handler, options = { passive: true }) {
7848
8427
  target.addEventListener(eventName, handler, options);
7849
- return () => target.removeEventListener(eventName, handler);
8428
+ return () => target.removeEventListener(eventName, handler, options);
7850
8429
  }
7851
8430
 
7852
8431
  const compareByDepth = (a, b) => a.depth - b.depth;
@@ -9116,7 +9695,6 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
9116
9695
  */
9117
9696
  this.pendingAnimation = frame.update(() => {
9118
9697
  globalProjectionState.hasAnimatedSinceResize = true;
9119
- activeAnimations.layout++;
9120
9698
  this.motionValue || (this.motionValue = motionValue(0));
9121
9699
  this.motionValue.jump(0, false);
9122
9700
  this.currentAnimation = animateSingleValue(this.motionValue, [0, 1000], {
@@ -9127,11 +9705,7 @@ function createProjectionNode({ attachResizeListener, defaultParent, measureScro
9127
9705
  this.mixTargetDelta(latest);
9128
9706
  options.onUpdate && options.onUpdate(latest);
9129
9707
  },
9130
- onStop: () => {
9131
- activeAnimations.layout--;
9132
- },
9133
9708
  onComplete: () => {
9134
- activeAnimations.layout--;
9135
9709
  options.onComplete && options.onComplete();
9136
9710
  this.completeAnimation();
9137
9711
  },
@@ -9720,39 +10294,221 @@ const HTMLProjectionNode = createProjectionNode({
9720
10294
  checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"),
9721
10295
  });
9722
10296
 
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);
10297
+ const layoutSelector = "[data-layout],[data-layout-id]";
10298
+ /**
10299
+ * All imperatively-created projection nodes live in one persistent tree,
10300
+ * shared across animateLayout() calls (and with any React-created nodes,
10301
+ * via the singleton document root). Keyed by element for reuse.
10302
+ */
10303
+ const layoutNodes = new WeakMap();
10304
+ /**
10305
+ * Builders created within the same synchronous tick are flushed together
10306
+ * as a single "commit": every node is snapshotted before any updateDom
10307
+ * runs, mirroring React batching renders from different parts of the tree.
10308
+ */
10309
+ let pendingBuilders;
10310
+ function collectLayoutElements(scope) {
10311
+ const elements = [];
10312
+ if (scope instanceof HTMLElement && scope.matches(layoutSelector)) {
10313
+ elements.push(scope);
10314
+ }
10315
+ scope.querySelectorAll(layoutSelector).forEach((element) => {
10316
+ if (element instanceof HTMLElement)
10317
+ elements.push(element);
10318
+ });
10319
+ return elements;
10320
+ }
10321
+ /**
10322
+ * Process any work scheduled on the frameloop now. A previous animation
10323
+ * may have been seeked while paused (controls.time = x) without a frame
10324
+ * having rendered it - we must materialise that state into the DOM
10325
+ * before taking snapshots.
10326
+ */
10327
+ function flushPendingFrame() {
10328
+ if (frameData.isProcessing)
10329
+ return;
10330
+ const now = time.now();
10331
+ frameData.delta = motionUtils.clamp(0, 1000 / 60, now - frameData.timestamp);
10332
+ frameData.timestamp = now;
10333
+ frameData.isProcessing = true;
10334
+ frameSteps.update.process(frameData);
10335
+ frameSteps.preRender.process(frameData);
10336
+ frameSteps.render.process(frameData);
10337
+ frameData.isProcessing = false;
10338
+ }
10339
+ function getProjectionParent(element) {
10340
+ let ancestor = element.parentElement;
10341
+ while (ancestor) {
10342
+ const node = layoutNodes.get(ancestor);
10343
+ if (node && node.instance)
10344
+ return node;
10345
+ ancestor = ancestor.parentElement;
10346
+ }
10347
+ return undefined;
10348
+ }
10349
+ function createVisualElement() {
10350
+ return new HTMLVisualElement({
10351
+ props: {},
10352
+ presenceContext: null,
10353
+ visualState: {
10354
+ latestValues: {},
10355
+ renderState: {
10356
+ transform: {},
10357
+ transformOrigin: {},
10358
+ style: {},
10359
+ vars: {},
10360
+ },
10361
+ },
10362
+ }, { allowProjection: true });
10363
+ }
10364
+ function readNodeOptions(element, transition) {
10365
+ const layoutAttr = element.getAttribute("data-layout");
10366
+ const layoutId = element.getAttribute("data-layout-id") ?? undefined;
9733
10367
  return {
9734
- animationId: projection.root?.animationId ?? 0,
9735
- measuredBox,
9736
- layoutBox,
9737
- latestValues: projection.animationValues || projection.latestValues || {},
9738
- source: projection.id,
10368
+ layoutId,
10369
+ layout: layoutAttr !== null ? true : undefined,
10370
+ animationType: (!layoutAttr || layoutAttr === "true"
10371
+ ? "both"
10372
+ : layoutAttr),
10373
+ transition,
10374
+ };
10375
+ }
10376
+ function prepareNode(element, transition) {
10377
+ let node = layoutNodes.get(element);
10378
+ if (!node) {
10379
+ let visualElement = visualElementStore.get(element);
10380
+ if (!visualElement)
10381
+ visualElement = createVisualElement();
10382
+ /**
10383
+ * A first-time element may carry a projection transform in its
10384
+ * inline style (e.g. it was cloned from an element mid-animation).
10385
+ * That transform isn't tracked in latestValues so the engine can't
10386
+ * reset it before measuring - clear it now so the first layout
10387
+ * measurement isn't inflated.
10388
+ */
10389
+ if (element.style.transform &&
10390
+ !hasTransform(visualElement.latestValues)) {
10391
+ element.style.transform = "";
10392
+ }
10393
+ node = new HTMLProjectionNode(visualElement.latestValues, getProjectionParent(element));
10394
+ visualElement.projection = node;
10395
+ node.setOptions({
10396
+ ...readNodeOptions(element, transition),
10397
+ visualElement,
10398
+ });
10399
+ node.mount(element);
10400
+ layoutNodes.set(element, node);
10401
+ }
10402
+ else {
10403
+ node.setOptions(readNodeOptions(element, transition));
10404
+ }
10405
+ node.isPresent = true;
10406
+ if (node.options.onExitComplete) {
10407
+ node.setOptions({ onExitComplete: undefined });
10408
+ }
10409
+ return node;
10410
+ }
10411
+ function sortDocumentOrder(elements) {
10412
+ return [...elements].sort((a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
10413
+ }
10414
+ function dropNode(element, node) {
10415
+ node.setOptions({ onExitComplete: undefined });
10416
+ /**
10417
+ * Stop any lingering animation so it can't leak into future updates.
10418
+ * A follow node can share its currentAnimation with a surviving lead
10419
+ * (via resumingFrom), in which case it isn't ours to stop.
10420
+ */
10421
+ const stack = node.getStack();
10422
+ if (!stack || node.isLead())
10423
+ node.currentAnimation?.stop();
10424
+ node.unmount();
10425
+ layoutNodes.delete(element);
10426
+ }
10427
+ function flushPendingBuilders() {
10428
+ const builders = pendingBuilders;
10429
+ pendingBuilders = undefined;
10430
+ flushPendingFrame();
10431
+ /**
10432
+ * Discover and mount every node across all builders before snapshotting
10433
+ * any of them. Mounting during an active update flags isLayoutDirty,
10434
+ * which would make that node's own willUpdate skip its snapshot.
10435
+ * Document order guarantees ancestors mount before descendants, even
10436
+ * when they're discovered by different builders.
10437
+ */
10438
+ const targets = new Map();
10439
+ for (const builder of builders) {
10440
+ for (const element of builder.collectTargets()) {
10441
+ const owners = targets.get(element);
10442
+ owners ? owners.push(builder) : targets.set(element, [builder]);
10443
+ }
10444
+ }
10445
+ const union = new Map();
10446
+ for (const element of sortDocumentOrder(targets.keys())) {
10447
+ const owners = targets.get(element);
10448
+ const node = prepareNode(element, owners[owners.length - 1].transitionFor(element));
10449
+ for (const owner of owners)
10450
+ owner.adopt(element, node);
10451
+ union.set(element, node);
10452
+ }
10453
+ union.forEach((node) => {
10454
+ node.isLayoutDirty = false;
10455
+ node.willUpdate();
10456
+ });
10457
+ const updatePromises = [];
10458
+ for (const builder of builders) {
10459
+ const result = builder.runUpdate();
10460
+ if (result)
10461
+ updatePromises.push(result);
10462
+ }
10463
+ const commit = () => {
10464
+ /**
10465
+ * Process all additions before any removals so that, even across
10466
+ * builders, a removed member knows whether a replacement with the
10467
+ * same layoutId was added in this commit.
10468
+ */
10469
+ const newMemberIds = new Set();
10470
+ for (const builder of builders) {
10471
+ builder.reconcileAdditions(newMemberIds);
10472
+ }
10473
+ for (const builder of builders) {
10474
+ builder.reconcileRemovals(newMemberIds);
10475
+ }
10476
+ let root;
10477
+ union.forEach((node) => (root || (root = node.root)));
10478
+ for (const builder of builders)
10479
+ root || (root = builder.getRoot());
10480
+ root?.didUpdate();
10481
+ /**
10482
+ * The root flushes the update on a microtask, synchronously
10483
+ * processing the frame that creates the layout animations. Collect
10484
+ * them in a later microtask step of the same pass.
10485
+ */
10486
+ microtask.render(() => {
10487
+ for (const builder of builders)
10488
+ builder.finalize();
10489
+ });
9739
10490
  };
10491
+ updatePromises.length ? Promise.all(updatePromises).then(commit) : commit();
9740
10492
  }
9741
10493
  class LayoutAnimationBuilder {
9742
10494
  constructor(scope, updateDom, defaultOptions) {
9743
- this.sharedTransitions = new Map();
9744
- this.notifyReady = noop;
9745
- this.rejectReady = noop;
9746
10495
  this.scope = scope;
9747
10496
  this.updateDom = updateDom;
9748
10497
  this.defaultOptions = defaultOptions;
10498
+ this.sharedTransitions = new Map();
10499
+ this.notifyReady = () => { };
10500
+ this.rejectReady = () => { };
10501
+ this.tracked = new Map();
10502
+ this.restorePoints = new Map();
9749
10503
  this.readyPromise = new Promise((resolve, reject) => {
9750
10504
  this.notifyReady = resolve;
9751
10505
  this.rejectReady = reject;
9752
10506
  });
9753
- frame.postRender(() => {
9754
- this.start().then(this.notifyReady).catch(this.rejectReady);
9755
- });
10507
+ if (!pendingBuilders) {
10508
+ pendingBuilders = [];
10509
+ queueMicrotask(flushPendingBuilders);
10510
+ }
10511
+ pendingBuilders.push(this);
9756
10512
  }
9757
10513
  shared(id, transition) {
9758
10514
  this.sharedTransitions.set(id, transition);
@@ -9761,114 +10517,107 @@ class LayoutAnimationBuilder {
9761
10517
  then(resolve, reject) {
9762
10518
  return this.readyPromise.then(resolve, reject);
9763
10519
  }
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();
10520
+ transitionFor(element) {
10521
+ const layoutId = element.getAttribute("data-layout-id");
10522
+ return ((layoutId && this.sharedTransitions.get(layoutId)) ||
10523
+ this.defaultOptions);
10524
+ }
10525
+ adopt(element, node) {
10526
+ this.tracked.set(element, node);
10527
+ this.restorePoints.set(element, {
10528
+ parent: element.parentElement,
10529
+ next: element.nextSibling,
9785
10530
  });
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 = "";
10531
+ }
10532
+ collectTargets() {
10533
+ return collectLayoutElements(this.scope);
10534
+ }
10535
+ runUpdate() {
10536
+ try {
10537
+ const result = this.updateDom();
10538
+ if (result && typeof result.then === "function") {
10539
+ return result.then(undefined, (error) => {
10540
+ this.updateError = error;
10541
+ });
9805
10542
  }
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;
10543
+ }
10544
+ catch (error) {
10545
+ this.updateError = error;
10546
+ }
10547
+ return undefined;
9818
10548
  }
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);
10549
+ reconcileAdditions(newMemberIds) {
10550
+ for (const element of collectLayoutElements(this.scope)) {
10551
+ if (this.tracked.has(element))
10552
+ continue;
10553
+ const node = prepareNode(element, this.transitionFor(element));
10554
+ this.adopt(element, node);
10555
+ node.options.layoutId && newMemberIds.add(node.options.layoutId);
9837
10556
  }
9838
- return records;
9839
10557
  }
9840
- handleExitingElements(beforeRecords, afterRecords) {
9841
- const afterElementsSet = new Set(afterRecords.map((record) => record.element));
9842
- beforeRecords.forEach((record) => {
9843
- if (afterElementsSet.has(record.element))
10558
+ reconcileRemovals(newMemberIds) {
10559
+ this.tracked.forEach((node, element) => {
10560
+ if (element.isConnected)
9844
10561
  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);
10562
+ const restore = this.restorePoints.get(element);
10563
+ this.restorePoints.delete(element);
10564
+ const { layoutId } = node.options;
10565
+ const stack = node.getStack();
10566
+ const hasSurvivor = stack &&
10567
+ stack.members.some((member) => member !== node &&
10568
+ member.instance
10569
+ ?.isConnected);
10570
+ /**
10571
+ * A removed lead with a surviving stack member - and no
10572
+ * replacement member added this commit - runs an exit
10573
+ * crossfade: restore the element to its old position in the
10574
+ * DOM, relegate it and let the survivor take over. It's
10575
+ * removed again once the animation completes.
10576
+ */
10577
+ if (layoutId &&
10578
+ node.isLead() &&
10579
+ hasSurvivor &&
10580
+ !newMemberIds.has(layoutId)) {
10581
+ if (restore && restore.parent.isConnected) {
10582
+ restore.parent.insertBefore(element, restore.next && restore.next.parentNode === restore.parent
10583
+ ? restore.next
10584
+ : null);
10585
+ node.isPresent = false;
10586
+ node.setOptions({
10587
+ onExitComplete: () => {
10588
+ element.remove();
10589
+ dropNode(element, node);
10590
+ },
10591
+ });
10592
+ if (node.relegate())
10593
+ return;
10594
+ element.remove();
10595
+ }
10596
+ }
10597
+ dropNode(element, node);
10598
+ this.tracked.delete(element);
9853
10599
  });
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;
10600
+ }
10601
+ getRoot() {
10602
+ let root;
10603
+ this.tracked.forEach((node) => (root || (root = node.root)));
10604
+ return root;
10605
+ }
10606
+ finalize() {
10607
+ if (this.updateError) {
10608
+ this.rejectReady(this.updateError);
10609
+ return;
10610
+ }
10611
+ const animations = new Set();
10612
+ this.tracked.forEach((node) => {
10613
+ if (node.instance && node.currentAnimation) {
10614
+ animations.add(node.currentAnimation);
9866
10615
  }
9867
10616
  });
10617
+ this.notifyReady(new GroupAnimation([...animations]));
9868
10618
  }
9869
10619
  }
9870
10620
  function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9871
- // animateLayout(updateDom)
9872
10621
  if (typeof scopeOrUpdateDom === "function") {
9873
10622
  return {
9874
10623
  scope: document,
@@ -9876,107 +10625,15 @@ function parseAnimateLayoutArgs(scopeOrUpdateDom, updateDomOrOptions, options) {
9876
10625
  defaultOptions: updateDomOrOptions,
9877
10626
  };
9878
10627
  }
9879
- // animateLayout(scope, updateDom, options?)
9880
- const elements = resolveElements(scopeOrUpdateDom);
9881
- const scope = elements[0] || document;
10628
+ const scope = scopeOrUpdateDom instanceof Document
10629
+ ? scopeOrUpdateDom
10630
+ : resolveElements(scopeOrUpdateDom)[0] ?? document;
9882
10631
  return {
9883
10632
  scope,
9884
10633
  updateDom: updateDomOrOptions,
9885
10634
  defaultOptions: options,
9886
10635
  };
9887
10636
  }
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
10637
 
9981
10638
  /**
9982
10639
  * @deprecated
@@ -10017,7 +10674,6 @@ exports.SVGVisualElement = SVGVisualElement;
10017
10674
  exports.ViewTransitionBuilder = ViewTransitionBuilder;
10018
10675
  exports.VisualElement = VisualElement;
10019
10676
  exports.acceleratedValues = acceleratedValues;
10020
- exports.activeAnimations = activeAnimations;
10021
10677
  exports.addAttrValue = addAttrValue;
10022
10678
  exports.addDomEvent = addDomEvent;
10023
10679
  exports.addScaleCorrector = addScaleCorrector;