|
| 1 | +/** |
| 2 | + * Copyright 2026 Google LLC |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +import { getAnimations, ViewTransitionPart } from "./animations.js"; |
| 7 | + |
| 8 | +/** |
| 9 | + * Returns CSS needed to morph an element during a View Transition, |
| 10 | + * following the technique described in https://www.bram.us/2025/05/15/view-transitions-border-radius-revisited/ |
| 11 | + * |
| 12 | + * @param vt The active ViewTransition |
| 13 | + * @param element The element to apply the morph to |
| 14 | + * @param properties A list of CSS properties to transition |
| 15 | + * @returns A string containing the required CSS, or an empty string if it couldn't be generated |
| 16 | + */ |
| 17 | +export function morph( |
| 18 | + vt: ViewTransition, |
| 19 | + element: HTMLElement, |
| 20 | + properties: string[] |
| 21 | +): string { |
| 22 | + // 1. Get view-transition-name |
| 23 | + const styles = window.getComputedStyle(element); |
| 24 | + const vtName = styles.viewTransitionName; |
| 25 | + |
| 26 | + if (!vtName || vtName === "none") { |
| 27 | + console.warn("morph: Element has no view-transition-name. Skipping."); |
| 28 | + return ""; |
| 29 | + } |
| 30 | + |
| 31 | + // 2. Warn if element already has a transition |
| 32 | + const durations = styles.transitionDuration.split(",").map(d => parseFloat(d)); |
| 33 | + if (durations.some(d => d > 0)) { |
| 34 | + console.warn("morph: Element already has a CSS transition applied. It will be overwritten by morph."); |
| 35 | + } |
| 36 | + |
| 37 | + // 3. Get the duration and easing from the original ::view-transition-group |
| 38 | + const groupAnimations = getAnimations(vt, vtName, ViewTransitionPart.Group); |
| 39 | + if (groupAnimations.length === 0) { |
| 40 | + console.warn(`morph: Could not find ::view-transition-group animation for ${vtName}. Skipping.`); |
| 41 | + return ""; |
| 42 | + } |
| 43 | + |
| 44 | + const anim = groupAnimations[0]; |
| 45 | + const effect = anim.effect as KeyframeEffect; |
| 46 | + const timing = effect.getComputedTiming(); |
| 47 | + const durationMs = timing.duration; |
| 48 | + const easing = effect.getTiming().easing; |
| 49 | + |
| 50 | + // 4. Generate the CSS string |
| 51 | + if (!element.id) { |
| 52 | + console.warn("morph: Element must have an ID to be targeted. Skipping."); |
| 53 | + return ""; |
| 54 | + } |
| 55 | + |
| 56 | + return ` |
| 57 | +#${element.id} { |
| 58 | + transition-property: ${properties.join(", ")}; |
| 59 | + transition-duration: ${durationMs}ms; |
| 60 | + transition-timing-function: ${easing}; |
| 61 | +} |
| 62 | +
|
| 63 | +::view-transition-old(${vtName}) { |
| 64 | + display: none; |
| 65 | +} |
| 66 | +
|
| 67 | +::view-transition-new(${vtName}) { |
| 68 | + animation: none; |
| 69 | + width: 100%; |
| 70 | + height: 100%; |
| 71 | +} |
| 72 | +`.trim(); |
| 73 | +} |
0 commit comments