Skip to main content

sk_css/
view_transition.rs

1//! View transition pseudo-elements as selectors over stand-in elements. A rule for
2//! `::view-transition-old(card)` is rewritten to match an element `sk-vt-old[sk-vt-name="card"]`
3//! under `sk-vt-image-pair`, `sk-vt-group` and `sk-vt`, whose parent is the document element;
4//! the renderer builds those elements while a transition runs ([`MatchDom::is_view_transition_pseudo`]).
5//!
6//! [`MatchDom::is_view_transition_pseudo`]: crate::MatchDom::is_view_transition_pseudo
7
8/// The stand-in tags: `::view-transition`, `-group`, `-image-pair`, `-old`, `-new`.
9pub const TAGS: [&str; 5] = [
10    "sk-vt",
11    "sk-vt-group",
12    "sk-vt-image-pair",
13    "sk-vt-old",
14    "sk-vt-new",
15];
16
17/// The attribute that carries the transition name on every stand-in but `sk-vt`.
18pub const NAME_ATTR: &str = "sk-vt-name";
19
20/// The root's attribute that `:active-view-transition` reads: the active transition's types,
21/// space-separated (empty when it has none).
22pub const ACTIVE_ATTR: &str = ":active-view-transition";
23
24/// The pseudo-elements' default styles. The renderer sets `--sk-vt-*` on each group: its captured
25/// geometry, old and new (the same when only one exists, which makes the group animation hold).
26pub(crate) const UA_SHEET: &str = "
27::view-transition { position: fixed; inset: 0; }
28::view-transition-group(*) {
29  position: absolute; top: 0; left: 0;
30  width: var(--sk-vt-width); height: var(--sk-vt-height); transform: var(--sk-vt-transform);
31  animation-name: -ua-view-transition-group-anim; animation-duration: 0.25s;
32  animation-fill-mode: both;
33}
34::view-transition-image-pair(*) {
35  position: absolute; inset: 0; isolation: var(--sk-vt-isolation, auto);
36}
37::view-transition-old(*), ::view-transition-new(*) {
38  position: absolute; top: 0; left: 0; width: 100%; height: auto;
39  mix-blend-mode: var(--sk-vt-blend, normal);
40}
41::view-transition-old(*) { animation-name: -ua-view-transition-fade-out; }
42::view-transition-new(*) { animation-name: -ua-view-transition-fade-in; }
43@keyframes -ua-view-transition-fade-out { to { opacity: 0; } }
44@keyframes -ua-view-transition-fade-in { from { opacity: 0; } }
45@keyframes -ua-view-transition-group-anim {
46  from {
47    width: var(--sk-vt-old-width); height: var(--sk-vt-old-height);
48    transform: var(--sk-vt-old-transform);
49  }
50}
51";
52
53/// The image pair and images inherit their group's animation timing in the spec's UA sheet
54/// (`animation-duration: inherit`, …), which the cascade here cannot say: each longhand still at
55/// its initial value takes the group's.
56pub fn inherit_animation_timing(
57    animations: &[crate::AnimationSpec],
58    group: Option<&crate::AnimationSpec>,
59) -> Vec<crate::AnimationSpec> {
60    let Some(group) = group else {
61        return animations.to_vec();
62    };
63    animations
64        .iter()
65        .map(|own| {
66            let mut spec = own.clone();
67            if spec.duration.is_zero() {
68                spec.duration = group.duration;
69            }
70            if spec.delay.is_zero() {
71                spec.delay = group.delay;
72            }
73            if spec.easing == crate::Easing::default() {
74                spec.easing = group.easing;
75            }
76            if spec.iterations == 1.0 {
77                spec.iterations = group.iterations;
78            }
79            if spec.direction == crate::AnimationDirection::default() {
80                spec.direction = group.direction;
81            }
82            if spec.fill == crate::FillMode::default() {
83                spec.fill = group.fill;
84            }
85            if spec.play_state == crate::PlayState::default() {
86                spec.play_state = group.play_state;
87            }
88            spec
89        })
90        .collect()
91}
92
93/// The rewritten selector for one containing a view transition pseudo-element, or `None` when
94/// there is none or it is malformed. `ua` leaves only the subject's tag counting, so that every
95/// author rule outranks it.
96pub(crate) fn rewrite(text: &str, ua: bool) -> Option<String> {
97    let at = text.find("::view-transition")?;
98    let (prefix, rest) = text.split_at(at);
99    let rest = &rest[2..];
100    let (kind, after) = [
101        ("view-transition-image-pair", 2),
102        ("view-transition-group", 1),
103        ("view-transition-old", 3),
104        ("view-transition-new", 4),
105        ("view-transition", 0),
106    ]
107    .into_iter()
108    .find_map(|(name, kind)| rest.strip_prefix(name).map(|after| (kind, after)))?;
109    let mut subject = TAGS[kind].to_string();
110    let suffix = if kind == 0 {
111        after
112    } else {
113        let inner = after.strip_prefix('(')?;
114        let close = inner.find(')')?;
115        let (part, suffix) = (&inner[..close], &inner[close + 1..]);
116        let mut pieces = part.split('.');
117        let name = pieces.next().unwrap_or("").trim();
118        if !name.is_empty() && name != "*" {
119            subject.push_str(&format!("[{NAME_ATTR}=\"{name}\"]"));
120        }
121        for class in pieces {
122            let class = class.trim();
123            if class.is_empty() {
124                return None;
125            }
126            subject.push('.');
127            subject.push_str(class);
128        }
129        suffix
130    };
131    if suffix.contains("::") {
132        return None;
133    }
134    subject.push_str(suffix);
135    let origin = match prefix.trim_end() {
136        "" if ua => ":where(:root)".to_string(),
137        "" => ":root".to_string(),
138        trimmed if prefix.len() != trimmed.len() || trimmed.ends_with(['>', '+', '~']) => {
139            format!("{trimmed} *")
140        }
141        trimmed => trimmed.to_string(),
142    };
143    let mut out = origin;
144    for ancestor in match kind {
145        0 => &[][..],
146        1 => &[0][..],
147        2 => &[0, 1][..],
148        _ => &[0, 1, 2][..],
149    } {
150        out.push_str(&format!(" > :where({})", TAGS[*ancestor]));
151    }
152    out.push_str(" > ");
153    out.push_str(&subject);
154    Some(out)
155}
156
157#[cfg(test)]
158mod tests {
159    use super::{rewrite, ACTIVE_ATTR, NAME_ATTR};
160    use crate::{ComputedStates, Engine, Env, MatchDom, Vars};
161    use std::rc::Rc;
162
163    /// `(tag, class, parent, attrs)`; index 0 is no node, 1 the document element.
164    struct Doc(
165        Vec<(
166            &'static str,
167            &'static str,
168            usize,
169            Vec<(&'static str, &'static str)>,
170        )>,
171    );
172
173    #[derive(Clone, Copy)]
174    struct At<'d>(&'d Doc, usize);
175
176    impl<'d> At<'d> {
177        fn node(
178            &self,
179        ) -> &'d (
180            &'static str,
181            &'static str,
182            usize,
183            Vec<(&'static str, &'static str)>,
184        ) {
185            &self.0 .0[self.1]
186        }
187        fn siblings(&self) -> Vec<usize> {
188            let parent = self.node().2;
189            (1..self.0 .0.len())
190                .filter(|&j| self.0 .0[j].2 == parent)
191                .collect()
192        }
193    }
194
195    impl<'d> MatchDom for At<'d> {
196        fn key(&self) -> u64 {
197            self.1 as u64
198        }
199        fn parent(&self) -> Option<Self> {
200            let p = self.node().2;
201            (p != 0).then_some(At(self.0, p))
202        }
203        fn prev_sibling(&self) -> Option<Self> {
204            let s = self.siblings();
205            let i = s.iter().position(|&j| j == self.1)?;
206            (i > 0).then(|| At(self.0, s[i - 1]))
207        }
208        fn next_sibling(&self) -> Option<Self> {
209            let s = self.siblings();
210            let i = s.iter().position(|&j| j == self.1)?;
211            s.get(i + 1).map(|&j| At(self.0, j))
212        }
213        fn has_tag(&self, name: &str) -> bool {
214            self.node().0 == name
215        }
216        fn tag_eq(&self, other: &Self) -> bool {
217            self.node().0 == other.node().0
218        }
219        fn has_class(&self, name: &str) -> bool {
220            self.node().1.split_whitespace().any(|c| c == name)
221        }
222        fn tag_name(&self) -> &str {
223            self.node().0
224        }
225        fn each_class(&self, f: &mut dyn FnMut(&str)) {
226            self.node().1.split_whitespace().for_each(f);
227        }
228        fn has_scope(&self, _: &str) -> bool {
229            false
230        }
231        fn attr(&self, name: &str) -> Option<&str> {
232            self.node()
233                .3
234                .iter()
235                .find(|(k, _)| *k == name)
236                .map(|(_, v)| *v)
237        }
238        fn is_empty(&self) -> bool {
239            !self.0 .0.iter().any(|n| n.2 == self.1)
240        }
241        fn is_root(&self) -> bool {
242            self.node().2 == 0
243        }
244        fn is_view_transition_pseudo(&self) -> bool {
245            self.node().0.starts_with("sk-vt")
246        }
247    }
248
249    fn doc(types: &'static str) -> Doc {
250        Doc(vec![
251            ("", "", 0, vec![]),
252            ("div", "", 0, vec![(ACTIVE_ATTR, types)]),
253            ("div", "item", 1, vec![]),
254            ("sk-vt", "", 1, vec![]),
255            ("sk-vt-group", "", 3, vec![(NAME_ATTR, "root")]),
256            ("sk-vt-group", "card", 3, vec![(NAME_ATTR, "hero")]),
257            ("sk-vt-image-pair", "card", 5, vec![(NAME_ATTR, "hero")]),
258            ("sk-vt-old", "card", 6, vec![(NAME_ATTR, "hero")]),
259        ])
260    }
261
262    fn cascade(css: &str, d: &Doc, i: usize, inline: &str, parent: &Rc<Vars>) -> ComputedStates {
263        let mut diagnostics = Vec::new();
264        let inline = crate::parse_inline_style(inline, &mut diagnostics);
265        let states = Engine::compile(css).compute_node(
266            At(d, i),
267            Some(&inline),
268            parent,
269            None,
270            &Env::default(),
271            &mut diagnostics,
272        );
273        assert!(diagnostics.is_empty(), "{diagnostics:?}");
274        states
275    }
276
277    fn duration(states: &ComputedStates) -> Option<f32> {
278        states.animations.first().map(|a| a.duration.as_secs_f32())
279    }
280
281    #[test]
282    fn transition_rules_style_the_stand_ins_and_nothing_else() {
283        let css = "* { opacity: 0.5 }
284            ::view-transition-group(*) { animation-duration: 1s }
285            ::view-transition-group(hero) { animation-duration: 2s }
286            ::view-transition-group(*.card) { animation-delay: 3s }
287            ::view-transition-old(*) { opacity: 0.25 }
288            :active-view-transition-type(forwards) .item { opacity: 0.75 }";
289        let d = doc("back forwards");
290        let none = Rc::new(Vars::default());
291        let geometry =
292            "--sk-vt-width: 40px; --sk-vt-height: 30px; --sk-vt-transform: translate(5px, 6px);
293            --sk-vt-old-width: 10px; --sk-vt-old-height: 10px; --sk-vt-old-transform: none";
294        let root = cascade(css, &d, 4, geometry, &none);
295        let hero = cascade(css, &d, 5, geometry, &none);
296        assert_eq!(duration(&root), Some(1.0));
297        assert_eq!(duration(&hero), Some(2.0));
298        assert_eq!(
299            hero.animations
300                .first()
301                .map(|a| a.delay.as_secs_f64() as f32),
302            Some(3.0)
303        );
304        assert_eq!(hero.base.size.width, Some(gpui::px(40.0).into()));
305        assert!(hero.base.vn_transform.is_some());
306        assert_eq!(
307            root.base.opacity, None,
308            "`*` does not reach a pseudo-element"
309        );
310        let old = cascade(css, &d, 7, "", &hero.vars);
311        assert_eq!(old.base.opacity, Some(0.25));
312        assert_eq!(
313            old.animations.first().map(|a| &*a.name),
314            Some("-ua-view-transition-fade-out")
315        );
316        let timed = super::inherit_animation_timing(&old.animations, hero.animations.first());
317        assert_eq!(timed.first().map(|a| a.duration.as_secs_f32()), Some(2.0));
318        assert_eq!(timed.first().map(|a| a.fill), Some(crate::FillMode::Both));
319        assert_eq!(cascade(css, &d, 2, "", &none).base.opacity, Some(0.75));
320        assert_eq!(
321            cascade(css, &doc("back"), 2, "", &none).base.opacity,
322            Some(0.5)
323        );
324    }
325
326    #[test]
327    fn pseudo_elements_become_stand_ins_under_the_originating_element() {
328        assert_eq!(
329            rewrite("::view-transition-old(card.big)", false).as_deref(),
330            Some(":root > :where(sk-vt) > :where(sk-vt-group) > :where(sk-vt-image-pair) > sk-vt-old[sk-vt-name=\"card\"].big")
331        );
332        assert_eq!(
333            rewrite(
334                "html:active-view-transition-type(slide)::view-transition-group(*)",
335                false
336            )
337            .as_deref(),
338            Some("html:active-view-transition-type(slide) > :where(sk-vt) > sk-vt-group")
339        );
340        assert_eq!(
341            rewrite("::view-transition-new(x):only-child", false).as_deref(),
342            Some(":root > :where(sk-vt) > :where(sk-vt-group) > :where(sk-vt-image-pair) > sk-vt-new[sk-vt-name=\"x\"]:only-child")
343        );
344        assert_eq!(
345            rewrite("::view-transition", true).as_deref(),
346            Some(":where(:root) > sk-vt")
347        );
348        assert_eq!(rewrite("div::after", false), None);
349    }
350}