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.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
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 clock time.
773    /// Returns true if any animation stepped and a redraw is needed.
774    pub fn poll_animations(&mut self) -> bool {
775        if !self.has_active_animations() {
776            return false;
777        }
778
779        // Capture layout-affecting node IDs before advancing: a transition or animation that
780        // finishes on this tick is removed/settled by `advance`, but the final layout value it
781        // produced still has to be laid out once with invalidated ancestor/sibling caches.
782        let mut layout_node_ids = self.transition_manager.layout_affecting_node_ids();
783        layout_node_ids.extend(self.animation_manager.layout_affecting_node_ids());
784        let layout_affecting = !layout_node_ids.is_empty()
785            || self.transition_manager.has_layout_affecting_transitions()
786            || self.animation_manager.has_layout_affecting_animations();
787
788        let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
789        let trans_events = self.transition_manager.advance(now_ms);
790        let anim_events = self
791            .animation_manager
792            .advance(now_ms, &self.base_node_styles);
793        let _vt_active = self.view_transition_manager.step(now_ms);
794
795        for ev in trans_events {
796            self.dispatch_transition_event(ev);
797        }
798        for ev in anim_events {
799            self.dispatch_animation_event(ev);
800        }
801
802        self.apply_animations_to_layout_tree();
803
804        // Paint-only animations (colour, opacity, transform, shadow, ...) write new style
805        // values onto the existing layout tree. Only properties that feed box layout require
806        // a fresh layout pass; everything else just needs the display list recompiled.
807        if layout_affecting {
808            self.invalidate_layout_for_node_ids(&layout_node_ids);
809            self.tick_frame();
810        } else {
811            strata_layout::box_model::refresh_inline_fragment_styles(&mut self.layout_root);
812            self.compile_display_list();
813        }
814
815        true
816    }
817
818    /// Invalidates cached layout geometry for each layout-animating node's ancestors and
819    /// parent container subtree so flex/grid/percentage siblings reflow smoothly on tick.
820    pub(crate) fn invalidate_layout_for_node_ids(&mut self, node_ids: &[u64]) {
821        if node_ids.is_empty() {
822            self.layout_root.invalidate_cache();
823            return;
824        }
825
826        let mut invalidated_parents: std::collections::HashSet<Vec<usize>> =
827            std::collections::HashSet::with_capacity(node_ids.len());
828        for &node_id in node_ids {
829            let Some(path) = self.node_paths.get(&node_id).cloned() else {
830                self.layout_root.invalidate_cache();
831                return;
832            };
833            self.layout_root.invalidate_ancestors(&path);
834            let parent_path: Vec<usize> = if path.is_empty() {
835                Vec::new()
836            } else {
837                path[..path.len() - 1].to_vec()
838            };
839            if invalidated_parents.insert(parent_path.clone()) {
840                if let Some(parent_node) =
841                    Self::find_layout_node_mut(&mut self.layout_root, &parent_path)
842                {
843                    parent_node.invalidate_cache();
844                } else {
845                    self.layout_root.invalidate_cache();
846                    return;
847                }
848            }
849        }
850    }
851
852    /// Dispatches a synthetic W3C animation lifecycle event to matching RSX element event listeners.
853    pub fn dispatch_animation_event(
854        &self,
855        event: strata_style::animation::AnimationLifecycleEvent,
856    ) {
857        let (node_id, name, elapsed, event_type) = match event {
858            strata_style::animation::AnimationLifecycleEvent::Start {
859                node_id,
860                name,
861                elapsed_time_sec,
862            } => (
863                node_id,
864                name,
865                elapsed_time_sec,
866                strata_dom::EventType::AnimationStart,
867            ),
868            strata_style::animation::AnimationLifecycleEvent::Iteration {
869                node_id,
870                name,
871                elapsed_time_sec,
872            } => (
873                node_id,
874                name,
875                elapsed_time_sec,
876                strata_dom::EventType::AnimationIteration,
877            ),
878            strata_style::animation::AnimationLifecycleEvent::End {
879                node_id,
880                name,
881                elapsed_time_sec,
882            } => (
883                node_id,
884                name,
885                elapsed_time_sec,
886                strata_dom::EventType::AnimationEnd,
887            ),
888            strata_style::animation::AnimationLifecycleEvent::Cancel {
889                node_id,
890                name,
891                elapsed_time_sec,
892            } => (
893                node_id,
894                name,
895                elapsed_time_sec,
896                strata_dom::EventType::AnimationCancel,
897            ),
898        };
899
900        if let Some(path) = self.node_paths.get(&node_id) {
901            if let Some(bp) = Self::find_blueprint_at_path(&self.root_blueprint, path) {
902                if let NodeBlueprint::Element { attributes, .. } = bp {
903                    for attr in attributes {
904                        if let strata_dom::Attribute::EventListener {
905                            event: ev_type,
906                            handler,
907                        } = attr
908                        {
909                            if *ev_type == event_type {
910                                let ev =
911                                    strata_dom::Event::animation(event_type, name.clone(), elapsed);
912                                handler(ev);
913                            }
914                        }
915                    }
916                }
917            }
918        }
919    }
920
921    /// Dispatches a synthetic W3C transition lifecycle event to matching RSX element event listeners.
922    pub fn dispatch_transition_event(
923        &self,
924        event: strata_style::transition::TransitionLifecycleEvent,
925    ) {
926        let (node_id, name, elapsed, event_type) = match event {
927            strata_style::transition::TransitionLifecycleEvent::Run {
928                node_id,
929                property,
930                elapsed_time_sec,
931            } => (
932                node_id,
933                property,
934                elapsed_time_sec,
935                strata_dom::EventType::TransitionRun,
936            ),
937            strata_style::transition::TransitionLifecycleEvent::Start {
938                node_id,
939                property,
940                elapsed_time_sec,
941            } => (
942                node_id,
943                property,
944                elapsed_time_sec,
945                strata_dom::EventType::TransitionStart,
946            ),
947            strata_style::transition::TransitionLifecycleEvent::End {
948                node_id,
949                property,
950                elapsed_time_sec,
951            } => (
952                node_id,
953                property,
954                elapsed_time_sec,
955                strata_dom::EventType::TransitionEnd,
956            ),
957            strata_style::transition::TransitionLifecycleEvent::Cancel {
958                node_id,
959                property,
960                elapsed_time_sec,
961            } => (
962                node_id,
963                property,
964                elapsed_time_sec,
965                strata_dom::EventType::TransitionCancel,
966            ),
967        };
968
969        if let Some(path) = self.node_paths.get(&node_id) {
970            if let Some(bp) = Self::find_blueprint_at_path(&self.root_blueprint, path) {
971                if let NodeBlueprint::Element { attributes, .. } = bp {
972                    for attr in attributes {
973                        if let strata_dom::Attribute::EventListener {
974                            event: ev_type,
975                            handler,
976                        } = attr
977                        {
978                            if *ev_type == event_type {
979                                let ev = strata_dom::Event::transition(
980                                    event_type,
981                                    name.clone(),
982                                    elapsed,
983                                );
984                                handler(ev);
985                            }
986                        }
987                    }
988                }
989            }
990        }
991    }
992
993    /// Registers all parsed `@keyframes` rules from a stylesheet into the runtime animation registry.
994    pub fn register_keyframes_stylesheet(&mut self, sheet: &strata_style::StyleSheet) {
995        self.animation_manager
996            .registry_mut()
997            .register_stylesheet(sheet);
998    }
999
1000    /// Registers a single compiled `@keyframes` rule into the runtime animation registry.
1001    pub fn register_keyframe_rule(&mut self, rule: &strata_style::KeyframeRule) {
1002        self.animation_manager.registry_mut().register_rule(rule);
1003    }
1004}