Skip to main content

strata/runtime/
animation.rs

1//! CSS keyframe animations, transitions, view transitions, and scroll animations.
2
3use super::*;
4
5fn fnv1a_mix(mut hash: u64, bytes: &[u8]) -> u64 {
6    for &b in bytes {
7        hash ^= b as u64;
8        hash = hash.wrapping_mul(0x100000001b3u64);
9    }
10    hash
11}
12
13fn blueprint_has_explicit_identity(bp: Option<&NodeBlueprint>) -> bool {
14    let Some(NodeBlueprint::Element { attributes, .. }) = bp else {
15        return false;
16    };
17    attributes.iter().any(|attr| {
18        matches!(
19            attr,
20            strata_dom::Attribute::Property { key, .. }
21                if key == "id" || key == "key" || key == "data-key"
22        )
23    })
24}
25
26fn blueprint_node_identity_hash(
27    parent_hash: u64,
28    child_index: usize,
29    bp: Option<&NodeBlueprint>,
30) -> u64 {
31    let mut hash = fnv1a_mix(parent_hash, &child_index.to_le_bytes());
32    match bp {
33        Some(NodeBlueprint::Element {
34            tag, attributes, ..
35        }) => {
36            hash = fnv1a_mix(hash, &[1]);
37            let mut tag_hasher = std::collections::hash_map::DefaultHasher::new();
38            std::hash::Hash::hash(tag, &mut tag_hasher);
39            hash = fnv1a_mix(hash, &std::hash::Hasher::finish(&tag_hasher).to_le_bytes());
40            for attr in attributes {
41                if let strata_dom::Attribute::Property { key, value } = attr {
42                    if key == "id" || key == "key" || key == "data-key" {
43                        hash = fnv1a_mix(hash, key.as_bytes());
44                        hash = fnv1a_mix(hash, &[0xff]);
45                        hash = fnv1a_mix(hash, value.as_bytes());
46                        hash = fnv1a_mix(hash, &[0xfe]);
47                    }
48                }
49            }
50        }
51        Some(NodeBlueprint::Text(_)) => {
52            hash = fnv1a_mix(hash, &[2]);
53        }
54        Some(NodeBlueprint::DynamicText(_)) => {
55            hash = fnv1a_mix(hash, &[3]);
56        }
57        Some(NodeBlueprint::Fragment(_)) => {
58            hash = fnv1a_mix(hash, &[4]);
59        }
60        Some(NodeBlueprint::Empty) => {
61            hash = fnv1a_mix(hash, &[5]);
62        }
63        None => {
64            hash = fnv1a_mix(hash, &[0]);
65        }
66    }
67    hash
68}
69
70impl AppRuntime {
71    /// Records current solved `border_box` dimensions for every tracked animation node ID
72    /// before a DOM update/rebuild overwrites styles or geometries.
73    pub(crate) fn capture_previous_node_sizes(&mut self) {
74        if self.path_node_ids.is_empty() {
75            return;
76        }
77        self.previous_node_sizes.clear();
78        let mut path = Vec::new();
79        Self::capture_node_sizes_rec(
80            &self.layout_root,
81            &mut path,
82            &self.path_node_ids,
83            &mut self.previous_node_sizes,
84        );
85    }
86
87    fn capture_node_sizes_rec(
88        node: &LayoutNode,
89        path: &mut Vec<usize>,
90        path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
91        out: &mut std::collections::HashMap<u64, (f32, f32)>,
92    ) {
93        if let Some(&id) = path_node_ids.get(path) {
94            out.insert(
95                id,
96                (
97                    node.geometry.border_box.width,
98                    node.geometry.border_box.height,
99                ),
100            );
101        }
102        for (idx, child) in node.children.iter().enumerate() {
103            path.push(idx);
104            Self::capture_node_sizes_rec(child, path, path_node_ids, out);
105            path.pop();
106        }
107    }
108
109    fn has_transition_to_auto_dim(
110        node: &LayoutNode,
111        blueprint: Option<&NodeBlueprint>,
112        parent_hash: u64,
113        child_index: usize,
114        previous_styles: &std::collections::HashMap<u64, ComputedStyle>,
115    ) -> bool {
116        let node_id = blueprint_node_identity_hash(parent_hash, child_index, blueprint);
117        if !node.style.transitions.is_empty() {
118            if let Some(old) = previous_styles.get(&node_id) {
119                let is_auto = |d| matches!(d, strata_style::types::Dimension::Auto);
120                let width_changed_to_auto =
121                    old.width != node.style.width && is_auto(node.style.width);
122                let height_changed_to_auto =
123                    old.height != node.style.height && is_auto(node.style.height);
124                if width_changed_to_auto || height_changed_to_auto {
125                    return true;
126                }
127            }
128        }
129        let bp_children = match blueprint {
130            Some(NodeBlueprint::Element { children, .. }) => Some(children.as_slice()),
131            Some(NodeBlueprint::Fragment(children)) => Some(children.as_slice()),
132            _ => None,
133        };
134        for (idx, child) in node.children.iter().enumerate() {
135            if Self::has_transition_to_auto_dim(
136                child,
137                bp_children.and_then(|c| c.get(idx)),
138                node_id,
139                idx,
140                previous_styles,
141            ) {
142                return true;
143            }
144        }
145        false
146    }
147
148    fn collect_measured_auto_sizes(
149        node: &LayoutNode,
150        blueprint: Option<&NodeBlueprint>,
151        parent_hash: u64,
152        child_index: usize,
153        out: &mut std::collections::HashMap<u64, (f32, f32)>,
154    ) {
155        let node_id = blueprint_node_identity_hash(parent_hash, child_index, blueprint);
156        if !node.style.transitions.is_empty() {
157            out.insert(
158                node_id,
159                (
160                    node.geometry.border_box.width,
161                    node.geometry.border_box.height,
162                ),
163            );
164        }
165        let bp_children = match blueprint {
166            Some(NodeBlueprint::Element { children, .. }) => Some(children.as_slice()),
167            Some(NodeBlueprint::Fragment(children)) => Some(children.as_slice()),
168            _ => None,
169        };
170        for (idx, child) in node.children.iter().enumerate() {
171            Self::collect_measured_auto_sizes(
172                child,
173                bp_children.and_then(|c| c.get(idx)),
174                node_id,
175                idx,
176                out,
177            );
178        }
179    }
180
181    /// Synchronizes running animations and transitions with the current layout tree.
182    pub fn sync_tree_animations(&mut self, now_ms: f64) {
183        let mut new_base_styles = std::collections::HashMap::new();
184        let mut new_node_paths = std::collections::HashMap::new();
185        let mut new_path_node_ids = std::collections::HashMap::new();
186        let mut path_buf = Vec::new();
187
188        let measured_auto_sizes = if Self::has_transition_to_auto_dim(
189            &self.layout_root,
190            Some(&self.root_blueprint),
191            0xcbf29ce484222325u64,
192            0,
193            &self.previous_node_styles,
194        ) {
195            let mut probe = self.layout_root.clone();
196            probe.compute_layout(self.viewport_width, self.viewport_height);
197            let mut sizes = std::collections::HashMap::new();
198            Self::collect_measured_auto_sizes(
199                &probe,
200                Some(&self.root_blueprint),
201                0xcbf29ce484222325u64,
202                0,
203                &mut sizes,
204            );
205            Some(sizes)
206        } else {
207            None
208        };
209
210        let mut trans_events = Vec::new();
211        let mut anim_events = Vec::new();
212
213        Self::sync_tree_animations_rec(
214            &self.layout_root,
215            Some(&self.root_blueprint),
216            0xcbf29ce484222325u64,
217            0,
218            &mut path_buf,
219            now_ms,
220            &self.previous_node_styles,
221            &self.previous_node_sizes,
222            measured_auto_sizes.as_ref(),
223            &mut new_base_styles,
224            &mut new_node_paths,
225            &mut new_path_node_ids,
226            &mut self.transition_manager,
227            &mut self.animation_manager,
228            &mut trans_events,
229            &mut anim_events,
230        );
231
232        self.base_node_styles = new_base_styles;
233        self.previous_node_styles = self.base_node_styles.clone();
234        self.node_paths = new_node_paths;
235        self.path_node_ids = new_path_node_ids;
236
237        // Prune any transitions/animations belonging to unmounted or replaced elements
238        // so dead nodes never leak state or keep frame ticks alive.
239        self.transition_manager
240            .retain_nodes(|id| self.base_node_styles.contains_key(id));
241        self.animation_manager
242            .retain_nodes(|id| self.base_node_styles.contains_key(id));
243
244        // Evaluate scroll-driven animations progress
245        self.evaluate_scroll_animations(&mut anim_events);
246
247        for ev in trans_events {
248            self.dispatch_transition_event(ev);
249        }
250        for ev in anim_events {
251            self.dispatch_animation_event(ev);
252        }
253
254        self.apply_animations_to_layout_tree();
255    }
256
257    #[allow(clippy::too_many_arguments)]
258    pub(crate) fn sync_tree_animations_rec(
259        node: &LayoutNode,
260        blueprint: Option<&NodeBlueprint>,
261        parent_hash: u64,
262        child_index: usize,
263        path: &mut Vec<usize>,
264        now_ms: f64,
265        previous_styles: &std::collections::HashMap<u64, ComputedStyle>,
266        previous_sizes: &std::collections::HashMap<u64, (f32, f32)>,
267        measured_auto_sizes: Option<&std::collections::HashMap<u64, (f32, f32)>>,
268        new_base_styles: &mut std::collections::HashMap<u64, ComputedStyle>,
269        new_node_paths: &mut std::collections::HashMap<u64, Vec<usize>>,
270        new_path_node_ids: &mut std::collections::HashMap<Vec<usize>, u64>,
271        transition_manager: &mut strata_style::transition::TransitionManager,
272        animation_manager: &mut strata_style::animation::AnimationManager,
273        trans_events: &mut Vec<strata_style::transition::TransitionLifecycleEvent>,
274        anim_events: &mut Vec<strata_style::animation::AnimationLifecycleEvent>,
275    ) {
276        let node_id = blueprint_node_identity_hash(parent_hash, child_index, blueprint);
277        new_base_styles.insert(node_id, node.style.clone());
278        new_node_paths.insert(node_id, path.clone());
279        new_path_node_ids.insert(path.clone(), node_id);
280
281        // Check for transitions if we have a previous style or @starting-style
282        let effective_old_style = match previous_styles.get(&node_id) {
283            Some(old) if old.display != strata_style::Display::None => {
284                if old.transitions.is_empty()
285                    && !node.style.transitions.is_empty()
286                    && !blueprint_has_explicit_identity(blueprint)
287                {
288                    node.style.starting_style.as_deref()
289                } else {
290                    Some(old)
291                }
292            }
293            _ => node.style.starting_style.as_deref(),
294        };
295
296        if let Some(old_style) = effective_old_style {
297            if !node.style.transitions.is_empty() {
298                let mut resolved_old_buf: Option<ComputedStyle> = None;
299                let mut resolved_new_buf: Option<ComputedStyle> = None;
300
301                if let Some(&(prev_w, prev_h)) = previous_sizes.get(&node_id) {
302                    if old_style.width == strata_style::types::Dimension::Auto
303                        && old_style.width != node.style.width
304                    {
305                        resolved_old_buf
306                            .get_or_insert_with(|| old_style.clone())
307                            .width = strata_style::types::Dimension::Px(prev_w);
308                    }
309                    if old_style.height == strata_style::types::Dimension::Auto
310                        && old_style.height != node.style.height
311                    {
312                        resolved_old_buf
313                            .get_or_insert_with(|| old_style.clone())
314                            .height = strata_style::types::Dimension::Px(prev_h);
315                    }
316                }
317                if let Some(&(target_w, target_h)) =
318                    measured_auto_sizes.and_then(|m| m.get(&node_id))
319                {
320                    if node.style.width == strata_style::types::Dimension::Auto
321                        && old_style.width != node.style.width
322                    {
323                        resolved_new_buf
324                            .get_or_insert_with(|| node.style.clone())
325                            .width = strata_style::types::Dimension::Px(target_w);
326                    }
327                    if node.style.height == strata_style::types::Dimension::Auto
328                        && old_style.height != node.style.height
329                    {
330                        resolved_new_buf
331                            .get_or_insert_with(|| node.style.clone())
332                            .height = strata_style::types::Dimension::Px(target_h);
333                    }
334                }
335
336                let old_ref = resolved_old_buf.as_ref().unwrap_or(old_style);
337                let new_ref = resolved_new_buf.as_ref().unwrap_or(&node.style);
338                trans_events.extend(transition_manager.update_styles(
339                    node_id,
340                    old_ref,
341                    new_ref,
342                    now_ms,
343                ));
344            }
345        }
346
347        // Check for keyframe animations
348        if !node.style.animations.is_empty() || animation_manager.has_active_animations() {
349            anim_events.extend(animation_manager.update_styles(node_id, &node.style, now_ms));
350        }
351
352        let bp_children = match blueprint {
353            Some(NodeBlueprint::Element { children, .. }) => Some(children.as_slice()),
354            Some(NodeBlueprint::Fragment(children)) => Some(children.as_slice()),
355            _ => None,
356        };
357
358        for (idx, child) in node.children.iter().enumerate() {
359            path.push(idx);
360            let child_bp = bp_children.and_then(|c| c.get(idx));
361            Self::sync_tree_animations_rec(
362                child,
363                child_bp,
364                node_id,
365                idx,
366                path,
367                now_ms,
368                previous_styles,
369                previous_sizes,
370                measured_auto_sizes,
371                new_base_styles,
372                new_node_paths,
373                new_path_node_ids,
374                transition_manager,
375                animation_manager,
376                trans_events,
377                anim_events,
378            );
379            path.pop();
380        }
381    }
382
383    /// Synchronizes paint-only CSS transitions strictly within the restyled subtree at
384    /// `subtree_path` without scanning the full document or disturbing active transitions
385    /// on unrelated subtrees.
386    pub(crate) fn sync_subtree_paint_transitions(&mut self, subtree_path: &[usize], now_ms: f64) {
387        let mut node_opt: Option<&mut LayoutNode> = Some(&mut self.layout_root);
388        for &idx in subtree_path {
389            node_opt = node_opt.and_then(|n| n.children.get_mut(idx));
390        }
391        let Some(subtree_root) = node_opt else {
392            return;
393        };
394
395        let mut path = subtree_path.to_vec();
396        let mut trans_events = Vec::new();
397        Self::sync_subtree_paint_transitions_rec(
398            subtree_root,
399            &mut path,
400            now_ms,
401            &self.path_node_ids,
402            &mut self.base_node_styles,
403            &mut self.previous_node_styles,
404            &mut self.transition_manager,
405            &self.animation_manager,
406            &mut trans_events,
407        );
408        for ev in trans_events {
409            self.dispatch_transition_event(ev);
410        }
411        if self.transition_manager.has_active_transitions()
412            || self.animation_manager.has_active_animations()
413        {
414            self.had_active_animations = true;
415        }
416    }
417
418    #[allow(clippy::too_many_arguments)]
419    fn sync_subtree_paint_transitions_rec(
420        node: &mut LayoutNode,
421        path: &mut Vec<usize>,
422        now_ms: f64,
423        path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
424        base_node_styles: &mut std::collections::HashMap<u64, ComputedStyle>,
425        previous_node_styles: &mut std::collections::HashMap<u64, ComputedStyle>,
426        transition_manager: &mut strata_style::transition::TransitionManager,
427        animation_manager: &strata_style::animation::AnimationManager,
428        trans_events: &mut Vec<strata_style::transition::TransitionLifecycleEvent>,
429    ) {
430        if let Some(&node_id) = path_node_ids.get(path) {
431            let old_style = base_node_styles
432                .get(&node_id)
433                .or_else(|| previous_node_styles.get(&node_id))
434                .cloned();
435            let new_base = node.style.clone();
436            if let Some(old) = old_style {
437                if !new_base.transitions.is_empty() {
438                    trans_events.extend(transition_manager.update_styles(
439                        node_id,
440                        &old,
441                        &new_base,
442                        now_ms,
443                    ));
444                }
445                previous_node_styles.insert(node_id, old);
446            }
447            base_node_styles.insert(node_id, new_base);
448            transition_manager.apply_to_style(node_id, &mut node.style);
449            animation_manager.apply_to_style(node_id, &mut node.style);
450            node.active_transitions = transition_manager.has_node_transitions(node_id);
451        }
452        for (idx, child) in node.children.iter_mut().enumerate() {
453            path.push(idx);
454            Self::sync_subtree_paint_transitions_rec(
455                child,
456                path,
457                now_ms,
458                path_node_ids,
459                base_node_styles,
460                previous_node_styles,
461                transition_manager,
462                animation_manager,
463                trans_events,
464            );
465            path.pop();
466        }
467    }
468
469    /// Restores the true post-cascade base styles from `self.base_node_styles` back onto
470    /// `self.layout_root` and clears in-flight collapse-lock overrides so incremental
471    /// reconciliation and subsequent animation syncs diff and reuse real target styles rather
472    /// than in-flight interpolated values.
473    pub(crate) fn restore_base_styles_to_layout_tree(&mut self) {
474        if self.base_node_styles.is_empty() {
475            return;
476        }
477        let mut path = Vec::new();
478        Self::restore_base_styles_rec(
479            &mut self.layout_root,
480            &mut path,
481            &self.path_node_ids,
482            &self.base_node_styles,
483        );
484    }
485
486    fn restore_base_styles_rec(
487        node: &mut LayoutNode,
488        path: &mut Vec<usize>,
489        path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
490        base_styles: &std::collections::HashMap<u64, ComputedStyle>,
491    ) {
492        let node_id = path_node_ids
493            .get(path)
494            .copied()
495            .unwrap_or_else(|| path_to_node_id(path));
496        if let Some(base) = base_styles.get(&node_id) {
497            node.style = base.clone();
498        }
499        node.transition_layout_width_px = None;
500        node.transition_layout_height_px = None;
501        for (idx, child) in node.children.iter_mut().enumerate() {
502            path.push(idx);
503            Self::restore_base_styles_rec(child, path, path_node_ids, base_styles);
504            path.pop();
505        }
506    }
507
508    /// Updates `base_node_styles` and `previous_node_styles` for a restyled non-transitioning
509    /// subtree so subsequent `apply_animations_to_layout_tree` / `restore_base_styles_to_layout_tree`
510    /// passes preserve the newly cascaded hover/interaction styles while unrelated animations run.
511    pub(crate) fn sync_subtree_base_styles(&mut self, subtree_path: &[usize]) {
512        let mut node_opt: Option<&LayoutNode> = Some(&self.layout_root);
513        for &idx in subtree_path {
514            node_opt = node_opt.and_then(|n| n.children.get(idx));
515        }
516        let Some(subtree_root) = node_opt else {
517            return;
518        };
519        let mut path = subtree_path.to_vec();
520        Self::sync_subtree_base_styles_rec(
521            subtree_root,
522            &mut path,
523            &self.path_node_ids,
524            &mut self.base_node_styles,
525            &mut self.previous_node_styles,
526        );
527    }
528
529    fn sync_subtree_base_styles_rec(
530        node: &LayoutNode,
531        path: &mut Vec<usize>,
532        path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
533        base_node_styles: &mut std::collections::HashMap<u64, ComputedStyle>,
534        previous_node_styles: &mut std::collections::HashMap<u64, ComputedStyle>,
535    ) {
536        if let Some(&node_id) = path_node_ids.get(path) {
537            let s = node.style.clone();
538            previous_node_styles.insert(node_id, s.clone());
539            base_node_styles.insert(node_id, s);
540        }
541        for (idx, child) in node.children.iter().enumerate() {
542            path.push(idx);
543            Self::sync_subtree_base_styles_rec(
544                child,
545                path,
546                path_node_ids,
547                base_node_styles,
548                previous_node_styles,
549            );
550            path.pop();
551        }
552    }
553
554    /// Applies active transition and animation values directly onto the layout tree.
555    pub fn apply_animations_to_layout_tree(&mut self) {
556        let has_anims = self.transition_manager.has_active_transitions()
557            || self.animation_manager.has_active_animations();
558        if !has_anims && !self.had_active_animations {
559            return;
560        }
561        self.had_active_animations = has_anims;
562
563        let mut path = Vec::new();
564        Self::apply_animations_rec(
565            &mut self.layout_root,
566            &mut path,
567            &self.path_node_ids,
568            &self.base_node_styles,
569            &self.transition_manager,
570            &self.animation_manager,
571            None,
572            (self.viewport_width, self.viewport_height),
573            (self.viewport_width, self.viewport_height),
574        );
575    }
576
577    #[allow(clippy::too_many_arguments)]
578    pub(crate) fn apply_animations_rec(
579        node: &mut LayoutNode,
580        path: &mut Vec<usize>,
581        path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
582        base_styles: &std::collections::HashMap<u64, ComputedStyle>,
583        transition_manager: &strata_style::transition::TransitionManager,
584        animation_manager: &strata_style::animation::AnimationManager,
585        inherited_color_override: Option<(strata_style::types::Color, strata_style::types::Color)>,
586        parent_size: (f32, f32),
587        viewport_size: (f32, f32),
588    ) {
589        let node_id = path_node_ids
590            .get(path)
591            .copied()
592            .unwrap_or_else(|| path_to_node_id(path));
593        if let Some(base) = base_styles.get(&node_id) {
594            node.style = base.clone();
595        }
596        let own_base_color = node.style.color;
597        if let Some((anc_base_color, anc_anim_color)) = inherited_color_override {
598            if own_base_color == anc_base_color {
599                node.style.color = anc_anim_color;
600            }
601        }
602        transition_manager.apply_to_style(node_id, &mut node.style);
603        animation_manager.apply_to_style(node_id, &mut node.style);
604        node.active_transitions = transition_manager.has_node_transitions(node_id);
605
606        let (lock_w, lock_h) = transition_manager.active_collapse_lock_dimensions(
607            node_id,
608            parent_size.0,
609            parent_size.1,
610            viewport_size.0,
611            viewport_size.1,
612            node.style.font_size,
613        );
614        node.transition_layout_width_px = lock_w;
615        node.transition_layout_height_px = lock_h;
616
617        let next_color_override = if node.style.color != own_base_color {
618            Some((own_base_color, node.style.color))
619        } else {
620            None
621        };
622
623        let child_parent_w = lock_w.unwrap_or(node.geometry.content_box.width).max(0.0);
624        let child_parent_h = lock_h.unwrap_or(node.geometry.content_box.height).max(0.0);
625        let child_parent = if child_parent_w > 0.0 || child_parent_h > 0.0 {
626            (child_parent_w, child_parent_h)
627        } else {
628            parent_size
629        };
630
631        for (idx, child) in node.children.iter_mut().enumerate() {
632            path.push(idx);
633            Self::apply_animations_rec(
634                child,
635                path,
636                path_node_ids,
637                base_styles,
638                transition_manager,
639                animation_manager,
640                next_color_override,
641                child_parent,
642                viewport_size,
643            );
644            path.pop();
645        }
646    }
647
648    /// Evaluates all active scroll-driven animations based on current container scroll positions.
649    pub fn evaluate_scroll_animations(
650        &mut self,
651        anim_events: &mut Vec<strata_style::animation::AnimationLifecycleEvent>,
652    ) {
653        for (node_id, path) in &self.node_paths {
654            if let Some(style) = self.base_node_styles.get(node_id) {
655                for anim in &style.animations {
656                    match &anim.timeline {
657                        strata_style::AnimationTimeline::Scroll(src, _axis) => {
658                            let scroll_progress = match src {
659                                strata_style::ScrollTimelineSource::Root => self
660                                    .active_scrollbars
661                                    .iter()
662                                    .max_by(|a, b| {
663                                        (a.bounds.width * a.bounds.height)
664                                            .partial_cmp(&(b.bounds.width * b.bounds.height))
665                                            .unwrap_or(std::cmp::Ordering::Equal)
666                                    })
667                                    .map(|b| {
668                                        if b.max_scroll_y > 0.0 {
669                                            (b.scroll_y / b.max_scroll_y).clamp(0.0, 1.0)
670                                        } else {
671                                            0.0
672                                        }
673                                    })
674                                    .unwrap_or(0.0),
675                                strata_style::ScrollTimelineSource::Nearest
676                                | strata_style::ScrollTimelineSource::SelfNode => {
677                                    let mut p = 0.0;
678                                    let mut check_path = path.clone();
679                                    while !check_path.is_empty() {
680                                        if let Some((_, sy)) = self.scroll_offsets.get(&check_path)
681                                        {
682                                            if let Some(bar) = self
683                                                .active_scrollbars
684                                                .iter()
685                                                .find(|b| b.path == check_path)
686                                            {
687                                                if bar.max_scroll_y > 0.0 {
688                                                    p = (*sy / bar.max_scroll_y).clamp(0.0, 1.0);
689                                                    break;
690                                                }
691                                            }
692                                        }
693                                        check_path.pop();
694                                    }
695                                    p
696                                }
697                            };
698                            anim_events.extend(self.animation_manager.step_node_scroll_progress(
699                                *node_id,
700                                scroll_progress,
701                                style,
702                            ));
703                        }
704                        strata_style::AnimationTimeline::View(_axis, _start, _end) => {
705                            let p = 0.5;
706                            anim_events.extend(
707                                self.animation_manager
708                                    .step_node_scroll_progress(*node_id, p, style),
709                            );
710                        }
711                        _ => {}
712                    }
713                }
714            }
715        }
716    }
717
718    /// Evaluates scroll-driven animations synchronously during container scroll, consuming 0% CPU when stationary.
719    pub fn sync_scroll_animations(&mut self) {
720        let mut anim_events = Vec::new();
721        self.evaluate_scroll_animations(&mut anim_events);
722        for ev in anim_events {
723            self.dispatch_animation_event(ev);
724        }
725        self.apply_animations_to_layout_tree();
726    }
727
728    /// Captures element layout bounding boxes for elements with `view-transition-name` before DOM mutation.
729    pub fn capture_view_transitions(&mut self) {
730        let mut named = Vec::new();
731        Self::collect_view_transition_elements(&self.layout_root, &mut named);
732        self.view_transition_manager.capture_old_state(&named);
733    }
734
735    /// Triggers a view transition after DOM mutation, pairing old bounds with new layout bounds.
736    pub fn start_view_transition(&mut self, duration_ms: f32) {
737        let mut named = Vec::new();
738        Self::collect_view_transition_elements(&self.layout_root, &mut named);
739        let now_ms = self.now_ms();
740        self.view_transition_manager
741            .start_transition(&named, now_ms, duration_ms);
742    }
743
744    pub(crate) fn collect_view_transition_elements(
745        node: &LayoutNode,
746        out: &mut Vec<(String, strata_primitives::geom::Rect)>,
747    ) {
748        if let Some(name) = &node.style.view_transition_name {
749            if name != "none" {
750                out.push((name.clone(), node.geometry.border_box.into()));
751            }
752        }
753        for child in &node.children {
754            Self::collect_view_transition_elements(child, out);
755        }
756    }
757
758    /// Returns true if any CSS property transitions or view transitions are currently active.
759    pub fn has_active_transitions(&self) -> bool {
760        self.transition_manager.has_active_transitions()
761            || self.view_transition_manager.has_active_transitions()
762            || self.layout_root.has_active_transitions()
763    }
764
765    /// Returns true if there are any active transitions or keyframe animations running.
766    pub fn has_active_animations(&self) -> bool {
767        self.transition_manager.has_active_transitions()
768            || self.animation_manager.has_time_based_animations()
769            || self.view_transition_manager.has_active_transitions()
770    }
771
772    /// Advances active animations and transitions by current runtime clock time.
773    /// Returns true if any animation stepped and a redraw is needed.
774    #[inline]
775    pub fn poll_animations(&mut self) -> bool {
776        let now = self.now();
777        self.poll_animations_at(now)
778    }
779
780    /// Advances the virtual clock by `dt` and steps active animations/transitions at that instant.
781    pub fn advance_animations(&mut self, dt: std::time::Duration) -> bool {
782        let now = self.advance_clock(dt);
783        self.poll_animations_at(now)
784    }
785
786    /// Advances active animations and transitions at an explicit monotonic `Instant`.
787    /// Returns true if any animation stepped and a redraw is needed.
788    pub fn poll_animations_at(&mut self, now: std::time::Instant) -> bool {
789        if !self.has_active_animations() {
790            return false;
791        }
792
793        // Capture layout-affecting node IDs before advancing: a transition or animation that
794        // finishes on this tick is removed/settled by `advance`, but the final layout value it
795        // produced still has to be laid out once with invalidated ancestor/sibling caches.
796        let mut layout_node_ids = self.transition_manager.layout_affecting_node_ids();
797        layout_node_ids.extend(self.animation_manager.layout_affecting_node_ids());
798        let layout_affecting = !layout_node_ids.is_empty()
799            || self.transition_manager.has_layout_affecting_transitions()
800            || self.animation_manager.has_layout_affecting_animations();
801
802        let now_ms = now
803            .saturating_duration_since(self.runtime_start_epoch)
804            .as_secs_f64()
805            * 1000.0;
806        let trans_events = self.transition_manager.advance(now_ms);
807        let anim_events = self
808            .animation_manager
809            .advance(now_ms, &self.base_node_styles);
810        let _vt_active = self.view_transition_manager.step(now_ms);
811
812        for ev in trans_events {
813            self.dispatch_transition_event(ev);
814        }
815        for ev in anim_events {
816            self.dispatch_animation_event(ev);
817        }
818
819        self.apply_animations_to_layout_tree();
820
821        // Paint-only animations (colour, opacity, transform, shadow, ...) write new style
822        // values onto the existing layout tree. Only properties that feed box layout require
823        // a fresh layout pass; everything else just needs the display list recompiled.
824        if layout_affecting {
825            self.invalidate_layout_for_node_ids(&layout_node_ids);
826            self.tick_frame();
827        } else {
828            strata_layout::box_model::refresh_inline_fragment_styles(&mut self.layout_root);
829            self.compile_display_list();
830        }
831
832        true
833    }
834
835    /// Invalidates cached layout geometry for each layout-animating node's ancestors and
836    /// parent container subtree so flex/grid/percentage siblings reflow smoothly on tick.
837    pub(crate) fn invalidate_layout_for_node_ids(&mut self, node_ids: &[u64]) {
838        if node_ids.is_empty() {
839            self.layout_root.invalidate_cache();
840            return;
841        }
842
843        let mut invalidated_parents: std::collections::HashSet<Vec<usize>> =
844            std::collections::HashSet::with_capacity(node_ids.len());
845        for &node_id in node_ids {
846            let Some(path) = self.node_paths.get(&node_id).cloned() else {
847                self.layout_root.invalidate_cache();
848                return;
849            };
850            self.layout_root.invalidate_ancestors(&path);
851            let parent_path: Vec<usize> = if path.is_empty() {
852                Vec::new()
853            } else {
854                path[..path.len() - 1].to_vec()
855            };
856            if invalidated_parents.insert(parent_path.clone()) {
857                if let Some(parent_node) =
858                    Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
859                {
860                    parent_node.invalidate_cache();
861                } else {
862                    self.layout_root.invalidate_cache();
863                    return;
864                }
865            }
866        }
867    }
868
869    /// Dispatches a synthetic W3C animation lifecycle event to matching RSX element event listeners.
870    pub fn dispatch_animation_event(
871        &self,
872        event: strata_style::animation::AnimationLifecycleEvent,
873    ) {
874        let (node_id, name, elapsed, event_type) = match event {
875            strata_style::animation::AnimationLifecycleEvent::Start {
876                node_id,
877                name,
878                elapsed_time_sec,
879            } => (
880                node_id,
881                name,
882                elapsed_time_sec,
883                strata_dom::EventType::AnimationStart,
884            ),
885            strata_style::animation::AnimationLifecycleEvent::Iteration {
886                node_id,
887                name,
888                elapsed_time_sec,
889            } => (
890                node_id,
891                name,
892                elapsed_time_sec,
893                strata_dom::EventType::AnimationIteration,
894            ),
895            strata_style::animation::AnimationLifecycleEvent::End {
896                node_id,
897                name,
898                elapsed_time_sec,
899            } => (
900                node_id,
901                name,
902                elapsed_time_sec,
903                strata_dom::EventType::AnimationEnd,
904            ),
905            strata_style::animation::AnimationLifecycleEvent::Cancel {
906                node_id,
907                name,
908                elapsed_time_sec,
909            } => (
910                node_id,
911                name,
912                elapsed_time_sec,
913                strata_dom::EventType::AnimationCancel,
914            ),
915        };
916
917        if let Some(path) = self.node_paths.get(&node_id) {
918            if let Some(bp) = Self::find_blueprint_at_path(&self.root_blueprint, path) {
919                if let NodeBlueprint::Element { attributes, .. } = bp {
920                    for attr in attributes {
921                        if let strata_dom::Attribute::EventListener {
922                            event: ev_type,
923                            handler,
924                        } = attr
925                        {
926                            if *ev_type == event_type {
927                                let ev =
928                                    strata_dom::Event::animation(event_type, name.clone(), elapsed);
929                                handler(ev);
930                            }
931                        }
932                    }
933                }
934            }
935        }
936    }
937
938    /// Dispatches a synthetic W3C transition lifecycle event to matching RSX element event listeners.
939    pub fn dispatch_transition_event(
940        &self,
941        event: strata_style::transition::TransitionLifecycleEvent,
942    ) {
943        let (node_id, name, elapsed, event_type) = match event {
944            strata_style::transition::TransitionLifecycleEvent::Run {
945                node_id,
946                property,
947                elapsed_time_sec,
948            } => (
949                node_id,
950                property,
951                elapsed_time_sec,
952                strata_dom::EventType::TransitionRun,
953            ),
954            strata_style::transition::TransitionLifecycleEvent::Start {
955                node_id,
956                property,
957                elapsed_time_sec,
958            } => (
959                node_id,
960                property,
961                elapsed_time_sec,
962                strata_dom::EventType::TransitionStart,
963            ),
964            strata_style::transition::TransitionLifecycleEvent::End {
965                node_id,
966                property,
967                elapsed_time_sec,
968            } => (
969                node_id,
970                property,
971                elapsed_time_sec,
972                strata_dom::EventType::TransitionEnd,
973            ),
974            strata_style::transition::TransitionLifecycleEvent::Cancel {
975                node_id,
976                property,
977                elapsed_time_sec,
978            } => (
979                node_id,
980                property,
981                elapsed_time_sec,
982                strata_dom::EventType::TransitionCancel,
983            ),
984        };
985
986        if let Some(path) = self.node_paths.get(&node_id) {
987            if let Some(bp) = Self::find_blueprint_at_path(&self.root_blueprint, path) {
988                if let NodeBlueprint::Element { attributes, .. } = bp {
989                    for attr in attributes {
990                        if let strata_dom::Attribute::EventListener {
991                            event: ev_type,
992                            handler,
993                        } = attr
994                        {
995                            if *ev_type == event_type {
996                                let ev = strata_dom::Event::transition(
997                                    event_type,
998                                    name.clone(),
999                                    elapsed,
1000                                );
1001                                handler(ev);
1002                            }
1003                        }
1004                    }
1005                }
1006            }
1007        }
1008    }
1009
1010    /// Registers all parsed `@keyframes` rules from a stylesheet into the runtime animation registry.
1011    pub fn register_keyframes_stylesheet(&mut self, sheet: &strata_style::StyleSheet) {
1012        self.animation_manager
1013            .registry_mut()
1014            .register_stylesheet(sheet);
1015    }
1016
1017    /// Registers a single compiled `@keyframes` rule into the runtime animation registry.
1018    pub fn register_keyframe_rule(&mut self, rule: &strata_style::KeyframeRule) {
1019        self.animation_manager.registry_mut().register_rule(rule);
1020    }
1021}