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
@@ -1,10 +1,12 @@
1
- import { secondsToMilliseconds } from 'motion-utils';
1
+ import { warnOnce, secondsToMilliseconds } from 'motion-utils';
2
2
  import { GroupAnimation } from '../animation/GroupAnimation.mjs';
3
3
  import { NativeAnimation } from '../animation/NativeAnimation.mjs';
4
4
  import { NativeAnimationWrapper } from '../animation/NativeAnimationWrapper.mjs';
5
5
  import { getValueTransition } from '../animation/utils/get-value-transition.mjs';
6
6
  import { mapEasingToNativeEasing } from '../animation/waapi/easing/map-easing.mjs';
7
7
  import { applyGeneratorOptions } from '../animation/waapi/utils/apply-generator.mjs';
8
+ import { resolveElements } from '../utils/resolve-elements.mjs';
9
+ import { assignViewTransitionNames, releaseViewTransitionNames } from './utils/assign-names.mjs';
8
10
  import { chooseLayerType } from './utils/choose-layer-type.mjs';
9
11
  import { css } from './utils/css.mjs';
10
12
  import { getViewAnimationLayerInfo } from './utils/get-layer-info.mjs';
@@ -12,87 +14,432 @@ import { getViewAnimations } from './utils/get-view-animations.mjs';
12
14
  import { hasTarget } from './utils/has-target.mjs';
13
15
 
14
16
  const definitionNames = ["layout", "enter", "exit", "new", "old"];
17
+ /**
18
+ * The `ViewTransitionTarget` buckets driving each generated layer type, in
19
+ * priority order - the inverse of `chooseLayerType`. The new view is driven by
20
+ * `new`/`enter`, the old by `old`/`exit`. `group-children`/`image-pair` have no
21
+ * bucket; they follow the default layout timing.
22
+ */
23
+ const typeBuckets = {
24
+ group: ["layout"],
25
+ new: ["new", "enter"],
26
+ old: ["old", "exit"],
27
+ };
28
+ /**
29
+ * Default "absent" origin for a single-value keyframe, by pseudo type, so e.g.
30
+ * `enter({ scale: 1 })` grows in from 0.85 and `exit({ opacity: 0 })` fades
31
+ * from 1. `enter` prefers the matching `exit` value over these (see below).
32
+ */
33
+ const ORIGIN_DEFAULTS = {
34
+ new: { opacity: 0, scale: 0.85 },
35
+ old: { opacity: 1, scale: 1 },
36
+ };
37
+ /**
38
+ * How much two box aspect ratios must differ before a morph is treated as
39
+ * aspect-changing (and so worth cropping). Matches the projection engine's
40
+ * `preserve-aspect` threshold, so small layout jitter doesn't trigger a crop.
41
+ */
42
+ const ASPECT_TOLERANCE = 0.2;
15
43
  function startViewAnimation(builder) {
16
- const { update, targets, options: defaultOptions } = builder;
44
+ const { update, targets, resolveDefs, cropOverride, pairs, classNames, flatGroups, options: defaultOptions, } = builder;
17
45
  if (!document.startViewTransition) {
18
- return new Promise(async (resolve) => {
46
+ // An async IIFE (not `new Promise(async …)`) so a throwing/rejecting
47
+ // update rejects this promise rather than leaving it unsettled.
48
+ return (async () => {
19
49
  await update();
20
- resolve(new GroupAnimation([]));
21
- });
50
+ return new GroupAnimation([]);
51
+ })();
22
52
  }
23
- // TODO: Go over existing targets and ensure they all have ids
24
53
  /**
25
- * If we don't have any animations defined for the root target,
26
- * remove it from being captured.
54
+ * Resolve any selector/Element targets to layer names, assigning a
55
+ * `view-transition-name` to each element as we go. We run this before the
56
+ * update (so the elements are captured in the old snapshot) and again
57
+ * after it (for the new snapshot). An element present in both keeps the
58
+ * same name and animates as a single `group` layer.
59
+ */
60
+ const nameRegistry = new Map();
61
+ const assigned = [];
62
+ /**
63
+ * Elements we tagged with a `view-transition-class` (via `.class()`),
64
+ * tracked separately from `assigned` so cleanup removes the class without
65
+ * ever stripping an author's own inline `view-transition-name`.
66
+ */
67
+ const classed = [];
68
+ /**
69
+ * Elements we set a `view-transition-group` on (for nesting), tracked for
70
+ * cleanup. `clipChildren` collects the names of nested parents that clip in
71
+ * the live layout, so their `::view-transition-group-children` is clipped
72
+ * through the transition - not just once the live DOM takes back over.
27
73
  */
28
- if (!hasTarget("root", targets)) {
29
- css.set(":root", {
30
- "view-transition-name": "none",
74
+ const grouped = [];
75
+ const clipChildren = new Set();
76
+ const layerTargets = new Map();
77
+ const croppedNames = new Set();
78
+ /**
79
+ * Each layer's explicit `.crop(true | false)` override (by resolved name),
80
+ * so `finalizeCrop` can let an author's choice win over the morph default.
81
+ */
82
+ const cropForName = new Map();
83
+ /**
84
+ * Each layer's stagger position (index + total) within its subject, per
85
+ * snapshot. Resolving against the snapshot the layer belongs to keeps
86
+ * stagger correct when `update()` replaces the matched elements, and lets
87
+ * us skip a layer that's absent from a snapshot (e.g. an exited element
88
+ * has no `new` pseudo-element).
89
+ */
90
+ const layerStagger = new Map();
91
+ /**
92
+ * Names allocated for a paired subject in the old snapshot, replayed onto
93
+ * its new-snapshot target so both ends share a layer and morph.
94
+ */
95
+ const pairNames = new Map();
96
+ /**
97
+ * The old (`from`) elements of each paired subject, so their names can be
98
+ * transferred off before the new (`to`) elements inherit them.
99
+ */
100
+ const pairFrom = new Map();
101
+ const resolveLayers = (phase) => {
102
+ targets.forEach((target, definition) => {
103
+ const className = classNames.get(definition);
104
+ /**
105
+ * Nest each resolved layer under its DOM-ancestor layer by default
106
+ * (`contain`), so an ancestor's clip/transform/opacity reach it
107
+ * through the transition; `.group(false)` opts a subject out (`none`)
108
+ * to stay flat and escape. Skipped for root / pre-named layers, which
109
+ * aren't elements we resolve and style.
110
+ */
111
+ const group = definition === "root" || !resolveDefs.has(definition)
112
+ ? undefined
113
+ : flatGroups.has(definition)
114
+ ? "none"
115
+ : "contain";
116
+ let names;
117
+ if (definition === "root" || !resolveDefs.has(definition)) {
118
+ names = [definition];
119
+ }
120
+ else if (pairs.has(definition)) {
121
+ /**
122
+ * Paired morph: name the old target in the old snapshot, then
123
+ * force the same name(s) onto the new target in the new one, so
124
+ * two different elements morph as a single layer.
125
+ */
126
+ if (phase === "old") {
127
+ pairFrom.set(definition, resolveElements(definition));
128
+ names = assignViewTransitionNames(definition, nameRegistry, assigned, undefined, className, classed, group, grouped, clipChildren);
129
+ pairNames.set(definition, names);
130
+ }
131
+ else {
132
+ /**
133
+ * Transfer the name(s) off the `from` elements before the
134
+ * `to` elements inherit them. A `from` that survives into
135
+ * the new snapshot (e.g. hidden with `visibility: hidden`
136
+ * rather than removed) would otherwise keep the name and
137
+ * collide - "duplicate view-transition-name".
138
+ */
139
+ for (const el of pairFrom.get(definition) ?? []) {
140
+ el.style?.removeProperty("view-transition-name");
141
+ /**
142
+ * Drop the old end from the registry too, so the new
143
+ * end alone supplies this name's `new` crop radii - we
144
+ * neither re-measure nor get ordered by a stale element.
145
+ */
146
+ nameRegistry.delete(el);
147
+ }
148
+ names = assignViewTransitionNames(pairs.get(definition), nameRegistry, assigned, pairNames.get(definition), className, classed, group, grouped, clipChildren);
149
+ }
150
+ }
151
+ else {
152
+ names = assignViewTransitionNames(definition, nameRegistry, assigned, undefined, className, classed, group, grouped, clipChildren);
153
+ }
154
+ // Record any explicit `.crop(true | false)` per resolved name; the
155
+ // crop set itself is computed later by `finalizeCrop` (it needs both
156
+ // snapshots to know which morphs change aspect ratio).
157
+ const override = cropOverride.get(definition);
158
+ names.forEach((name, index) => {
159
+ /**
160
+ * If two subjects resolve to the same element, merge their
161
+ * definitions so neither subject's animations are dropped.
162
+ */
163
+ const existing = layerTargets.get(name);
164
+ layerTargets.set(name, existing && existing !== target
165
+ ? { ...existing, ...target }
166
+ : target);
167
+ if (override !== undefined)
168
+ cropForName.set(name, override);
169
+ const stagger = layerStagger.get(name) ?? {};
170
+ stagger[phase] = [index, names.length];
171
+ layerStagger.set(name, stagger);
172
+ });
31
173
  });
32
- }
174
+ };
33
175
  /**
34
- * Set the timing curve to linear for all view transition layers.
35
- * This gets baked into the keyframes, which can't be changed
36
- * without breaking the generated animation.
37
- *
38
- * This allows us to set easing via updateTiming - which can be changed.
176
+ * The stagger index/total for a layer, resolved against the snapshot it
177
+ * belongs to. Returns index -1 when the layer is absent from that snapshot
178
+ * so the caller can skip a pseudo-element that doesn't exist.
39
179
  */
40
- css.set("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)", { "animation-timing-function": "linear !important" });
41
- css.commit(); // Write
42
- const transition = document.startViewTransition(async () => {
43
- await update();
44
- // TODO: Go over new targets and ensure they all have ids
180
+ const staggerPosition = (name, type) => {
181
+ const stagger = layerStagger.get(name);
182
+ const position = type === "old"
183
+ ? stagger?.old
184
+ : type === "new"
185
+ ? stagger?.new
186
+ : // group / group-children / image-pair persist across both.
187
+ stagger?.new ?? stagger?.old;
188
+ return position ?? [-1, 1];
189
+ };
190
+ /**
191
+ * Merge default + per-layer transition options for a generated layer and
192
+ * resolve any stagger/delay function against this element's position. Used
193
+ * by both the morph-retiming and crop corner-radius passes.
194
+ */
195
+ const resolveLayerTransition = (target, type, transitionName, index, total) => {
196
+ const transition = mergeTransition(getValueTransition(defaultOptions, transitionName), getValueTransition((layerOptions(target, type) ?? {}), transitionName));
197
+ if (typeof transition.delay === "function") {
198
+ transition.delay = transition.delay(index, total);
199
+ }
200
+ return transition;
201
+ };
202
+ /**
203
+ * Each layer's box size per snapshot, so `finalizeCrop` can tell whether a
204
+ * morph's aspect ratio changed (the only case worth cropping).
205
+ */
206
+ const cropBox = new Map();
207
+ const measureLayers = (phase) => nameRegistry.forEach((name, element) => {
208
+ const rect = element.getBoundingClientRect?.();
209
+ if (rect && rect.height) {
210
+ const entry = cropBox.get(name) ?? {};
211
+ entry[phase] = { width: rect.width, height: rect.height };
212
+ cropBox.set(name, entry);
213
+ }
45
214
  });
46
- transition.finished.finally(() => {
215
+ /**
216
+ * With both snapshots measured, settle which layers crop. The default crops
217
+ * only a morph whose aspect ratio *changes* between snapshots - the one case
218
+ * where `object-fit: cover` does real work. A same-aspect morph or a
219
+ * fade-only layer is left uncropped: its corners scale naturally (no flash
220
+ * from squaring, no `overflow: clip` eating its shadow) and a backdrop can't
221
+ * be clipped to nothing. An explicit `.crop(true | false)` overrides either
222
+ * way. Runs after both snapshots are measured, since aspect needs both.
223
+ */
224
+ const finalizeCrop = () => {
225
+ croppedNames.clear();
226
+ for (const name of layerStagger.keys()) {
227
+ if (name === "root")
228
+ continue;
229
+ // An explicit `.crop(true | false)` wins; otherwise crop a morph
230
+ // whose aspect ratio changed.
231
+ if (cropForName.get(name) ?? aspectChanged(name)) {
232
+ croppedNames.add(name);
233
+ }
234
+ }
235
+ };
236
+ /**
237
+ * Whether a layer is a morph whose box aspect ratio changed between
238
+ * snapshots (beyond a small tolerance). Fade-only layers (one snapshot) are
239
+ * never "changed".
240
+ */
241
+ const aspectChanged = (name) => {
242
+ const box = cropBox.get(name);
243
+ if (!box?.old || !box?.new || !box.old.height || !box.new.height) {
244
+ return false;
245
+ }
246
+ return (Math.abs(box.old.width / box.old.height -
247
+ box.new.width / box.new.height) > ASPECT_TOLERANCE);
248
+ };
249
+ /**
250
+ * Write the persistent view-transition CSS: suppress root capture when the
251
+ * root has no animations of its own; force linear timing (baked into the
252
+ * keyframes, so we can retime later via updateTiming); and clip +
253
+ * object-fit: cover every cropped morph (the UA default overflows on
254
+ * aspect-ratio change).
255
+ *
256
+ * `css.commit` replaces rather than appends, so we re-set the full rule set
257
+ * each call - the crop rules are only known after `finalizeCrop` runs in the
258
+ * update callback, so the second call writes them.
259
+ */
260
+ const commitViewCSS = () => {
261
+ if (!hasTarget("root", targets)) {
262
+ css.set(":root", { "view-transition-name": "none" });
263
+ }
264
+ css.set("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)", { "animation-timing-function": "linear !important" });
265
+ croppedNames.forEach((name) => {
266
+ css.set(`::view-transition-group(${name})`, { overflow: "clip" });
267
+ css.set(`::view-transition-old(${name}), ::view-transition-new(${name})`, { width: "100%", height: "100%", "object-fit": "cover" });
268
+ });
269
+ /**
270
+ * Clip the nested children of any layer that clips in the live layout,
271
+ * so a wrapper crops its child for the whole morph (mirroring the DOM)
272
+ * rather than only at the live-DOM handoff. No-op on browsers without
273
+ * nested view-transition groups.
274
+ */
275
+ clipChildren.forEach((name) => {
276
+ css.set(`::view-transition-group-children(${name})`, {
277
+ overflow: "clip",
278
+ });
279
+ });
280
+ css.commit(); // Write
281
+ };
282
+ const cleanup = () => {
283
+ releaseViewTransitionNames(assigned, classed, grouped);
47
284
  css.remove(); // Write
48
- });
49
- return new Promise((resolve) => {
50
- transition.ready.then(() => {
285
+ };
286
+ const callback = async () => {
287
+ await update();
288
+ /**
289
+ * Re-resolve so elements created by the update are named for the new
290
+ * snapshot, then measure them. With both snapshots measured we can
291
+ * settle the crop set (aspect-changing morphs + forced).
292
+ */
293
+ resolveLayers("new");
294
+ measureLayers("new");
295
+ finalizeCrop();
296
+ /**
297
+ * Re-commit the crop CSS unconditionally: `finalizeCrop` is computed
298
+ * here (after both snapshots are measured), so the clip rules must be
299
+ * (re)written to match the settled set.
300
+ */
301
+ commitViewCSS();
302
+ };
303
+ let transition;
304
+ try {
305
+ resolveLayers("old");
306
+ /**
307
+ * Measure the old snapshot against the optimistic crop set (the new
308
+ * snapshot doesn't exist yet, so aspect change can't be known here;
309
+ * `finalizeCrop` settles it post-update).
310
+ */
311
+ measureLayers("old");
312
+ commitViewCSS();
313
+ transition = document.startViewTransition(callback);
314
+ }
315
+ catch (error) {
316
+ /**
317
+ * The prelude writes inline names before the transition exists. If it
318
+ * throws (e.g. startViewTransition rejects in a bad UA state), release
319
+ * them so we neither leak DOM state nor stall the queue on a promise
320
+ * that never settles - hand back a rejection it can advance past.
321
+ */
322
+ cleanup();
323
+ return Promise.reject(error);
324
+ }
325
+ transition.finished.finally(cleanup);
326
+ return new Promise((resolve, reject) => {
327
+ transition.ready
328
+ .then(() => {
51
329
  const generatedViewAnimations = getViewAnimations();
52
330
  const animations = [];
53
331
  /**
54
332
  * Create animations for each of our explicitly-defined subjects.
333
+ * `opacityAnimated` additionally tracks which `${name}:${type}`
334
+ * we faded, so we can keep the UA `plus-lighter` blend only for a
335
+ * genuine opacity crossfade (both sides fading) and drop it for a
336
+ * slide/transform, where additive compositing would flash bright.
55
337
  */
56
- targets.forEach((definition, target) => {
57
- // TODO: If target is not "root", resolve elements
58
- // and iterate over each
338
+ const explicitlyAnimated = new Set();
339
+ const opacityAnimated = new Set();
340
+ layerTargets.forEach((target, name) => {
341
+ const stagger = layerStagger.get(name);
342
+ /**
343
+ * Presence: `enter` only fires for a pure newcomer (a new
344
+ * view with no old), `exit` only for a pure leaver. A
345
+ * survivor (both) gets neither - it just morphs.
346
+ */
347
+ const enterApplies = !!stagger?.new && !stagger?.old;
348
+ const exitApplies = !!stagger?.old && !stagger?.new;
59
349
  for (const key of definitionNames) {
60
- if (!definition[key])
350
+ if (!target[key])
351
+ continue;
352
+ if (key === "enter" && !enterApplies)
353
+ continue;
354
+ if (key === "exit" && !exitApplies)
61
355
  continue;
62
- const { keyframes, options } = definition[key];
356
+ const type = chooseLayerType(key);
357
+ const [index, total] = staggerPosition(name, type);
358
+ // Skip a layer absent from its snapshot.
359
+ if (index === -1)
360
+ continue;
361
+ const { keyframes, options } = target[key];
63
362
  for (let [valueName, valueKeyframes] of Object.entries(keyframes)) {
64
- if (!valueKeyframes)
363
+ // Skip only missing values - `0` (e.g. opacity: 0)
364
+ // is valid and must reach the from-value inference.
365
+ if (valueKeyframes == null)
65
366
  continue;
66
- const valueOptions = {
67
- ...getValueTransition(defaultOptions, valueName),
68
- ...getValueTransition(options, valueName),
69
- };
70
- const type = chooseLayerType(key);
71
367
  /**
72
- * If this is an opacity animation, and keyframes are not an array,
73
- * we need to convert them into an array and set an initial value.
368
+ * The view path hands keyframes straight to WAAPI,
369
+ * so Motion's `x`/`y` shorthands (compiled to
370
+ * `transform` only via the value pipeline) have no
371
+ * effect. Warn and skip - use `transform`/`translate`.
74
372
  */
75
- if (valueName === "opacity" &&
76
- !Array.isArray(valueKeyframes)) {
77
- const initialValue = type === "new" ? 0 : 1;
78
- valueKeyframes = [initialValue, valueKeyframes];
373
+ if (valueName === "x" || valueName === "y") {
374
+ warnOnce(false, `animateView() animates view-transition layers with CSS properties; the "${valueName}" shorthand has no effect - use transform, e.g. { transform: "translateX(40px)" }.`);
375
+ continue;
79
376
  }
80
377
  /**
81
- * Resolve stagger function if provided.
378
+ * enter/exit win over new/old on a shared property -
379
+ * skip it here when the gated bucket also defines it.
380
+ */
381
+ if (key === "new" &&
382
+ enterApplies &&
383
+ target.enter?.keyframes[valueName] != null) {
384
+ continue;
385
+ }
386
+ if (key === "old" &&
387
+ exitApplies &&
388
+ target.exit?.keyframes[valueName] != null) {
389
+ continue;
390
+ }
391
+ const valueOptions = mergeTransition(getValueTransition(defaultOptions, valueName), getValueTransition(options, valueName));
392
+ /**
393
+ * Infer an origin for a single-value keyframe. An
394
+ * `enter` mirrors the matching `exit` value (a
395
+ * defined exit reverses into the enter for free);
396
+ * otherwise the per-type default (opacity 0/1, scale
397
+ * 0.85). No default -> left as-is (animates from the
398
+ * live value).
399
+ *
400
+ * `new`/`old` fire for survivors too, where only the
401
+ * opacity crossfade default applies - a transform
402
+ * default like scale 0.85 would pop a persisting
403
+ * element, so gate it on the layer actually
404
+ * entering/leaving.
405
+ */
406
+ if (!Array.isArray(valueKeyframes)) {
407
+ const exitValue = key === "enter"
408
+ ? target.exit?.keyframes[valueName]
409
+ : undefined;
410
+ const allowDefault = valueName === "opacity" ||
411
+ (type === "new" ? enterApplies : exitApplies);
412
+ const from = exitValue != null
413
+ ? Array.isArray(exitValue)
414
+ ? exitValue[exitValue.length - 1]
415
+ : exitValue
416
+ : allowDefault
417
+ ? ORIGIN_DEFAULTS[type]?.[valueName]
418
+ : undefined;
419
+ if (from !== undefined) {
420
+ valueKeyframes = [from, valueKeyframes];
421
+ }
422
+ }
423
+ /**
424
+ * Resolve stagger function if provided, per element
425
+ * across this subject's resolved layers.
82
426
  */
83
427
  if (typeof valueOptions.delay === "function") {
84
- valueOptions.delay = valueOptions.delay(0, 1);
428
+ valueOptions.delay = valueOptions.delay(index, total);
85
429
  }
86
430
  valueOptions.duration && (valueOptions.duration = secondsToMilliseconds(valueOptions.duration));
87
431
  valueOptions.delay && (valueOptions.delay = secondsToMilliseconds(valueOptions.delay));
88
- const animation = new NativeAnimation({
432
+ animations.push(new NativeAnimation({
89
433
  ...valueOptions,
90
434
  element: document.documentElement,
91
435
  name: valueName,
92
- pseudoElement: `::view-transition-${type}(${target})`,
436
+ pseudoElement: `::view-transition-${type}(${name})`,
93
437
  keyframes: valueKeyframes,
94
- });
95
- animations.push(animation);
438
+ }));
439
+ explicitlyAnimated.add(`${name}:${type}`);
440
+ if (valueName === "opacity") {
441
+ opacityAnimated.add(`${name}:${type}`);
442
+ }
96
443
  }
97
444
  }
98
445
  });
@@ -111,45 +458,129 @@ function startViewAnimation(builder) {
111
458
  const name = getViewAnimationLayerInfo(pseudoElement);
112
459
  if (!name)
113
460
  continue;
114
- const targetDefinition = targets.get(name.layer);
115
- if (!targetDefinition) {
116
- /**
117
- * If transition name is group then update the timing of the animation
118
- * whereas if it's old or new then we could possibly replace it using
119
- * the above method.
120
- */
121
- const transitionName = name.type === "group" ? "layout" : "";
122
- let animationTransition = {
123
- ...getValueTransition(defaultOptions, transitionName),
124
- };
125
- animationTransition.duration && (animationTransition.duration = secondsToMilliseconds(animationTransition.duration));
126
- animationTransition =
127
- applyGeneratorOptions(animationTransition);
128
- const easing = mapEasingToNativeEasing(animationTransition.ease, animationTransition.duration);
129
- effect.updateTiming({
130
- delay: secondsToMilliseconds(animationTransition.delay ?? 0),
131
- duration: animationTransition.duration,
132
- easing,
133
- });
134
- animations.push(new NativeAnimationWrapper(animation));
135
- }
136
- else if (hasOpacity(targetDefinition, "enter") &&
137
- hasOpacity(targetDefinition, "exit") &&
138
- effect
139
- .getKeyframes()
140
- .some((keyframe) => keyframe.mixBlendMode)) {
141
- animations.push(new NativeAnimationWrapper(animation));
142
- }
143
- else {
144
- animation.cancel();
461
+ const targetDefinition = layerTargets.get(name.layer);
462
+ /**
463
+ * We built our own animation for this layer, so drop the
464
+ * browser-generated fade we're replacing. The UA
465
+ * `plus-lighter` blend is a *separate* generated animation on
466
+ * the same pseudo (it sets `mix-blend-mode` in its keyframes):
467
+ * keep it *only* for a true opacity crossfade - both sides
468
+ * fading - so a symmetric crossfade composites without
469
+ * darkening, but a slide/transform (where both layers stay
470
+ * opaque and overlap) doesn't flash bright from the addition.
471
+ */
472
+ if (explicitlyAnimated.has(`${name.layer}:${name.type}`)) {
473
+ const isCrossfade = opacityAnimated.has(`${name.layer}:new`) &&
474
+ opacityAnimated.has(`${name.layer}:old`);
475
+ if (isCrossfade &&
476
+ effect
477
+ .getKeyframes()
478
+ .some((keyframe) => keyframe.mixBlendMode)) {
479
+ animations.push(new NativeAnimationWrapper(animation));
480
+ }
481
+ else {
482
+ animation.cancel();
483
+ }
484
+ continue;
145
485
  }
486
+ /**
487
+ * Otherwise retime the browser-generated animation to
488
+ * Motion's timing. This auto-enables the layout (group)
489
+ * morph for any resolved/named target, and applies the
490
+ * default timing to old/new layers we haven't explicitly
491
+ * overridden.
492
+ *
493
+ * group + group-children both follow the layout timing so
494
+ * the nesting container stays in sync with the morph.
495
+ */
496
+ /**
497
+ * A survivor's old + new are the two halves of one
498
+ * `plus-lighter` crossfade. They must share identical timing
499
+ * (so their opacities stay mirrored and sum to 1 - else the
500
+ * additive blend flashes bright wherever both are partly
501
+ * visible) and fade linearly (the bounce belongs on the
502
+ * group's geometry, not the opacity). So time them as the
503
+ * group, rather than via their own - potentially staggered,
504
+ * or enter/exit-derived - old/new options.
505
+ */
506
+ const stagger = layerStagger.get(name.layer);
507
+ const isMorphCrossfade = (name.type === "old" || name.type === "new") &&
508
+ !!stagger?.old &&
509
+ !!stagger?.new;
510
+ const timingType = name.type.startsWith("group") || isMorphCrossfade
511
+ ? "group"
512
+ : name.type;
513
+ const [index, total] = staggerPosition(name.layer, timingType);
514
+ const transitionName = timingType === "group" ? "layout" : "";
515
+ let animationTransition = resolveLayerTransition(targetDefinition, timingType, transitionName, index === -1 ? 0 : index, total);
516
+ /**
517
+ * The crossfade should resolve at the spring's *perceptual*
518
+ * (visual) duration - the geometry can keep bouncing, but the
519
+ * opacity shouldn't drag through the settle. So capture
520
+ * `visualDuration` before `applyGeneratorOptions` replaces it
521
+ * with the full overshoot duration, and use it for the fade.
522
+ */
523
+ const visualDuration = animationTransition.visualDuration;
524
+ animationTransition.duration && (animationTransition.duration = secondsToMilliseconds(animationTransition.duration));
525
+ animationTransition =
526
+ applyGeneratorOptions(animationTransition);
527
+ const duration = isMorphCrossfade && visualDuration !== undefined
528
+ ? secondsToMilliseconds(visualDuration)
529
+ : animationTransition.duration;
530
+ const easing = isMorphCrossfade
531
+ ? "linear"
532
+ : mapEasingToNativeEasing(animationTransition.ease, animationTransition.duration);
533
+ effect.updateTiming({
534
+ delay: secondsToMilliseconds(animationTransition.delay ?? 0),
535
+ duration,
536
+ easing,
537
+ });
538
+ animations.push(new NativeAnimationWrapper(animation));
146
539
  }
147
540
  resolve(new GroupAnimation(animations));
148
- });
541
+ })
542
+ .catch(() =>
543
+ /**
544
+ * `ready` rejects when the transition is skipped - no visual
545
+ * change, or superseded by an interrupting transition. The DOM
546
+ * update still applied, so settle with no animations rather than
547
+ * surfacing it as an error to an awaiting caller. A genuine
548
+ * failure in `update()` rejects `updateCallbackDone` (already
549
+ * settled by now), so propagate that instead.
550
+ */
551
+ transition.updateCallbackDone.then(() => resolve(new GroupAnimation([])), reject));
149
552
  });
150
553
  }
151
- function hasOpacity(target, key) {
152
- return target?.[key]?.keyframes.opacity;
554
+ /**
555
+ * The options that should time a given generated layer type, so a retimed
556
+ * group/old/new picks up any per-target transition the user provided. Checks
557
+ * the type's buckets in priority order (e.g. `new` before `enter`).
558
+ */
559
+ function layerOptions(target, type) {
560
+ for (const bucket of typeBuckets[type] ?? []) {
561
+ const options = target?.[bucket]?.options;
562
+ if (options)
563
+ return options;
564
+ }
565
+ }
566
+ /**
567
+ * Merge a base transition (e.g. the default `options`) with a per-layer/value
568
+ * override. An explicit `duration` on the override must win over an inherited
569
+ * generator's own timing: a spring prefers `visualDuration`, and
570
+ * `spring.applyToOptions` overwrites `duration` with the computed settle time -
571
+ * so without this the override is silently discarded. Dropping the inherited
572
+ * `type`/`visualDuration` makes the layer a plain tween of that duration, unless
573
+ * it asked for its own generator `type`/`visualDuration`.
574
+ */
575
+ function mergeTransition(base, override) {
576
+ const merged = { ...base, ...override };
577
+ if (override.duration !== undefined) {
578
+ if (override.visualDuration === undefined)
579
+ delete merged.visualDuration;
580
+ if (override.type === undefined)
581
+ delete merged.type;
582
+ }
583
+ return merged;
153
584
  }
154
585
 
155
586
  export { startViewAnimation };