Skip to main content

aylis_core/
anim.rs

1//! Animações de propriedades (o "Animator").
2//!
3//! Qualquer propriedade numérica ou de cor pode ser animada pelo nome, porque o
4//! sistema de propriedades permite ler e gravar qualquer uma:
5//!
6//! - por código: [`Ui::animate`];
7//! - por componente filho: [`PropertyAnimation`] (`FloatAnimation` /
8//!   `ColorAnimation`), disparado por um [`Trigger`] (hover, pressed, focused, checked,
9//!   appear, hover_within) do controle pai, sem código, ou pelos métodos `start` e `stop`.
10//!
11//! Numa lista que recicla as linhas (o `VirtualList`), a linha que vai para outro item recomeça
12//! as animações ([`Ui::reset_animations`]): o estado do item chega pronto, sem animar, e o
13//! `appear` vale uma vez por item.
14//!
15//! A plataforma chama [`Ui::tick`] a cada frame enquanto [`Ui::is_animating`] for
16//! verdadeiro; parado, nada roda.
17
18use crate::color::Color;
19use crate::component::{Component, ComponentId, MethodInfo};
20use crate::error::{Error, Result};
21use crate::prop::{PropEnum, PropInfo, PropKind, PropType, PropValue};
22use crate::ui::Ui;
23
24/// Curva de aceleração (suavização). Como propriedade, é gravada pelo nome (`out_quad`,
25/// ou os do CSS: `ease`, `ease-in`...) ou como `cubic-bezier(x1, y1, x2, y2)`.
26#[derive(Clone, Copy, Debug, Default, PartialEq)]
27pub enum Easing {
28    #[default]
29    Linear,
30    InQuad,
31    OutQuad,
32    InOutQuad,
33    OutCubic,
34    InOutCubic,
35    /// Passa um pouco do destino e volta (efeito "mola" leve).
36    OutBack,
37    /// Curva de Bézier cúbica de (0,0) a (1,1) com os dois pontos de controle, como a
38    /// `cubic-bezier()` do CSS. O `x` dos pontos fica entre 0 e 1; o `y` pode passar.
39    CubicBezier(f32, f32, f32, f32),
40}
41
42impl Easing {
43    pub const ALL: [Easing; 7] = [
44        Easing::Linear,
45        Easing::InQuad,
46        Easing::OutQuad,
47        Easing::InOutQuad,
48        Easing::OutCubic,
49        Easing::InOutCubic,
50        Easing::OutBack,
51    ];
52
53    /// Aplica a curva a `t` (0..1).
54    pub fn apply(self, t: f32) -> f32 {
55        let t = t.clamp(0.0, 1.0);
56        match self {
57            Easing::Linear => t,
58            Easing::InQuad => t * t,
59            Easing::OutQuad => 1.0 - (1.0 - t) * (1.0 - t),
60            Easing::InOutQuad => {
61                if t < 0.5 {
62                    2.0 * t * t
63                } else {
64                    1.0 - (-2.0 * t + 2.0).powi(2) / 2.0
65                }
66            }
67            Easing::OutCubic => 1.0 - (1.0 - t).powi(3),
68            Easing::InOutCubic => {
69                if t < 0.5 {
70                    4.0 * t * t * t
71                } else {
72                    1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
73                }
74            }
75            Easing::OutBack => {
76                let c1 = 1.70158;
77                let c3 = c1 + 1.0;
78                1.0 + c3 * (t - 1.0).powi(3) + c1 * (t - 1.0).powi(2)
79            }
80            Easing::CubicBezier(x1, y1, x2, y2) => cubic_bezier(x1.clamp(0.0, 1.0), y1, x2.clamp(0.0, 1.0), y2, t),
81        }
82    }
83
84    /// Nomes das curvas prontas, na ordem de [`Easing::ALL`].
85    pub const NAMES: &'static [&'static str] =
86        &["linear", "in_quad", "out_quad", "in_out_quad", "out_cubic", "in_out_cubic", "out_back"];
87
88    /// As curvas do CSS (`ease`, `ease-in`, `ease-out`, `ease-in-out`) com os pontos delas.
89    pub const CSS: [(&'static str, [f32; 4]); 4] = [
90        ("ease", [0.25, 0.1, 0.25, 1.0]),
91        ("ease-in", [0.42, 0.0, 1.0, 1.0]),
92        ("ease-out", [0.0, 0.0, 0.58, 1.0]),
93        ("ease-in-out", [0.42, 0.0, 0.58, 1.0]),
94    ];
95
96    /// Lê um nome (`out_quad`, `OutQuad`, `out-quad`), um nome do CSS ou
97    /// `cubic-bezier(x1, y1, x2, y2)`.
98    pub fn parse(text: &str) -> Option<Easing> {
99        let text = text.trim();
100        if let Some(args) = text.strip_prefix("cubic-bezier(").and_then(|a| a.strip_suffix(')')) {
101            let v: Vec<f32> = args.split(',').map(|n| n.trim().parse::<f32>()).collect::<Result<_, _>>().ok()?;
102            let [x1, y1, x2, y2] = v[..] else { return None };
103            return Some(Easing::CubicBezier(x1, y1, x2, y2));
104        }
105        if let Some((_, [a, b, c, d])) = Easing::CSS.iter().find(|(n, _)| n.eq_ignore_ascii_case(text)) {
106            return Some(Easing::CubicBezier(*a, *b, *c, *d));
107        }
108        let plain: String = text.chars().filter(|c| *c != '_' && *c != '-').collect();
109        Easing::NAMES
110            .iter()
111            .position(|n| n.replace('_', "").eq_ignore_ascii_case(&plain))
112            .map(|i| Easing::ALL[i])
113    }
114
115    /// O texto que [`Easing::parse`] lê.
116    pub fn to_spec(self) -> String {
117        match self {
118            Easing::CubicBezier(a, b, c, d) => {
119                if let Some((name, _)) = Easing::CSS.iter().find(|(_, p)| *p == [a, b, c, d]) {
120                    return name.to_string();
121                }
122                let n = |v: f32| format!("{}", (v * 1000.0).round() / 1000.0);
123                format!("cubic-bezier({}, {}, {}, {})", n(a), n(b), n(c), n(d))
124            }
125            named => Easing::NAMES[Easing::ALL.iter().position(|e| *e == named).unwrap_or(0)].to_string(),
126        }
127    }
128
129    /// Os pontos de controle da curva como Bézier cúbica (as prontas são aproximações das
130    /// funções, as mesmas do easings.net). É o que o editor da curva abre para ajustar.
131    pub fn to_bezier(self) -> [f32; 4] {
132        match self {
133            Easing::Linear => [0.0, 0.0, 1.0, 1.0],
134            Easing::InQuad => [0.55, 0.085, 0.68, 0.53],
135            Easing::OutQuad => [0.25, 0.46, 0.45, 0.94],
136            Easing::InOutQuad => [0.455, 0.03, 0.515, 0.955],
137            Easing::OutCubic => [0.215, 0.61, 0.355, 1.0],
138            Easing::InOutCubic => [0.645, 0.045, 0.355, 1.0],
139            Easing::OutBack => [0.175, 0.885, 0.32, 1.275],
140            Easing::CubicBezier(a, b, c, d) => [a, b, c, d],
141        }
142    }
143}
144
145/// `y` da Bézier (0,0)-(x1,y1)-(x2,y2)-(1,1) no ponto em que `x` = `x`: acha o parâmetro
146/// por Newton e, se não convergir, por bisseção.
147fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, x: f32) -> f32 {
148    let curve = |a: f32, b: f32, s: f32| 3.0 * a * s * (1.0 - s) * (1.0 - s) + 3.0 * b * s * s * (1.0 - s) + s * s * s;
149    let slope = |a: f32, b: f32, s: f32| 3.0 * a * (1.0 - s) * (1.0 - s) + 6.0 * (b - a) * s * (1.0 - s) + 3.0 * (1.0 - b) * s * s;
150    let mut s = x;
151    for _ in 0..8 {
152        let err = curve(x1, x2, s) - x;
153        if err.abs() < 1e-5 {
154            return curve(y1, y2, s);
155        }
156        let d = slope(x1, x2, s);
157        if d.abs() < 1e-6 {
158            break;
159        }
160        s -= err / d;
161    }
162    let (mut lo, mut hi) = (0.0f32, 1.0f32);
163    s = x;
164    for _ in 0..40 {
165        let v = curve(x1, x2, s);
166        if (v - x).abs() < 1e-5 {
167            break;
168        }
169        if v < x { lo = s } else { hi = s }
170        s = (lo + hi) / 2.0;
171    }
172    curve(y1, y2, s)
173}
174
175impl std::str::FromStr for Easing {
176    type Err = Error;
177
178    fn from_str(s: &str) -> Result<Self> {
179        Easing::parse(s).ok_or_else(|| {
180            Error::invalid(format!("curva '{s}' inválida; use um de: {}, ease, ease-in, ease-out, ease-in-out ou cubic-bezier(x1, y1, x2, y2)", Easing::NAMES.join(", ")))
181        })
182    }
183}
184
185impl PropType for Easing {
186    const KIND: PropKind = PropKind::Easing;
187    fn to_value(&self) -> PropValue {
188        PropValue::String(self.to_spec())
189    }
190    fn from_value(value: PropValue) -> Result<Self> {
191        value.to_str()?.parse()
192    }
193}
194
195/// Estado do controle pai que dispara uma animação.
196#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
197pub enum Trigger {
198    /// Só por código ([`Ui::start_animation`]).
199    #[default]
200    None,
201    Hover,
202    Pressed,
203    Focused,
204    Checked,
205    /// Ao aparecer na tela (o controle entrou na área visível, rolando ou não): uma vez só,
206    /// como o "scroll reveal" da web. Numa lista que recicla as linhas, uma vez por item.
207    Appear,
208    /// O mouse está no controle ou em qualquer um dos de dentro dele (o `:hover` do CSS): a
209    /// linha inteira de uma lista com o mouse no título. O `hover` é só o controle debaixo do
210    /// mouse (decidido em 22/11: um gatilho novo, para não mudar os forms que já usam o `hover`).
211    HoverWithin,
212}
213
214impl PropEnum for Trigger {
215    const NAMES: &'static [&'static str] = &["none", "hover", "pressed", "focused", "checked", "appear", "hover_within"];
216
217    fn from_index(index: usize) -> Option<Self> {
218        [Trigger::None, Trigger::Hover, Trigger::Pressed, Trigger::Focused, Trigger::Checked, Trigger::Appear, Trigger::HoverWithin]
219            .get(index)
220            .copied()
221    }
222
223    fn index(self) -> usize {
224        self as usize
225    }
226}
227
228#[derive(Clone, Copy, Debug, PartialEq)]
229pub(crate) enum AnimValue {
230    Float(f64),
231    Color(Color),
232}
233
234impl AnimValue {
235    fn from_prop(v: &PropValue) -> Option<AnimValue> {
236        match v {
237            PropValue::Float(_) | PropValue::Int(_) => v.to_f64().ok().map(AnimValue::Float),
238            PropValue::Color(_) | PropValue::String(_) => v.to_color().ok().map(AnimValue::Color),
239            _ => None,
240        }
241    }
242
243    fn to_prop(self) -> PropValue {
244        match self {
245            AnimValue::Float(v) => PropValue::Float(v),
246            AnimValue::Color(c) => PropValue::Color(c),
247        }
248    }
249
250    fn lerp(self, to: AnimValue, t: f32) -> AnimValue {
251        match (self, to) {
252            (AnimValue::Float(a), AnimValue::Float(b)) => AnimValue::Float(a + (b - a) * t as f64),
253            (AnimValue::Color(a), AnimValue::Color(b)) => AnimValue::Color(a.lerp(b, t)),
254            (_, b) => b,
255        }
256    }
257}
258
259/// `0:0; 0.6:1.15; 1:1` → os passos em ordem; `None` se vazio ou mal escrito.
260pub fn parse_keyframes(text: &str) -> Option<Vec<(f32, f64)>> {
261    let mut steps = Vec::new();
262    for item in text.split(';').map(str::trim).filter(|s| !s.is_empty()) {
263        let (t, v) = item.split_once(':')?;
264        let t: f32 = t.trim().replace(',', ".").parse().ok()?;
265        let v: f64 = v.trim().replace(',', ".").parse().ok()?;
266        steps.push((t.clamp(0.0, 1.0), v));
267    }
268    if steps.len() < 2 {
269        return None;
270    }
271    steps.sort_by(|a, b| a.0.total_cmp(&b.0));
272    Some(steps)
273}
274
275/// O valor da sequência no tempo `t` (0 a 1), em linha reta entre os passos.
276fn sample_keyframes(steps: &[(f32, f64)], t: f32) -> f64 {
277    let Some(first) = steps.first() else { return 0.0 };
278    if t <= first.0 {
279        return first.1;
280    }
281    for w in steps.windows(2) {
282        let ((t0, v0), (t1, v1)) = (w[0], w[1]);
283        if t <= t1 {
284            let f = if t1 > t0 { ((t - t0) / (t1 - t0)) as f64 } else { 1.0 };
285            return v0 + (v1 - v0) * f;
286        }
287    }
288    steps.last().map_or(0.0, |s| s.1)
289}
290
291/// Uma animação em andamento.
292#[derive(Clone, Debug)]
293pub(crate) struct Running {
294    pub(crate) target: ComponentId,
295    property: String,
296    from: AnimValue,
297    to: AnimValue,
298    /// Quando começa (o atraso já somado).
299    start: f64,
300    duration: f64,
301    easing: Easing,
302    auto_reverse: bool,
303    looping: bool,
304    /// Os passos (fração do tempo, valor) de uma sequência; vazio: de `from` a `to`.
305    keyframes: std::rc::Rc<[(f32, f64)]>,
306    /// Componente de animação que iniciou esta (se houver).
307    pub(crate) owner: Option<ComponentId>,
308}
309
310/// Opções de [`Ui::animate`].
311#[derive(Clone, Copy, Debug, PartialEq)]
312pub struct AnimationOptions {
313    pub duration_ms: f32,
314    /// Espera antes de começar (o valor fica no inicial enquanto isso).
315    pub delay_ms: f32,
316    pub easing: Easing,
317    /// Ao chegar no destino, volta ao início.
318    pub auto_reverse: bool,
319    /// Repete para sempre (até [`Ui::stop_animations`]).
320    pub looping: bool,
321}
322
323impl Default for AnimationOptions {
324    fn default() -> Self {
325        Self { duration_ms: 200.0, delay_ms: 0.0, easing: Easing::OutQuad, auto_reverse: false, looping: false }
326    }
327}
328
329impl AnimationOptions {
330    pub fn new(duration_ms: f32, easing: Easing) -> Self {
331        Self { duration_ms, easing, ..Default::default() }
332    }
333}
334
335impl Ui {
336    /// Anima uma propriedade (numérica ou cor) do valor atual até `to`.
337    ///
338    /// Uma animação anterior da mesma propriedade é substituída e a nova parte do
339    /// valor em que a anterior parou, então não há saltos.
340    pub fn animate(
341        &mut self,
342        id: ComponentId,
343        property: &str,
344        to: impl Into<PropValue>,
345        options: AnimationOptions,
346    ) -> Result<()> {
347        let current = self.get_prop(id, property)?;
348        self.animate_from_to(id, property, current, to.into(), options, None)
349    }
350
351    fn animate_from_to(
352        &mut self,
353        id: ComponentId,
354        property: &str,
355        from: PropValue,
356        to: PropValue,
357        options: AnimationOptions,
358        owner: Option<ComponentId>,
359    ) -> Result<()> {
360        let invalid = || Error::invalid("só propriedades numéricas ou de cor podem ser animadas").with_property(property);
361        // Cor com nome (`success`, `text/85`): a do tema em uso.
362        let named = |v: PropValue| match v {
363            PropValue::String(s) if crate::palette::is_named(&s) => self.theme.resolve_color(&s).map_or(PropValue::String(s), PropValue::Color),
364            v => v,
365        };
366        let (from, to) = (named(from), named(to));
367        let from = AnimValue::from_prop(&from).ok_or_else(invalid)?;
368        let to = AnimValue::from_prop(&to).ok_or_else(invalid)?;
369        self.animations.retain(|a| !(a.target == id && a.property == property));
370        self.animations.push(Running {
371            target: id,
372            property: property.to_string(),
373            from,
374            to,
375            start: self.time + (options.delay_ms.max(0.0) / 1000.0) as f64,
376            duration: (options.duration_ms.max(0.0) / 1000.0) as f64,
377            easing: options.easing,
378            auto_reverse: options.auto_reverse,
379            looping: options.looping,
380            keyframes: std::rc::Rc::from(Vec::new()),
381            owner,
382        });
383        self.request_repaint();
384        Ok(())
385    }
386
387    /// Para as animações das propriedades do componente (o valor fica onde está).
388    pub fn stop_animations(&mut self, id: ComponentId) {
389        self.animations.retain(|a| a.target != id && a.owner != Some(id));
390    }
391
392    /// Chama [`Component::frame`] em cada quadro até ele devolver `false` (a rolagem com
393    /// deslize, que anda no tempo do quadro e não num timer fixo, e acompanha o monitor).
394    pub fn request_frames(&mut self, id: ComponentId) {
395        if !self.frame_hooks.contains(&id) {
396            self.frame_hooks.push(id);
397        }
398        // Um quadro a pintar, sem dizer onde: o componente marca a área dele no `frame`.
399        self.repaint_requested = true;
400    }
401
402    fn tick_frame_hooks(&mut self) {
403        for id in std::mem::take(&mut self.frame_hooks) {
404            let more = self.with_component(id, |c, ctx| c.timed_mut().is_some_and(|t| t.frame(ctx))).unwrap_or(false);
405            if more && self.contains(id) && !self.frame_hooks.contains(&id) {
406                self.frame_hooks.push(id);
407            }
408        }
409    }
410
411    /// `id` está com o lugar ou a transparência animando (`translate_x`, `translate_y`,
412    /// `opacity`): o desenho dele, igual de um quadro para o outro, vai numa camada guardada.
413    pub(crate) fn animates_placement(&self, id: ComponentId) -> bool {
414        self.placement_movers().any(|m| m == id)
415    }
416
417    /// Os controles com o lugar ou a transparência animando (veja [`Ui::animates_placement`]).
418    pub(crate) fn placement_movers(&self) -> impl Iterator<Item = ComponentId> + '_ {
419        self.animations.iter().filter(|a| matches!(a.property.as_str(), "translate_x" | "translate_y" | "opacity")).map(|a| a.target)
420    }
421
422    /// Há animação ou transição de estilo em andamento.
423    pub fn is_animating(&self) -> bool {
424        !self.animations.is_empty() || !self.frame_hooks.is_empty() || self.frame_requests.borrow().iter().any(|(id, f)| f.0 && self.contains(*id)) || self.is_flinging() || self.overscroll_active() || !self.transitions.is_empty()
425    }
426
427    /// Avança as animações até o tempo atual ([`Ui::time`]). A plataforma chama isto antes
428    /// de cada pintura.
429    pub fn tick(&mut self) {
430        self.tick_flings();
431        self.tick_overscroll();
432        self.tick_busy();
433        self.tick_transitions();
434        self.check_appear();
435        self.tick_frame_hooks();
436        if self.animations.is_empty() {
437            return;
438        }
439        let _profile = crate::profile::scope(crate::profile::Lane::Animation, || format!("{} animações", self.animations.len()));
440        let now = self.time;
441        let mut updates = Vec::with_capacity(self.animations.len());
442        self.animations.retain_mut(|a| {
443            let span = if a.auto_reverse { a.duration * 2.0 } else { a.duration };
444            let mut elapsed = (now - a.start).max(0.0);
445            let finished = !a.looping && elapsed >= span;
446            if a.looping && span > 0.0 {
447                elapsed %= span;
448            }
449            let mut t = if a.duration > 0.0 { (elapsed / a.duration) as f32 } else { 1.0 };
450            if finished {
451                t = if a.auto_reverse { 0.0 } else { 1.0 };
452            } else if a.auto_reverse && t > 1.0 {
453                t = 2.0 - t;
454            }
455            let eased = a.easing.apply(t.min(1.0));
456            let value = if a.keyframes.is_empty() { a.from.lerp(a.to, eased) } else { AnimValue::Float(sample_keyframes(&a.keyframes, eased)) };
457            updates.push((a.target, a.property.clone(), value.to_prop()));
458            !finished
459        });
460        for (id, property, value) in updates {
461            // A propriedade pode ter sumido (componente liberado); só ignora.
462            let _ = self.set_prop(id, &property, value);
463        }
464    }
465
466    /// Inicia uma [`PropertyAnimation`] (normalmente as de `trigger: none`).
467    pub fn start_animation(&mut self, animation: ComponentId) -> Result<()> {
468        self.play_animation(animation, true)
469    }
470
471    /// Dispara as animações filhas de `control` que esperam este `trigger`: ao ativar,
472    /// vão para `stop_value`; ao desativar, voltam ao valor original.
473    pub(crate) fn run_triggers(&mut self, control: ComponentId, trigger: Trigger, active: bool) {
474        let animations: Vec<ComponentId> = self
475            .children(control)
476            .iter()
477            .copied()
478            .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == trigger))
479            .collect();
480        for animation in animations {
481            let _ = self.play_animation(animation, active);
482        }
483    }
484
485    /// Para a [`PropertyAnimation`] `animation` (o valor fica onde está).
486    pub fn stop_animation(&mut self, animation: ComponentId) {
487        self.animations.retain(|r| r.owner != Some(animation));
488    }
489
490    fn play_animation(&mut self, animation: ComponentId, forward: bool) -> Result<()> {
491        let mut a = self.get::<PropertyAnimation>(animation).ok_or(Error::InvalidId)?.clone();
492        let result = self.play_with(animation, &mut a, forward);
493        if let Some(anim) = self.get_mut::<PropertyAnimation>(animation) {
494            anim.original = a.original;
495        }
496        result
497    }
498
499    /// Roda a animação `a` (a do componente `animation`, que pode estar fora do `Ui` durante
500    /// o `invoke` dele) para a frente ou de volta ao valor original.
501    fn play_with(&mut self, animation: ComponentId, a: &mut PropertyAnimation, forward: bool) -> Result<()> {
502        let target = self.parent(animation).ok_or(Error::InvalidId)?;
503        let current = self.get_prop(target, &a.property)?;
504        let original = a.original.clone().unwrap_or_else(|| current.clone());
505        a.original = Some(original.clone());
506        let (from, to) = if forward {
507            let from = if a.start_value == PropValue::Null { current } else { a.start_value.clone() };
508            (from, a.stop_value.clone())
509        } else {
510            (current, original)
511        };
512        let options = AnimationOptions {
513            duration_ms: a.duration,
514            delay_ms: if forward { a.delay } else { 0.0 },
515            easing: a.easing,
516            auto_reverse: forward && a.auto_reverse,
517            looping: forward && a.looping,
518        };
519        self.animate_from_to(target, &a.property, from, to, options, Some(animation))?;
520        // Sequência de passos (só na ida): os valores vêm dela.
521        if forward {
522            if let Some(steps) = parse_keyframes(&a.keyframes) {
523                if let Some(run) = self.animations.iter_mut().find(|r| r.target == target && r.property == a.property) {
524                    run.keyframes = std::rc::Rc::from(steps);
525                }
526            }
527        }
528        Ok(())
529    }
530
531    /// Põe a animação direto no fim (`forward`) ou no valor original, sem andar no tempo: o
532    /// estado que um item já tinha quando chega a uma linha reciclada. A que repete sem parar
533    /// não tem fim e roda.
534    fn settle_animation(&mut self, animation: ComponentId, forward: bool) {
535        self.stop_animation(animation);
536        let (Some(target), Some(mut a)) = (self.parent(animation), self.get::<PropertyAnimation>(animation).cloned()) else { return };
537        if !forward {
538            if let Some(original) = a.original {
539                let _ = self.set_prop(target, &a.property, original);
540            }
541            return;
542        }
543        if a.looping {
544            let _ = self.play_animation(animation, true);
545            return;
546        }
547        let Ok(current) = self.get_prop(target, &a.property) else { return };
548        let end = match parse_keyframes(&a.keyframes) {
549            Some(steps) => PropValue::Float(steps.last().map_or(0.0, |s| s.1)),
550            // Ida e volta termina onde começou.
551            None if a.auto_reverse => if a.start_value == PropValue::Null { current.clone() } else { a.start_value.clone() },
552            None => a.stop_value.clone(),
553        };
554        a.original.get_or_insert(current);
555        if let Some(anim) = self.get_mut::<PropertyAnimation>(animation) {
556            anim.original = a.original;
557        }
558        let _ = self.set_prop(target, &a.property, end);
559    }
560
561    /// As animações (`FloatAnimation`, `ColorAnimation`) em `root` e nos de dentro dele.
562    fn animations_within(&self, root: ComponentId) -> Vec<ComponentId> {
563        let mut out = Vec::new();
564        let mut stack = vec![root];
565        while let Some(c) = stack.pop() {
566            if self.get::<PropertyAnimation>(c).is_some() {
567                out.push(c);
568            }
569            stack.extend(self.children(c).iter().copied());
570        }
571        out
572    }
573
574    /// `root` ou algum dos de dentro tem animação (`FloatAnimation`, `ColorAnimation`): a lista
575    /// que recicla linhas só recomeça as animações quando o modelo tem alguma.
576    pub fn has_animations(&self, root: ComponentId) -> bool {
577        !self.animations_within(root).is_empty()
578    }
579
580    /// `root` passou a mostrar outra coisa (a linha reciclada de uma lista, que vai para outro
581    /// item): as animações dele e dos de dentro param e as propriedades voltam ao valor de antes
582    /// delas; o `appear` pode rodar de novo; e as dos estados que estão valendo (o mouse em
583    /// cima, o foco) ficam no fim, sem animar. Devolve se algum `appear` já tinha rodado (o item
584    /// que sai já apareceu).
585    pub fn reset_animations(&mut self, root: ComponentId) -> bool {
586        let mut appeared = false;
587        let animations = self.animations_within(root);
588        for &animation in &animations {
589            self.stop_animation(animation);
590            let Some(target) = self.parent(animation) else { continue };
591            let Some(a) = self.get_mut::<PropertyAnimation>(animation) else { continue };
592            let property = a.property.clone();
593            let original = a.original.take();
594            if a.trigger == Trigger::Appear {
595                appeared |= a.appeared;
596                a.appeared = false;
597                // Volta a esperar (sem refazer a lista de todas: rolar não percorre a tela).
598                if let Some(waiting) = self.appear_waiting.as_mut().filter(|w| !w.contains(&animation)) {
599                    waiting.push(animation);
600                }
601            }
602            if let Some(original) = original {
603                let _ = self.set_prop(target, &property, original);
604            }
605        }
606        for animation in animations {
607            let Some((target, trigger, enabled)) = self.parent(animation).zip(self.get::<PropertyAnimation>(animation).map(|a| (a.trigger, a.enabled))).map(|(t, (g, e))| (t, g, e)) else { continue };
608            let state = self.cb(target).map(|cb| cb.state()).unwrap_or_default();
609            let active = match trigger {
610                Trigger::Hover => state.hover,
611                Trigger::Pressed => state.pressed,
612                Trigger::Focused => state.focused,
613                Trigger::Checked => state.checked,
614                Trigger::HoverWithin => self.hover_within(target).0,
615                Trigger::None | Trigger::Appear => false,
616            };
617            if enabled && active {
618                self.settle_animation(animation, true);
619            }
620        }
621        appeared
622    }
623
624    /// Os `appear` de `root` e dos de dentro contam como já rodados e ficam no fim, sem animar:
625    /// o item que já apareceu e volta numa linha reciclada.
626    pub fn finish_appear(&mut self, root: ComponentId) {
627        for animation in self.animations_within(root) {
628            let Some(a) = self.get_mut::<PropertyAnimation>(animation).filter(|a| a.trigger == Trigger::Appear && a.enabled) else { continue };
629            a.appeared = true;
630            if let Some(waiting) = self.appear_waiting.as_mut() {
631                waiting.retain(|w| *w != animation);
632            }
633            self.settle_animation(animation, true);
634        }
635    }
636
637    /// As animações filhas de `control` com o gatilho `trigger` vão direto para o fim (`active`)
638    /// ou para o valor original, sem animar.
639    pub(crate) fn settle_triggers(&mut self, control: ComponentId, trigger: Trigger, active: bool) {
640        let animations: Vec<ComponentId> = self
641            .children(control)
642            .iter()
643            .copied()
644            .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == trigger))
645            .collect();
646        for animation in animations {
647            self.settle_animation(animation, active);
648        }
649    }
650
651    /// Os controles com alguma animação `hover_within` filha (refeito quando a árvore muda).
652    pub(crate) fn hover_within_hosts(&mut self) -> &[ComponentId] {
653        if self.hover_within_hosts.is_none() {
654            let mut hosts: Vec<ComponentId> = self
655                .components()
656                .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.trigger == Trigger::HoverWithin))
657                .filter_map(|c| self.parent(c))
658                .collect();
659            hosts.dedup();
660            self.hover_within_hosts = Some(hosts);
661        }
662        self.hover_within_hosts.as_deref().unwrap_or_default()
663    }
664
665    /// As animações `appear` cujo controle entrou na área visível rodam (uma vez). A lista
666    /// das que esperam é refeita quando a árvore muda; com nenhuma, não custa nada.
667    pub(crate) fn check_appear(&mut self) {
668        if self.appear_waiting.is_none() {
669            let waiting: Vec<ComponentId> = self
670                .components()
671                .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == Trigger::Appear && !a.appeared))
672                .collect();
673            self.appear_waiting = Some(waiting);
674        }
675        let Some(waiting) = self.appear_waiting.clone() else { return };
676        if waiting.is_empty() || self.design_mode {
677            return;
678        }
679        let mut left = Vec::new();
680        for animation in waiting {
681            let Some(target) = self.parent(animation) else { continue };
682            if self.visible_fraction(target) >= 0.15 {
683                if let Some(a) = self.get_mut::<PropertyAnimation>(animation) {
684                    a.appeared = true;
685                }
686                let _ = self.play_animation(animation, true);
687            } else {
688                left.push(animation);
689            }
690        }
691        self.appear_waiting = Some(left);
692    }
693
694    /// Quanto do controle está à vista (0 a 1): o retângulo dele cortado pelo de cada
695    /// contêiner acima (as rolagens) e pelo form aberto.
696    fn visible_fraction(&self, id: ComponentId) -> f32 {
697        let root = self.root_of(id);
698        if !self.is_open(root) {
699            return 0.0;
700        }
701        let Some(r) = self.absolute_rect(id) else { return 0.0 };
702        if !self.cb(id).is_some_and(|cb| cb.visible()) {
703            return 0.0;
704        }
705        let area = (r.width * r.height).max(1.0);
706        let (mut x0, mut y0, mut x1, mut y1) = (r.x, r.y, r.right(), r.bottom());
707        let mut current = self.parent(id);
708        while let Some(p) = current {
709            if let Some(c) = self.absolute_rect(p) {
710                (x0, y0, x1, y1) = (x0.max(c.x), y0.max(c.y), x1.min(c.right()), y1.min(c.bottom()));
711            }
712            if !self.cb(p).is_none_or(|cb| cb.visible()) {
713                return 0.0;
714            }
715            current = self.parent(p);
716        }
717        ((x1 - x0).max(0.0) * (y1 - y0).max(0.0)) / area
718    }
719}
720
721/// Animação declarada como componente filho do controle animado.
722/// Funciona sem código, inclusive vinda do arquivo de layout.
723///
724/// ```ignore
725/// let anim = ui.add(PropertyAnimation::color("fill", Color::rgb(255, 0, 0)), botao);
726/// ui.set_prop(anim, "trigger", "hover")?;
727/// ```
728#[derive(Clone, Debug, PartialEq)]
729pub struct PropertyAnimation {
730    color: bool,
731    /// A propriedade do pai que a animação muda (`opacity`, `fill`, `left`...).
732    pub property: String,
733    /// Valor inicial; `Null` = o valor atual da propriedade.
734    pub start_value: PropValue,
735    /// O valor a que a propriedade chega no fim da animação.
736    pub stop_value: PropValue,
737    /// Quanto dura a ida, em milissegundos.
738    pub duration: f32,
739    /// Espera antes de começar, em milissegundos (só na ida).
740    pub delay: f32,
741    /// A curva de velocidade da animação (`linear`, `out_quad`...): como o valor anda no tempo.
742    pub easing: Easing,
743    /// O estado do pai que dispara a animação (`hover`, `pressed`, `focused`, `checked`,
744    /// `appear`); `none`: só por código.
745    pub trigger: Trigger,
746    /// Chegando ao fim, volta ao valor inicial pelo mesmo caminho.
747    pub auto_reverse: bool,
748    /// Repete sem parar até ser desligada.
749    pub looping: bool,
750    /// Desligada, o gatilho não a dispara.
751    pub enabled: bool,
752    /// Sequência de passos (`0:0; 0.6:1.15; 1:1`: fração do tempo e valor), no lugar de ir de
753    /// `start_value` a `stop_value` (só números).
754    pub keyframes: String,
755    /// Valor da propriedade antes da primeira execução (para onde volta).
756    original: Option<PropValue>,
757    /// O gatilho `appear` já rodou.
758    pub(crate) appeared: bool,
759}
760
761impl PropertyAnimation {
762    fn new(color: bool, property: &str, stop_value: PropValue) -> Self {
763        Self {
764            color,
765            property: property.to_string(),
766            start_value: PropValue::Null,
767            stop_value,
768            duration: 200.0,
769            delay: 0.0,
770            easing: Easing::OutQuad,
771            trigger: Trigger::None,
772            auto_reverse: false,
773            looping: false,
774            enabled: true,
775            original: None,
776            keyframes: String::new(),
777            appeared: false,
778        }
779    }
780
781    /// `FloatAnimation`: anima uma propriedade numérica.
782    pub fn float(property: &str, stop_value: f64) -> Self {
783        Self::new(false, property, PropValue::Float(stop_value))
784    }
785
786    /// `ColorAnimation`: anima uma propriedade de cor.
787    pub fn color(property: &str, stop_value: Color) -> Self {
788        Self::new(true, property, PropValue::Color(stop_value))
789    }
790
791    pub fn with_trigger(mut self, trigger: Trigger) -> Self {
792        self.trigger = trigger;
793        self
794    }
795
796    pub fn with_duration(mut self, ms: f32) -> Self {
797        self.duration = ms;
798        self
799    }
800
801    pub fn with_easing(mut self, easing: Easing) -> Self {
802        self.easing = easing;
803        self
804    }
805
806    pub fn with_delay(mut self, ms: f32) -> Self {
807        self.delay = ms;
808        self
809    }
810}
811
812/// Para o registro de classes: `FloatAnimation`.
813#[derive(Clone, Debug, PartialEq)]
814pub struct FloatAnimation(pub PropertyAnimation);
815
816impl Default for FloatAnimation {
817    fn default() -> Self {
818        Self(PropertyAnimation::float("opacity", 1.0))
819    }
820}
821
822/// Para o registro de classes: `ColorAnimation`.
823#[derive(Clone, Debug, PartialEq)]
824pub struct ColorAnimation(pub PropertyAnimation);
825
826impl Default for ColorAnimation {
827    fn default() -> Self {
828        Self(PropertyAnimation::color("fill", Color::TRANSPARENT))
829    }
830}
831
832macro_rules! delegate_animation {
833    ($t:ty, $name:literal) => {
834        impl Component for $t {
835            fn class_name(&self) -> &'static str {
836                $name
837            }
838
839            fn inner(&self) -> Option<&dyn Component> {
840                Some(&self.0)
841            }
842
843            fn inner_mut(&mut self) -> Option<&mut dyn Component> {
844                Some(&mut self.0)
845            }
846
847            fn methods(&self) -> &'static [MethodInfo] {
848                self.0.methods()
849            }
850        }
851    };
852}
853
854delegate_animation!(FloatAnimation, "FloatAnimation");
855delegate_animation!(ColorAnimation, "ColorAnimation");
856
857const FLOAT_PROPS: &[PropInfo] = &[
858    PropInfo::new("property", PropKind::String, "Animation"),
859    PropInfo::new("start_value", PropKind::Float, "Animation"),
860    PropInfo::new("stop_value", PropKind::Float, "Animation"),
861    PropInfo::new("duration", PropKind::Duration, "Animation"),
862    PropInfo::new("delay", PropKind::Duration, "Animation"),
863    PropInfo::new("easing", PropKind::Easing, "Animation"),
864    PropInfo::new("trigger", PropKind::Enum(Trigger::NAMES), "Animation").rust_type("Trigger"),
865    PropInfo::new("auto_reverse", PropKind::Bool, "Animation"),
866    PropInfo::new("looping", PropKind::Bool, "Animation"),
867    PropInfo::new("enabled", PropKind::Bool, "Animation"),
868    PropInfo::new("keyframes", PropKind::String, "Animation"),
869];
870
871const COLOR_PROPS: &[PropInfo] = &[
872    PropInfo::new("property", PropKind::String, "Animation"),
873    PropInfo::new("start_value", PropKind::Color, "Animation"),
874    PropInfo::new("stop_value", PropKind::Color, "Animation"),
875    PropInfo::new("duration", PropKind::Duration, "Animation"),
876    PropInfo::new("delay", PropKind::Duration, "Animation"),
877    PropInfo::new("easing", PropKind::Easing, "Animation"),
878    PropInfo::new("trigger", PropKind::Enum(Trigger::NAMES), "Animation").rust_type("Trigger"),
879    PropInfo::new("auto_reverse", PropKind::Bool, "Animation"),
880    PropInfo::new("looping", PropKind::Bool, "Animation"),
881    PropInfo::new("enabled", PropKind::Bool, "Animation"),
882];
883
884impl Component for PropertyAnimation {
885    fn class_name(&self) -> &'static str {
886        if self.color { "ColorAnimation" } else { "FloatAnimation" }
887    }
888
889    fn props(&self) -> &'static [PropInfo] {
890        if self.color { COLOR_PROPS } else { FLOAT_PROPS }
891    }
892
893    fn get_prop(&self, name: &str) -> Option<PropValue> {
894        Some(match name {
895            "property" => self.property.clone().into(),
896            "start_value" => self.start_value.clone(),
897            "stop_value" => self.stop_value.clone(),
898            "duration" => self.duration.into(),
899            "delay" => self.delay.into(),
900            "easing" => self.easing.to_value(),
901            "trigger" => PropValue::enum_value(self.trigger),
902            "auto_reverse" => self.auto_reverse.into(),
903            "looping" => self.looping.into(),
904            "enabled" => self.enabled.into(),
905            "keyframes" => self.keyframes.clone().into(),
906            _ => return None,
907        })
908    }
909
910    fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
911        let value_of = |v: PropValue, color: bool| -> Result<PropValue> {
912            Ok(match v {
913                PropValue::Null => PropValue::Null,
914                v if color => PropValue::Color(v.to_color()?),
915                v => PropValue::Float(v.to_f64()?),
916            })
917        };
918        match name {
919            "property" => {
920                self.property = value.to_str()?.to_string();
921                self.original = None;
922            }
923            "start_value" => self.start_value = value_of(value, self.color)?,
924            "stop_value" => self.stop_value = value_of(value, self.color)?,
925            "duration" => self.duration = value.to_f32()?.max(0.0),
926            "delay" => self.delay = value.to_f32()?.max(0.0),
927            "easing" => self.easing = Easing::from_value(value)?,
928            "trigger" => self.trigger = value.to_enum()?,
929            "auto_reverse" => self.auto_reverse = value.to_bool()?,
930            "looping" => self.looping = value.to_bool()?,
931            "enabled" => self.enabled = value.to_bool()?,
932            "keyframes" => {
933                let text = value.to_str()?.to_string();
934                if !text.trim().is_empty() && parse_keyframes(&text).is_none() {
935                    return Err(Error::invalid("use fração:valor separados por ; (0:0; 0.6:1.15; 1:1)"));
936                }
937                self.keyframes = text;
938            }
939            _ => return Err(Error::UnknownProperty(name.to_string())),
940        }
941        Ok(())
942    }
943
944    fn methods(&self) -> &'static [MethodInfo] {
945        const METHODS: &[MethodInfo] = &[MethodInfo::new("start", &[], None), MethodInfo::new("stop", &[], None)];
946        METHODS
947    }
948
949    /// `start` (a de `trigger: none`, ou uma linha da lista pelo código) e `stop` (o valor fica
950    /// onde está), em todas as linguagens (pelo protocolo), como o [`Ui::start_animation`].
951    fn invoke(&mut self, ctx: &mut crate::EventCtx<'_>, method: &str, _args: &[PropValue]) -> std::result::Result<PropValue, String> {
952        match method {
953            "start" => {
954                let id = ctx.id;
955                ctx.ui.play_with(id, self, true).map_err(|e| e.to_string())?;
956            }
957            "stop" => ctx.ui.stop_animation(ctx.id),
958            _ => return Err(format!("{} não tem o método '{method}'", self.class_name())),
959        }
960        Ok(PropValue::Null)
961    }
962}