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    /// Synchronizes running animations and transitions with the current layout tree.
72    pub fn sync_tree_animations(&mut self, now_ms: f64) {
73        let mut new_base_styles = std::collections::HashMap::new();
74        let mut new_node_paths = std::collections::HashMap::new();
75        let mut new_path_node_ids = std::collections::HashMap::new();
76        let mut path_buf = Vec::new();
77
78        let mut trans_events = Vec::new();
79        let mut anim_events = Vec::new();
80
81        Self::sync_tree_animations_rec(
82            &self.layout_root,
83            Some(&self.root_blueprint),
84            0xcbf29ce484222325u64,
85            0,
86            &mut path_buf,
87            now_ms,
88            &self.previous_node_styles,
89            &mut new_base_styles,
90            &mut new_node_paths,
91            &mut new_path_node_ids,
92            &mut self.transition_manager,
93            &mut self.animation_manager,
94            &mut trans_events,
95            &mut anim_events,
96        );
97
98        self.base_node_styles = new_base_styles;
99        self.previous_node_styles = self.base_node_styles.clone();
100        self.node_paths = new_node_paths;
101        self.path_node_ids = new_path_node_ids;
102
103        // Prune any transitions/animations belonging to unmounted or replaced elements
104        // so dead nodes never leak state or keep frame ticks alive.
105        self.transition_manager
106            .retain_nodes(|id| self.base_node_styles.contains_key(id));
107        self.animation_manager
108            .retain_nodes(|id| self.base_node_styles.contains_key(id));
109
110        // Evaluate scroll-driven animations progress
111        self.evaluate_scroll_animations(&mut anim_events);
112
113        for ev in trans_events {
114            self.dispatch_transition_event(ev);
115        }
116        for ev in anim_events {
117            self.dispatch_animation_event(ev);
118        }
119
120        self.apply_animations_to_layout_tree();
121    }
122
123    #[allow(clippy::too_many_arguments)]
124    pub(crate) fn sync_tree_animations_rec(
125        node: &LayoutNode,
126        blueprint: Option<&NodeBlueprint>,
127        parent_hash: u64,
128        child_index: usize,
129        path: &mut Vec<usize>,
130        now_ms: f64,
131        previous_styles: &std::collections::HashMap<u64, ComputedStyle>,
132        new_base_styles: &mut std::collections::HashMap<u64, ComputedStyle>,
133        new_node_paths: &mut std::collections::HashMap<u64, Vec<usize>>,
134        new_path_node_ids: &mut std::collections::HashMap<Vec<usize>, u64>,
135        transition_manager: &mut strata_style::transition::TransitionManager,
136        animation_manager: &mut strata_style::animation::AnimationManager,
137        trans_events: &mut Vec<strata_style::transition::TransitionLifecycleEvent>,
138        anim_events: &mut Vec<strata_style::animation::AnimationLifecycleEvent>,
139    ) {
140        let node_id = blueprint_node_identity_hash(parent_hash, child_index, blueprint);
141        new_base_styles.insert(node_id, node.style.clone());
142        new_node_paths.insert(node_id, path.clone());
143        new_path_node_ids.insert(path.clone(), node_id);
144
145        // Check for transitions if we have a previous style or @starting-style
146        let effective_old_style = match previous_styles.get(&node_id) {
147            Some(old) if old.display != strata_style::Display::None => {
148                if old.transitions.is_empty()
149                    && !node.style.transitions.is_empty()
150                    && !blueprint_has_explicit_identity(blueprint)
151                {
152                    node.style.starting_style.as_deref()
153                } else {
154                    Some(old)
155                }
156            }
157            _ => node.style.starting_style.as_deref(),
158        };
159
160        if let Some(old_style) = effective_old_style {
161            if !node.style.transitions.is_empty() {
162                trans_events.extend(transition_manager.update_styles(
163                    node_id,
164                    old_style,
165                    &node.style,
166                    now_ms,
167                ));
168            }
169        }
170
171        // Check for keyframe animations
172        if !node.style.animations.is_empty() || animation_manager.has_active_animations() {
173            anim_events.extend(animation_manager.update_styles(node_id, &node.style, now_ms));
174        }
175
176        let bp_children = match blueprint {
177            Some(NodeBlueprint::Element { children, .. }) => Some(children.as_slice()),
178            Some(NodeBlueprint::Fragment(children)) => Some(children.as_slice()),
179            _ => None,
180        };
181
182        for (idx, child) in node.children.iter().enumerate() {
183            path.push(idx);
184            let child_bp = bp_children.and_then(|c| c.get(idx));
185            Self::sync_tree_animations_rec(
186                child,
187                child_bp,
188                node_id,
189                idx,
190                path,
191                now_ms,
192                previous_styles,
193                new_base_styles,
194                new_node_paths,
195                new_path_node_ids,
196                transition_manager,
197                animation_manager,
198                trans_events,
199                anim_events,
200            );
201            path.pop();
202        }
203    }
204
205    /// Applies active transition and animation values directly onto the layout tree.
206    pub fn apply_animations_to_layout_tree(&mut self) {
207        let has_anims = self.transition_manager.has_active_transitions()
208            || self.animation_manager.has_active_animations();
209        if !has_anims && !self.had_active_animations {
210            return;
211        }
212        self.had_active_animations = has_anims;
213
214        let mut path = Vec::new();
215        Self::apply_animations_rec(
216            &mut self.layout_root,
217            &mut path,
218            &self.path_node_ids,
219            &self.base_node_styles,
220            &self.transition_manager,
221            &self.animation_manager,
222            None,
223        );
224    }
225
226    pub(crate) fn apply_animations_rec(
227        node: &mut LayoutNode,
228        path: &mut Vec<usize>,
229        path_node_ids: &std::collections::HashMap<Vec<usize>, u64>,
230        base_styles: &std::collections::HashMap<u64, ComputedStyle>,
231        transition_manager: &strata_style::transition::TransitionManager,
232        animation_manager: &strata_style::animation::AnimationManager,
233        inherited_color_override: Option<(strata_style::types::Color, strata_style::types::Color)>,
234    ) {
235        let node_id = path_node_ids
236            .get(path)
237            .copied()
238            .unwrap_or_else(|| path_to_node_id(path));
239        if let Some(base) = base_styles.get(&node_id) {
240            node.style = base.clone();
241        }
242        let own_base_color = node.style.color;
243        if let Some((anc_base_color, anc_anim_color)) = inherited_color_override {
244            if own_base_color == anc_base_color {
245                node.style.color = anc_anim_color;
246            }
247        }
248        transition_manager.apply_to_style(node_id, &mut node.style);
249        animation_manager.apply_to_style(node_id, &mut node.style);
250        node.active_transitions = transition_manager.has_node_transitions(node_id);
251
252        let next_color_override = if node.style.color != own_base_color {
253            Some((own_base_color, node.style.color))
254        } else {
255            None
256        };
257
258        for (idx, child) in node.children.iter_mut().enumerate() {
259            path.push(idx);
260            Self::apply_animations_rec(
261                child,
262                path,
263                path_node_ids,
264                base_styles,
265                transition_manager,
266                animation_manager,
267                next_color_override,
268            );
269            path.pop();
270        }
271    }
272
273    /// Evaluates all active scroll-driven animations based on current container scroll positions.
274    pub fn evaluate_scroll_animations(
275        &mut self,
276        anim_events: &mut Vec<strata_style::animation::AnimationLifecycleEvent>,
277    ) {
278        for (node_id, path) in &self.node_paths {
279            if let Some(style) = self.base_node_styles.get(node_id) {
280                for anim in &style.animations {
281                    match &anim.timeline {
282                        strata_style::AnimationTimeline::Scroll(src, _axis) => {
283                            let scroll_progress = match src {
284                                strata_style::ScrollTimelineSource::Root => self
285                                    .active_scrollbars
286                                    .iter()
287                                    .max_by(|a, b| {
288                                        (a.bounds.width * a.bounds.height)
289                                            .partial_cmp(&(b.bounds.width * b.bounds.height))
290                                            .unwrap_or(std::cmp::Ordering::Equal)
291                                    })
292                                    .map(|b| {
293                                        if b.max_scroll_y > 0.0 {
294                                            (b.scroll_y / b.max_scroll_y).clamp(0.0, 1.0)
295                                        } else {
296                                            0.0
297                                        }
298                                    })
299                                    .unwrap_or(0.0),
300                                strata_style::ScrollTimelineSource::Nearest
301                                | strata_style::ScrollTimelineSource::SelfNode => {
302                                    let mut p = 0.0;
303                                    let mut check_path = path.clone();
304                                    while !check_path.is_empty() {
305                                        if let Some((_, sy)) = self.scroll_offsets.get(&check_path)
306                                        {
307                                            if let Some(bar) = self
308                                                .active_scrollbars
309                                                .iter()
310                                                .find(|b| b.path == check_path)
311                                            {
312                                                if bar.max_scroll_y > 0.0 {
313                                                    p = (*sy / bar.max_scroll_y).clamp(0.0, 1.0);
314                                                    break;
315                                                }
316                                            }
317                                        }
318                                        check_path.pop();
319                                    }
320                                    p
321                                }
322                            };
323                            anim_events.extend(self.animation_manager.step_node_scroll_progress(
324                                *node_id,
325                                scroll_progress,
326                                style,
327                            ));
328                        }
329                        strata_style::AnimationTimeline::View(_axis, _start, _end) => {
330                            let p = 0.5;
331                            anim_events.extend(
332                                self.animation_manager
333                                    .step_node_scroll_progress(*node_id, p, style),
334                            );
335                        }
336                        _ => {}
337                    }
338                }
339            }
340        }
341    }
342
343    /// Evaluates scroll-driven animations synchronously during container scroll, consuming 0% CPU when stationary.
344    pub fn sync_scroll_animations(&mut self) {
345        let mut anim_events = Vec::new();
346        self.evaluate_scroll_animations(&mut anim_events);
347        for ev in anim_events {
348            self.dispatch_animation_event(ev);
349        }
350        self.apply_animations_to_layout_tree();
351    }
352
353    /// Captures element layout bounding boxes for elements with `view-transition-name` before DOM mutation.
354    pub fn capture_view_transitions(&mut self) {
355        let mut named = Vec::new();
356        Self::collect_view_transition_elements(&self.layout_root, &mut named);
357        self.view_transition_manager.capture_old_state(&named);
358    }
359
360    /// Triggers a view transition after DOM mutation, pairing old bounds with new layout bounds.
361    pub fn start_view_transition(&mut self, duration_ms: f32) {
362        let mut named = Vec::new();
363        Self::collect_view_transition_elements(&self.layout_root, &mut named);
364        let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
365        self.view_transition_manager
366            .start_transition(&named, now_ms, duration_ms);
367    }
368
369    pub(crate) fn collect_view_transition_elements(
370        node: &LayoutNode,
371        out: &mut Vec<(String, strata_primitives::geom::Rect)>,
372    ) {
373        if let Some(name) = &node.style.view_transition_name {
374            if name != "none" {
375                out.push((name.clone(), node.geometry.border_box.into()));
376            }
377        }
378        for child in &node.children {
379            Self::collect_view_transition_elements(child, out);
380        }
381    }
382
383    /// Returns true if any CSS property transitions or view transitions are currently active.
384    pub fn has_active_transitions(&self) -> bool {
385        self.transition_manager.has_active_transitions()
386            || self.view_transition_manager.has_active_transitions()
387            || self.layout_root.has_active_transitions()
388    }
389
390    /// Returns true if there are any active transitions or keyframe animations running.
391    pub fn has_active_animations(&self) -> bool {
392        self.transition_manager.has_active_transitions()
393            || self.animation_manager.has_time_based_animations()
394            || self.view_transition_manager.has_active_transitions()
395    }
396
397    /// Advances active animations and transitions by current clock time.
398    /// Returns true if any animation stepped and a redraw is needed.
399    pub fn poll_animations(&mut self) -> bool {
400        if !self.has_active_animations() {
401            return false;
402        }
403
404        // Capture this before advancing: a transition or animation that finishes on this
405        // tick is removed/settled by `advance`, but the final layout value it produced still
406        // has to be laid out once.
407        let layout_affecting = self.transition_manager.has_layout_affecting_transitions()
408            || self.animation_manager.has_layout_affecting_animations();
409
410        let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
411        let trans_events = self.transition_manager.advance(now_ms);
412        let anim_events = self
413            .animation_manager
414            .advance(now_ms, &self.base_node_styles);
415        let _vt_active = self.view_transition_manager.step(now_ms);
416
417        for ev in trans_events {
418            self.dispatch_transition_event(ev);
419        }
420        for ev in anim_events {
421            self.dispatch_animation_event(ev);
422        }
423
424        self.apply_animations_to_layout_tree();
425
426        // Paint-only animations (colour, opacity, transform, shadow, ...) write new style
427        // values onto the existing layout tree. Only properties that feed box layout require
428        // a fresh layout pass; everything else just needs the display list recompiled.
429        if layout_affecting {
430            self.tick_frame();
431        } else {
432            strata_layout::box_model::refresh_inline_fragment_styles(&mut self.layout_root);
433            self.compile_display_list();
434        }
435
436        true
437    }
438
439    /// Dispatches a synthetic W3C animation lifecycle event to matching RSX element event listeners.
440    pub fn dispatch_animation_event(
441        &self,
442        event: strata_style::animation::AnimationLifecycleEvent,
443    ) {
444        let (node_id, name, elapsed, event_type) = match event {
445            strata_style::animation::AnimationLifecycleEvent::Start {
446                node_id,
447                name,
448                elapsed_time_sec,
449            } => (
450                node_id,
451                name,
452                elapsed_time_sec,
453                strata_dom::EventType::AnimationStart,
454            ),
455            strata_style::animation::AnimationLifecycleEvent::Iteration {
456                node_id,
457                name,
458                elapsed_time_sec,
459            } => (
460                node_id,
461                name,
462                elapsed_time_sec,
463                strata_dom::EventType::AnimationIteration,
464            ),
465            strata_style::animation::AnimationLifecycleEvent::End {
466                node_id,
467                name,
468                elapsed_time_sec,
469            } => (
470                node_id,
471                name,
472                elapsed_time_sec,
473                strata_dom::EventType::AnimationEnd,
474            ),
475            strata_style::animation::AnimationLifecycleEvent::Cancel {
476                node_id,
477                name,
478                elapsed_time_sec,
479            } => (
480                node_id,
481                name,
482                elapsed_time_sec,
483                strata_dom::EventType::AnimationCancel,
484            ),
485        };
486
487        if let Some(path) = self.node_paths.get(&node_id) {
488            if let Some(bp) = Self::find_blueprint_at_path(&self.root_blueprint, path) {
489                if let NodeBlueprint::Element { attributes, .. } = bp {
490                    for attr in attributes {
491                        if let strata_dom::Attribute::EventListener {
492                            event: ev_type,
493                            handler,
494                        } = attr
495                        {
496                            if *ev_type == event_type {
497                                let ev =
498                                    strata_dom::Event::animation(event_type, name.clone(), elapsed);
499                                handler(ev);
500                            }
501                        }
502                    }
503                }
504            }
505        }
506    }
507
508    /// Dispatches a synthetic W3C transition lifecycle event to matching RSX element event listeners.
509    pub fn dispatch_transition_event(
510        &self,
511        event: strata_style::transition::TransitionLifecycleEvent,
512    ) {
513        let (node_id, name, elapsed, event_type) = match event {
514            strata_style::transition::TransitionLifecycleEvent::Run {
515                node_id,
516                property,
517                elapsed_time_sec,
518            } => (
519                node_id,
520                property,
521                elapsed_time_sec,
522                strata_dom::EventType::TransitionRun,
523            ),
524            strata_style::transition::TransitionLifecycleEvent::Start {
525                node_id,
526                property,
527                elapsed_time_sec,
528            } => (
529                node_id,
530                property,
531                elapsed_time_sec,
532                strata_dom::EventType::TransitionStart,
533            ),
534            strata_style::transition::TransitionLifecycleEvent::End {
535                node_id,
536                property,
537                elapsed_time_sec,
538            } => (
539                node_id,
540                property,
541                elapsed_time_sec,
542                strata_dom::EventType::TransitionEnd,
543            ),
544            strata_style::transition::TransitionLifecycleEvent::Cancel {
545                node_id,
546                property,
547                elapsed_time_sec,
548            } => (
549                node_id,
550                property,
551                elapsed_time_sec,
552                strata_dom::EventType::TransitionCancel,
553            ),
554        };
555
556        if let Some(path) = self.node_paths.get(&node_id) {
557            if let Some(bp) = Self::find_blueprint_at_path(&self.root_blueprint, path) {
558                if let NodeBlueprint::Element { attributes, .. } = bp {
559                    for attr in attributes {
560                        if let strata_dom::Attribute::EventListener {
561                            event: ev_type,
562                            handler,
563                        } = attr
564                        {
565                            if *ev_type == event_type {
566                                let ev = strata_dom::Event::transition(
567                                    event_type,
568                                    name.clone(),
569                                    elapsed,
570                                );
571                                handler(ev);
572                            }
573                        }
574                    }
575                }
576            }
577        }
578    }
579
580    /// Registers all parsed `@keyframes` rules from a stylesheet into the runtime animation registry.
581    pub fn register_keyframes_stylesheet(&mut self, sheet: &strata_style::StyleSheet) {
582        self.animation_manager
583            .registry_mut()
584            .register_stylesheet(sheet);
585    }
586
587    /// Registers a single compiled `@keyframes` rule into the runtime animation registry.
588    pub fn register_keyframe_rule(&mut self, rule: &strata_style::KeyframeRule) {
589        self.animation_manager.registry_mut().register_rule(rule);
590    }
591}