use std::{
cell::RefCell,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use super::node::{HitTestBehavior, Node, SyntheticNodeRole};
use crate::{
animation::{Animation, AnimationFillMode, AnimationIterationCount},
core::NodeId,
};
static EXIT_ANIMATIONS_IN_USE: AtomicBool = AtomicBool::new(false);
fn exit_animations_in_use() -> bool {
EXIT_ANIMATIONS_IN_USE.load(Ordering::Relaxed)
}
thread_local! {
static BEGAN_LEAVING: RefCell<Vec<NodeId>> = const { RefCell::new(Vec::new()) };
static ENDED_LEAVING: RefCell<Vec<NodeId>> = const { RefCell::new(Vec::new()) };
}
pub(crate) fn take_began_leaving() -> Vec<NodeId> {
if !exit_animations_in_use() {
return Vec::new();
}
BEGAN_LEAVING.with(|began| std::mem::take(&mut *began.borrow_mut()))
}
pub(crate) fn take_ended_leaving() -> Vec<NodeId> {
if !exit_animations_in_use() {
return Vec::new();
}
ENDED_LEAVING.with(|ended| std::mem::take(&mut *ended.borrow_mut()))
}
#[derive(Clone)]
pub(crate) struct NodeAnimations {
pub(crate) play: Option<Animation>,
pub(crate) exit: Option<Animation>,
pub(crate) left: Option<Box<Forgotten>>,
}
#[derive(Clone, Default)]
pub(crate) struct Forgotten {
role: Option<SyntheticNodeRole>,
names: Vec<(NodeId, Names)>,
}
#[derive(Clone)]
struct Names {
element_id: Option<Arc<str>>,
component_key: Option<Arc<str>>,
component_slot_id: Option<u64>,
}
impl Forgotten {
pub(crate) fn known_as(&self) -> (Option<Arc<str>>, Option<Arc<str>>) {
self
.names
.first()
.map(|(_, names)| (names.component_key.clone(), names.element_id.clone()))
.unwrap_or_default()
}
}
impl Node {
pub(crate) fn set_animation(&mut self, spec: Animation) {
self.animations_mut().play = Some(spec);
self.layout_cache.invalidate();
}
pub(crate) fn set_exit_animation(&mut self, spec: Animation) {
self.animations_mut().exit = Some(spec);
EXIT_ANIMATIONS_IN_USE.store(true, Ordering::Relaxed);
}
pub(crate) fn keeps_leaving_children(&self) -> bool {
self.rare_style.presence
}
fn leaves_with_an_animation(&self) -> bool {
(self.component_key.is_some() || self.element_id.is_some())
&& self
.animation
.as_deref()
.is_some_and(|animations| animations.exit.is_some())
}
pub(crate) fn take_leaving_children(&mut self, new: &Node) -> Vec<(usize, Node)> {
if !exit_animations_in_use() {
return Vec::new();
}
let keeps = new.keeps_leaving_children();
let among_new = |key: &Option<Arc<str>>, id: &Option<Arc<str>>| {
new
.children
.iter()
.any(|kept| &kept.component_key == key && &kept.element_id == id)
};
let comes_back = |child: &Node| {
keeps
&& child.left_as().is_some_and(|forgotten| {
let (key, id) = forgotten.known_as();
(key.is_some() || id.is_some()) && among_new(&key, &id)
})
};
let leaves = |child: &Node| {
(child.is_leaving_layer() && !comes_back(child))
|| (keeps
&& !child.is_leaving_layer()
&& child.leaves_with_an_animation()
&& !among_new(&child.component_key, &child.element_id))
};
for child in self.children.iter_mut() {
if comes_back(child) {
ENDED_LEAVING.with(|ended| ended.borrow_mut().push(child.node_id));
child.end_leaving();
}
}
if !self.children.iter().any(leaves) {
return Vec::new();
}
let mut taken = Vec::new();
let mut staying = Vec::with_capacity(self.children.len());
for (index, child) in std::mem::take(&mut self.children).into_iter().enumerate() {
if !leaves(&child) {
staying.push(child);
continue;
}
if !child.is_leaving_layer() {
BEGAN_LEAVING.with(|began| began.borrow_mut().push(child.node_id));
}
taken.push((index, child));
}
self.children = staying;
taken
}
pub(crate) fn keep_leaving_children(&mut self, leaving: Vec<(usize, Node)>) {
if leaving.is_empty() {
return;
}
for (index, child) in leaving {
self.children.insert(index.min(self.children.len()), child);
}
self.layout_cache.invalidate();
}
pub(crate) fn holds_leaving_child(&self) -> bool {
exit_animations_in_use()
&& self
.children
.iter()
.any(|child| child.is_leaving_layer() || child.holds_leaving_child())
}
pub(crate) fn children_to_match(&self) -> Option<Vec<&Node>> {
(exit_animations_in_use() && self.children.iter().any(Node::is_leaving_layer))
.then(|| self.children.iter().filter(|child| !child.is_leaving_layer()).collect())
}
fn animations_mut(&mut self) -> &mut NodeAnimations {
self.animation.get_or_insert_with(|| {
Box::new(NodeAnimations {
play: None,
exit: None,
left: None,
})
})
}
pub(crate) fn playing_animation(&self) -> Option<&Animation> {
self.animation.as_deref()?.play.as_ref()
}
pub(crate) fn has_keyframe_animation(&self) -> bool {
self.animation.is_some() || self.children.iter().any(Node::has_keyframe_animation)
}
pub(crate) fn has_exit_animation(&self) -> bool {
self
.animation
.as_deref()
.is_some_and(|animations| animations.exit.is_some())
|| self.children.iter().any(Node::has_exit_animation)
}
pub(crate) fn begin_exit(&mut self, restarted: &mut dyn FnMut(NodeId)) -> Option<Duration> {
let mut longest = None;
if let Some(animations) = self.animation.as_deref_mut()
&& let Some(mut exit) = animations.exit.clone()
{
exit.fill_mode = match exit.fill_mode {
AnimationFillMode::None | AnimationFillMode::Forwards => AnimationFillMode::Forwards,
AnimationFillMode::Backwards | AnimationFillMode::Both => AnimationFillMode::Both,
};
if exit.iteration_count == AnimationIterationCount::Infinite {
exit.iteration_count = AnimationIterationCount::Count(1.0);
}
longest = Some(exit.total_time());
animations.play = Some(exit);
restarted(self.node_id);
self.layout_cache.invalidate();
}
for child in &mut self.children {
longest = longest.max(child.begin_exit(restarted));
}
longest.filter(|time| !time.is_zero())
}
pub(crate) fn turn_into_leaving_layer(&mut self) {
let mut forgotten = Forgotten {
role: self.synthetic_role,
names: Vec::new(),
};
self.set_synthetic_role(SyntheticNodeRole::LeavingLayer);
self.hit_test = HitTestBehavior::None;
self.forget_names(&mut forgotten.names);
self.animations_mut().left = Some(Box::new(forgotten));
}
pub(crate) fn left_as(&self) -> Option<&Forgotten> {
if !self.is_leaving_layer() {
return None;
}
self.animation.as_deref()?.left.as_deref()
}
pub(crate) fn end_leaving(&mut self) {
let Some(forgotten) = self
.animation
.as_deref_mut()
.and_then(|animations| animations.left.take())
else {
return;
};
self.synthetic_role = forgotten.role;
self.hit_test = HitTestBehavior::default();
let names: std::collections::HashMap<NodeId, Names> = forgotten.names.into_iter().collect();
self.take_back_names(&names);
}
fn take_back_names(&mut self, names: &std::collections::HashMap<NodeId, Names>) {
if let Some(known) = names.get(&self.node_id) {
self.element_id = known.element_id.clone();
self.component_key = known.component_key.clone();
self.component_slot_id = known.component_slot_id;
}
for child in &mut self.children {
child.take_back_names(names);
}
}
pub(crate) fn subtree_ids(&self, ids: &mut Vec<NodeId>) {
if self.node_id.is_assigned() {
ids.push(self.node_id);
}
for child in &self.children {
child.subtree_ids(ids);
}
}
fn forget_names(&mut self, kept: &mut Vec<(NodeId, Names)>) {
kept.push((
self.node_id,
Names {
element_id: self.element_id.clone(),
component_key: self.component_key.clone(),
component_slot_id: self.component_slot_id,
},
));
self.element_id = None;
self.component_key = None;
self.component_slot_id = None;
self.outer_decoration = None;
if !self.draws_canvas() {
self.element_ref = None;
}
for child in &mut self.children {
child.forget_names(kept);
}
}
fn draws_canvas(&self) -> bool {
#[cfg(feature = "canvas")]
{
matches!(self.node_kind(), super::node_kind::NodeKind::Canvas { .. })
}
#[cfg(not(feature = "canvas"))]
{
false
}
}
pub(crate) fn is_leaving_layer(&self) -> bool {
self.has_synthetic_role(SyntheticNodeRole::LeavingLayer)
}
}