1use 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#[derive(Clone, Copy, Debug, Default, PartialEq)]
27pub enum Easing {
28 #[default]
29 Linear,
30 InQuad,
31 OutQuad,
32 InOutQuad,
33 OutCubic,
34 InOutCubic,
35 OutBack,
37 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 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 pub const NAMES: &'static [&'static str] =
86 &["linear", "in_quad", "out_quad", "in_out_quad", "out_cubic", "in_out_cubic", "out_back"];
87
88 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 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 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 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
145fn 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
197pub enum Trigger {
198 #[default]
200 None,
201 Hover,
202 Pressed,
203 Focused,
204 Checked,
205 Appear,
208 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
259pub 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
275fn 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#[derive(Clone, Debug)]
293pub(crate) struct Running {
294 pub(crate) target: ComponentId,
295 property: String,
296 from: AnimValue,
297 to: AnimValue,
298 start: f64,
300 duration: f64,
301 easing: Easing,
302 auto_reverse: bool,
303 looping: bool,
304 keyframes: std::rc::Rc<[(f32, f64)]>,
306 pub(crate) owner: Option<ComponentId>,
308}
309
310#[derive(Clone, Copy, Debug, PartialEq)]
312pub struct AnimationOptions {
313 pub duration_ms: f32,
314 pub delay_ms: f32,
316 pub easing: Easing,
317 pub auto_reverse: bool,
319 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 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 let named = |v: PropValue| match v {
364 PropValue::String(s) if crate::palette::is_named(&s) || crate::ui::is_hex_with_opacity(&s) => self.theme.resolve_color(&s).map_or(PropValue::String(s), PropValue::Color),
365 v => v,
366 };
367 let (from, to) = (named(from), named(to));
368 let from = AnimValue::from_prop(&from).ok_or_else(invalid)?;
369 let to = AnimValue::from_prop(&to).ok_or_else(invalid)?;
370 self.animations.retain(|a| !(a.target == id && a.property == property));
371 self.animations.push(Running {
372 target: id,
373 property: property.to_string(),
374 from,
375 to,
376 start: self.time + (options.delay_ms.max(0.0) / 1000.0) as f64,
377 duration: (options.duration_ms.max(0.0) / 1000.0) as f64,
378 easing: options.easing,
379 auto_reverse: options.auto_reverse,
380 looping: options.looping,
381 keyframes: std::rc::Rc::from(Vec::new()),
382 owner,
383 });
384 self.request_repaint();
385 Ok(())
386 }
387
388 pub fn stop_animations(&mut self, id: ComponentId) {
390 self.animations.retain(|a| a.target != id && a.owner != Some(id));
391 }
392
393 pub fn request_frames(&mut self, id: ComponentId) {
396 if !self.frame_hooks.contains(&id) {
397 self.frame_hooks.push(id);
398 }
399 self.repaint_requested = true;
401 }
402
403 fn tick_frame_hooks(&mut self) {
404 for id in std::mem::take(&mut self.frame_hooks) {
405 let more = self.with_component(id, |c, ctx| c.timed_mut().is_some_and(|t| t.frame(ctx))).unwrap_or(false);
406 if more && self.contains(id) && !self.frame_hooks.contains(&id) {
407 self.frame_hooks.push(id);
408 }
409 }
410 }
411
412 pub(crate) fn animates_placement(&self, id: ComponentId) -> bool {
415 self.placement_movers().any(|m| m == id)
416 }
417
418 pub(crate) fn placement_movers(&self) -> impl Iterator<Item = ComponentId> + '_ {
420 self.animations.iter().filter(|a| matches!(a.property.as_str(), "translate_x" | "translate_y" | "opacity")).map(|a| a.target)
421 }
422
423 pub fn is_animating(&self) -> bool {
427 let shown = |id: ComponentId| self.form_shown(id);
428 self.animations.iter().any(|a| shown(a.target))
429 || self.frame_hooks.iter().any(|&id| shown(id))
430 || self.frame_requests.borrow().iter().any(|(id, f)| f.0 && self.contains(*id) && shown(*id))
431 || self.is_flinging()
432 || self.is_middle_scrolling()
433 || self.overscroll_active()
434 || !self.transitions.is_empty()
435 }
436
437 pub fn tick(&mut self) {
440 self.tick_flings();
441 self.tick_middle_scrolls();
442 self.tick_overscroll();
443 self.tick_busy();
444 self.tick_transitions();
445 self.check_appear();
446 self.tick_frame_hooks();
447 if self.animations.is_empty() {
448 return;
449 }
450 let _profile = crate::profile::scope(crate::profile::Lane::Animation, || format!("{} animações", self.animations.len()));
451 let now = self.time;
452 let mut updates = Vec::with_capacity(self.animations.len());
453 self.animations.retain_mut(|a| {
454 let span = if a.auto_reverse { a.duration * 2.0 } else { a.duration };
455 let mut elapsed = (now - a.start).max(0.0);
456 let finished = !a.looping && elapsed >= span;
457 if a.looping && span > 0.0 {
458 elapsed %= span;
459 }
460 let mut t = if a.duration > 0.0 { (elapsed / a.duration) as f32 } else { 1.0 };
461 if finished {
462 t = if a.auto_reverse { 0.0 } else { 1.0 };
463 } else if a.auto_reverse && t > 1.0 {
464 t = 2.0 - t;
465 }
466 let eased = a.easing.apply(t.min(1.0));
467 let value = if a.keyframes.is_empty() { a.from.lerp(a.to, eased) } else { AnimValue::Float(sample_keyframes(&a.keyframes, eased)) };
468 updates.push((a.target, a.property.clone(), value.to_prop()));
469 !finished
470 });
471 for (id, property, value) in updates {
472 let _ = self.set_prop(id, &property, value);
474 }
475 }
476
477 pub fn start_animation(&mut self, animation: ComponentId) -> Result<()> {
479 self.play_animation(animation, true)
480 }
481
482 pub(crate) fn run_triggers(&mut self, control: ComponentId, trigger: Trigger, active: bool) {
485 let animations: Vec<ComponentId> = self
486 .children(control)
487 .iter()
488 .copied()
489 .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == trigger))
490 .collect();
491 for animation in animations {
492 let _ = self.play_animation(animation, active);
493 }
494 }
495
496 pub fn stop_animation(&mut self, animation: ComponentId) {
498 self.animations.retain(|r| r.owner != Some(animation));
499 }
500
501 fn play_animation(&mut self, animation: ComponentId, forward: bool) -> Result<()> {
502 let mut a = self.get::<PropertyAnimation>(animation).ok_or(Error::InvalidId)?.clone();
503 let result = self.play_with(animation, &mut a, forward);
504 if let Some(anim) = self.get_mut::<PropertyAnimation>(animation) {
505 anim.original = a.original;
506 }
507 result
508 }
509
510 fn play_with(&mut self, animation: ComponentId, a: &mut PropertyAnimation, forward: bool) -> Result<()> {
513 let target = self.parent(animation).ok_or(Error::InvalidId)?;
514 let current = self.get_prop(target, &a.property)?;
515 let original = a.original.clone().unwrap_or_else(|| current.clone());
516 a.original = Some(original.clone());
517 let (from, to) = if forward {
518 let from = if a.start_value == PropValue::Null { current } else { a.start_value.clone() };
519 (from, a.stop_value.clone())
520 } else {
521 (current, original)
522 };
523 let options = AnimationOptions {
524 duration_ms: a.duration,
525 delay_ms: if forward { a.delay } else { 0.0 },
526 easing: a.easing,
527 auto_reverse: forward && a.auto_reverse,
528 looping: forward && a.looping,
529 };
530 self.animate_from_to(target, &a.property, from, to, options, Some(animation))?;
531 if forward {
533 if let Some(steps) = parse_keyframes(&a.keyframes) {
534 if let Some(run) = self.animations.iter_mut().find(|r| r.target == target && r.property == a.property) {
535 run.keyframes = std::rc::Rc::from(steps);
536 }
537 }
538 }
539 Ok(())
540 }
541
542 fn settle_animation(&mut self, animation: ComponentId, forward: bool) {
546 self.stop_animation(animation);
547 let (Some(target), Some(mut a)) = (self.parent(animation), self.get::<PropertyAnimation>(animation).cloned()) else { return };
548 if !forward {
549 if let Some(original) = a.original {
550 let _ = self.set_prop(target, &a.property, original);
551 }
552 return;
553 }
554 if a.looping {
555 let _ = self.play_animation(animation, true);
556 return;
557 }
558 let Ok(current) = self.get_prop(target, &a.property) else { return };
559 let end = match parse_keyframes(&a.keyframes) {
560 Some(steps) => PropValue::Float(steps.last().map_or(0.0, |s| s.1)),
561 None if a.auto_reverse => if a.start_value == PropValue::Null { current.clone() } else { a.start_value.clone() },
563 None => a.stop_value.clone(),
564 };
565 a.original.get_or_insert(current);
566 if let Some(anim) = self.get_mut::<PropertyAnimation>(animation) {
567 anim.original = a.original;
568 }
569 let _ = self.set_prop(target, &a.property, end);
570 }
571
572 fn animations_within(&self, root: ComponentId) -> Vec<ComponentId> {
574 let mut out = Vec::new();
575 let mut stack = vec![root];
576 while let Some(c) = stack.pop() {
577 if self.get::<PropertyAnimation>(c).is_some() {
578 out.push(c);
579 }
580 stack.extend(self.children(c).iter().copied());
581 }
582 out
583 }
584
585 pub fn has_animations(&self, root: ComponentId) -> bool {
588 !self.animations_within(root).is_empty()
589 }
590
591 pub fn reset_animations(&mut self, root: ComponentId) -> bool {
597 let mut appeared = false;
598 let animations = self.animations_within(root);
599 for &animation in &animations {
600 self.stop_animation(animation);
601 let Some(target) = self.parent(animation) else { continue };
602 let Some(a) = self.get_mut::<PropertyAnimation>(animation) else { continue };
603 let property = a.property.clone();
604 let original = a.original.take();
605 if a.trigger == Trigger::Appear {
606 appeared |= a.appeared;
607 a.appeared = false;
608 if let Some(waiting) = self.appear_waiting.as_mut().filter(|w| !w.contains(&animation)) {
610 waiting.push(animation);
611 }
612 }
613 if let Some(original) = original {
614 let _ = self.set_prop(target, &property, original);
615 }
616 }
617 for animation in animations {
618 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 };
619 let state = self.cb(target).map(|cb| cb.state()).unwrap_or_default();
620 let active = match trigger {
621 Trigger::Hover => state.hover,
622 Trigger::Pressed => state.pressed,
623 Trigger::Focused => state.focused,
624 Trigger::Checked => state.checked,
625 Trigger::HoverWithin => self.hover_within(target).0,
626 Trigger::None | Trigger::Appear => false,
627 };
628 if enabled && active {
629 self.settle_animation(animation, true);
630 }
631 }
632 appeared
633 }
634
635 pub fn finish_appear(&mut self, root: ComponentId) {
638 for animation in self.animations_within(root) {
639 let Some(a) = self.get_mut::<PropertyAnimation>(animation).filter(|a| a.trigger == Trigger::Appear && a.enabled) else { continue };
640 a.appeared = true;
641 if let Some(waiting) = self.appear_waiting.as_mut() {
642 waiting.retain(|w| *w != animation);
643 }
644 self.settle_animation(animation, true);
645 }
646 }
647
648 pub(crate) fn settle_triggers(&mut self, control: ComponentId, trigger: Trigger, active: bool) {
651 let animations: Vec<ComponentId> = self
652 .children(control)
653 .iter()
654 .copied()
655 .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == trigger))
656 .collect();
657 for animation in animations {
658 self.settle_animation(animation, active);
659 }
660 }
661
662 pub(crate) fn hover_within_hosts(&mut self) -> &[ComponentId] {
664 if self.hover_within_hosts.is_none() {
665 let mut hosts: Vec<ComponentId> = self
666 .components()
667 .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.trigger == Trigger::HoverWithin))
668 .filter_map(|c| self.parent(c))
669 .collect();
670 hosts.dedup();
671 self.hover_within_hosts = Some(hosts);
672 }
673 self.hover_within_hosts.as_deref().unwrap_or_default()
674 }
675
676 pub(crate) fn check_appear(&mut self) {
679 if self.appear_waiting.is_none() {
680 let waiting: Vec<ComponentId> = self
681 .components()
682 .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == Trigger::Appear && !a.appeared))
683 .collect();
684 self.appear_waiting = Some(waiting);
685 }
686 let Some(waiting) = self.appear_waiting.clone() else { return };
687 if waiting.is_empty() || self.design_mode {
688 return;
689 }
690 let mut left = Vec::new();
691 for animation in waiting {
692 let Some(target) = self.parent(animation) else { continue };
693 if self.visible_fraction(target) >= 0.15 {
694 if let Some(a) = self.get_mut::<PropertyAnimation>(animation) {
695 a.appeared = true;
696 }
697 let _ = self.play_animation(animation, true);
698 } else {
699 left.push(animation);
700 }
701 }
702 self.appear_waiting = Some(left);
703 }
704
705 fn visible_fraction(&self, id: ComponentId) -> f32 {
708 let root = self.root_of(id);
709 if !self.is_open(root) {
710 return 0.0;
711 }
712 let Some(r) = self.absolute_rect(id) else { return 0.0 };
713 if !self.cb(id).is_some_and(|cb| cb.visible()) {
714 return 0.0;
715 }
716 let area = (r.width * r.height).max(1.0);
717 let (mut x0, mut y0, mut x1, mut y1) = (r.x, r.y, r.right(), r.bottom());
718 let mut current = self.parent(id);
719 while let Some(p) = current {
720 if let Some(c) = self.absolute_rect(p) {
721 (x0, y0, x1, y1) = (x0.max(c.x), y0.max(c.y), x1.min(c.right()), y1.min(c.bottom()));
722 }
723 if !self.cb(p).is_none_or(|cb| cb.visible()) {
724 return 0.0;
725 }
726 current = self.parent(p);
727 }
728 ((x1 - x0).max(0.0) * (y1 - y0).max(0.0)) / area
729 }
730}
731
732#[derive(Clone, Debug, PartialEq)]
740pub struct PropertyAnimation {
741 color: bool,
742 pub property: String,
744 pub start_value: PropValue,
746 pub stop_value: PropValue,
748 pub duration: f32,
750 pub delay: f32,
752 pub easing: Easing,
754 pub trigger: Trigger,
757 pub auto_reverse: bool,
759 pub looping: bool,
761 pub enabled: bool,
763 pub keyframes: String,
766 original: Option<PropValue>,
768 pub(crate) appeared: bool,
770}
771
772impl PropertyAnimation {
773 fn new(color: bool, property: &str, stop_value: PropValue) -> Self {
774 Self {
775 color,
776 property: property.to_string(),
777 start_value: PropValue::Null,
778 stop_value,
779 duration: 200.0,
780 delay: 0.0,
781 easing: Easing::OutQuad,
782 trigger: Trigger::None,
783 auto_reverse: false,
784 looping: false,
785 enabled: true,
786 original: None,
787 keyframes: String::new(),
788 appeared: false,
789 }
790 }
791
792 pub fn float(property: &str, stop_value: f64) -> Self {
794 Self::new(false, property, PropValue::Float(stop_value))
795 }
796
797 pub fn color(property: &str, stop_value: Color) -> Self {
799 Self::new(true, property, PropValue::Color(stop_value))
800 }
801
802 pub fn with_trigger(mut self, trigger: Trigger) -> Self {
803 self.trigger = trigger;
804 self
805 }
806
807 pub fn with_duration(mut self, ms: f32) -> Self {
808 self.duration = ms;
809 self
810 }
811
812 pub fn with_easing(mut self, easing: Easing) -> Self {
813 self.easing = easing;
814 self
815 }
816
817 pub fn with_delay(mut self, ms: f32) -> Self {
818 self.delay = ms;
819 self
820 }
821}
822
823#[derive(Clone, Debug, PartialEq)]
825pub struct FloatAnimation(pub PropertyAnimation);
826
827impl Default for FloatAnimation {
828 fn default() -> Self {
829 Self(PropertyAnimation::float("opacity", 1.0))
830 }
831}
832
833#[derive(Clone, Debug, PartialEq)]
835pub struct ColorAnimation(pub PropertyAnimation);
836
837impl Default for ColorAnimation {
838 fn default() -> Self {
839 Self(PropertyAnimation::color("fill", Color::TRANSPARENT))
840 }
841}
842
843macro_rules! delegate_animation {
844 ($t:ty, $name:literal) => {
845 impl Component for $t {
846 fn class_name(&self) -> &'static str {
847 $name
848 }
849
850 fn inner(&self) -> Option<&dyn Component> {
851 Some(&self.0)
852 }
853
854 fn inner_mut(&mut self) -> Option<&mut dyn Component> {
855 Some(&mut self.0)
856 }
857
858 fn methods(&self) -> &'static [MethodInfo] {
859 self.0.methods()
860 }
861 }
862 };
863}
864
865delegate_animation!(FloatAnimation, "FloatAnimation");
866delegate_animation!(ColorAnimation, "ColorAnimation");
867
868const FLOAT_PROPS: &[PropInfo] = &[
869 PropInfo::new("property", PropKind::String, "Animation"),
870 PropInfo::new("start_value", PropKind::Float, "Animation"),
871 PropInfo::new("stop_value", PropKind::Float, "Animation"),
872 PropInfo::new("duration", PropKind::Duration, "Animation"),
873 PropInfo::new("delay", PropKind::Duration, "Animation"),
874 PropInfo::new("easing", PropKind::Easing, "Animation"),
875 PropInfo::new("trigger", PropKind::Enum(Trigger::NAMES), "Animation").rust_type("Trigger"),
876 PropInfo::new("auto_reverse", PropKind::Bool, "Animation"),
877 PropInfo::new("looping", PropKind::Bool, "Animation"),
878 PropInfo::new("enabled", PropKind::Bool, "Animation"),
879 PropInfo::new("keyframes", PropKind::String, "Animation"),
880];
881
882const COLOR_PROPS: &[PropInfo] = &[
883 PropInfo::new("property", PropKind::String, "Animation"),
884 PropInfo::new("start_value", PropKind::Color, "Animation"),
885 PropInfo::new("stop_value", PropKind::Color, "Animation"),
886 PropInfo::new("duration", PropKind::Duration, "Animation"),
887 PropInfo::new("delay", PropKind::Duration, "Animation"),
888 PropInfo::new("easing", PropKind::Easing, "Animation"),
889 PropInfo::new("trigger", PropKind::Enum(Trigger::NAMES), "Animation").rust_type("Trigger"),
890 PropInfo::new("auto_reverse", PropKind::Bool, "Animation"),
891 PropInfo::new("looping", PropKind::Bool, "Animation"),
892 PropInfo::new("enabled", PropKind::Bool, "Animation"),
893];
894
895impl Component for PropertyAnimation {
896 fn class_name(&self) -> &'static str {
897 if self.color { "ColorAnimation" } else { "FloatAnimation" }
898 }
899
900 fn props(&self) -> &'static [PropInfo] {
901 if self.color { COLOR_PROPS } else { FLOAT_PROPS }
902 }
903
904 fn get_prop(&self, name: &str) -> Option<PropValue> {
905 Some(match name {
906 "property" => self.property.clone().into(),
907 "start_value" => self.start_value.clone(),
908 "stop_value" => self.stop_value.clone(),
909 "duration" => self.duration.into(),
910 "delay" => self.delay.into(),
911 "easing" => self.easing.to_value(),
912 "trigger" => PropValue::enum_value(self.trigger),
913 "auto_reverse" => self.auto_reverse.into(),
914 "looping" => self.looping.into(),
915 "enabled" => self.enabled.into(),
916 "keyframes" => self.keyframes.clone().into(),
917 _ => return None,
918 })
919 }
920
921 fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
922 let value_of = |v: PropValue, color: bool| -> Result<PropValue> {
923 Ok(match v {
924 PropValue::Null => PropValue::Null,
925 v if color => PropValue::Color(v.to_color()?),
926 v => PropValue::Float(v.to_f64()?),
927 })
928 };
929 match name {
930 "property" => {
931 self.property = value.to_str()?.to_string();
932 self.original = None;
933 }
934 "start_value" => self.start_value = value_of(value, self.color)?,
935 "stop_value" => self.stop_value = value_of(value, self.color)?,
936 "duration" => self.duration = value.to_f32()?.max(0.0),
937 "delay" => self.delay = value.to_f32()?.max(0.0),
938 "easing" => self.easing = Easing::from_value(value)?,
939 "trigger" => self.trigger = value.to_enum()?,
940 "auto_reverse" => self.auto_reverse = value.to_bool()?,
941 "looping" => self.looping = value.to_bool()?,
942 "enabled" => self.enabled = value.to_bool()?,
943 "keyframes" => {
944 let text = value.to_str()?.to_string();
945 if !text.trim().is_empty() && parse_keyframes(&text).is_none() {
946 return Err(Error::invalid("use fração:valor separados por ; (0:0; 0.6:1.15; 1:1)"));
947 }
948 self.keyframes = text;
949 }
950 _ => return Err(Error::UnknownProperty(name.to_string())),
951 }
952 Ok(())
953 }
954
955 fn methods(&self) -> &'static [MethodInfo] {
956 const METHODS: &[MethodInfo] = &[MethodInfo::new("start", &[], None), MethodInfo::new("stop", &[], None)];
957 METHODS
958 }
959
960 fn invoke(&mut self, ctx: &mut crate::EventCtx<'_>, method: &str, _args: &[PropValue]) -> std::result::Result<PropValue, String> {
963 match method {
964 "start" => {
965 let id = ctx.id;
966 ctx.ui.play_with(id, self, true).map_err(|e| e.to_string())?;
967 }
968 "stop" => ctx.ui.stop_animation(ctx.id),
969 _ => return Err(format!("{} não tem o método '{method}'", self.class_name())),
970 }
971 Ok(PropValue::Null)
972 }
973}