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 {
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 pub fn stop_animations(&mut self, id: ComponentId) {
389 self.animations.retain(|a| a.target != id && a.owner != Some(id));
390 }
391
392 pub fn request_frames(&mut self, id: ComponentId) {
395 if !self.frame_hooks.contains(&id) {
396 self.frame_hooks.push(id);
397 }
398 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 pub(crate) fn animates_placement(&self, id: ComponentId) -> bool {
414 self.placement_movers().any(|m| m == id)
415 }
416
417 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 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.is_middle_scrolling() || self.overscroll_active() || !self.transitions.is_empty()
425 }
426
427 pub fn tick(&mut self) {
430 self.tick_flings();
431 self.tick_middle_scrolls();
432 self.tick_overscroll();
433 self.tick_busy();
434 self.tick_transitions();
435 self.check_appear();
436 self.tick_frame_hooks();
437 if self.animations.is_empty() {
438 return;
439 }
440 let _profile = crate::profile::scope(crate::profile::Lane::Animation, || format!("{} animações", self.animations.len()));
441 let now = self.time;
442 let mut updates = Vec::with_capacity(self.animations.len());
443 self.animations.retain_mut(|a| {
444 let span = if a.auto_reverse { a.duration * 2.0 } else { a.duration };
445 let mut elapsed = (now - a.start).max(0.0);
446 let finished = !a.looping && elapsed >= span;
447 if a.looping && span > 0.0 {
448 elapsed %= span;
449 }
450 let mut t = if a.duration > 0.0 { (elapsed / a.duration) as f32 } else { 1.0 };
451 if finished {
452 t = if a.auto_reverse { 0.0 } else { 1.0 };
453 } else if a.auto_reverse && t > 1.0 {
454 t = 2.0 - t;
455 }
456 let eased = a.easing.apply(t.min(1.0));
457 let value = if a.keyframes.is_empty() { a.from.lerp(a.to, eased) } else { AnimValue::Float(sample_keyframes(&a.keyframes, eased)) };
458 updates.push((a.target, a.property.clone(), value.to_prop()));
459 !finished
460 });
461 for (id, property, value) in updates {
462 let _ = self.set_prop(id, &property, value);
464 }
465 }
466
467 pub fn start_animation(&mut self, animation: ComponentId) -> Result<()> {
469 self.play_animation(animation, true)
470 }
471
472 pub(crate) fn run_triggers(&mut self, control: ComponentId, trigger: Trigger, active: bool) {
475 let animations: Vec<ComponentId> = self
476 .children(control)
477 .iter()
478 .copied()
479 .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == trigger))
480 .collect();
481 for animation in animations {
482 let _ = self.play_animation(animation, active);
483 }
484 }
485
486 pub fn stop_animation(&mut self, animation: ComponentId) {
488 self.animations.retain(|r| r.owner != Some(animation));
489 }
490
491 fn play_animation(&mut self, animation: ComponentId, forward: bool) -> Result<()> {
492 let mut a = self.get::<PropertyAnimation>(animation).ok_or(Error::InvalidId)?.clone();
493 let result = self.play_with(animation, &mut a, forward);
494 if let Some(anim) = self.get_mut::<PropertyAnimation>(animation) {
495 anim.original = a.original;
496 }
497 result
498 }
499
500 fn play_with(&mut self, animation: ComponentId, a: &mut PropertyAnimation, forward: bool) -> Result<()> {
503 let target = self.parent(animation).ok_or(Error::InvalidId)?;
504 let current = self.get_prop(target, &a.property)?;
505 let original = a.original.clone().unwrap_or_else(|| current.clone());
506 a.original = Some(original.clone());
507 let (from, to) = if forward {
508 let from = if a.start_value == PropValue::Null { current } else { a.start_value.clone() };
509 (from, a.stop_value.clone())
510 } else {
511 (current, original)
512 };
513 let options = AnimationOptions {
514 duration_ms: a.duration,
515 delay_ms: if forward { a.delay } else { 0.0 },
516 easing: a.easing,
517 auto_reverse: forward && a.auto_reverse,
518 looping: forward && a.looping,
519 };
520 self.animate_from_to(target, &a.property, from, to, options, Some(animation))?;
521 if forward {
523 if let Some(steps) = parse_keyframes(&a.keyframes) {
524 if let Some(run) = self.animations.iter_mut().find(|r| r.target == target && r.property == a.property) {
525 run.keyframes = std::rc::Rc::from(steps);
526 }
527 }
528 }
529 Ok(())
530 }
531
532 fn settle_animation(&mut self, animation: ComponentId, forward: bool) {
536 self.stop_animation(animation);
537 let (Some(target), Some(mut a)) = (self.parent(animation), self.get::<PropertyAnimation>(animation).cloned()) else { return };
538 if !forward {
539 if let Some(original) = a.original {
540 let _ = self.set_prop(target, &a.property, original);
541 }
542 return;
543 }
544 if a.looping {
545 let _ = self.play_animation(animation, true);
546 return;
547 }
548 let Ok(current) = self.get_prop(target, &a.property) else { return };
549 let end = match parse_keyframes(&a.keyframes) {
550 Some(steps) => PropValue::Float(steps.last().map_or(0.0, |s| s.1)),
551 None if a.auto_reverse => if a.start_value == PropValue::Null { current.clone() } else { a.start_value.clone() },
553 None => a.stop_value.clone(),
554 };
555 a.original.get_or_insert(current);
556 if let Some(anim) = self.get_mut::<PropertyAnimation>(animation) {
557 anim.original = a.original;
558 }
559 let _ = self.set_prop(target, &a.property, end);
560 }
561
562 fn animations_within(&self, root: ComponentId) -> Vec<ComponentId> {
564 let mut out = Vec::new();
565 let mut stack = vec![root];
566 while let Some(c) = stack.pop() {
567 if self.get::<PropertyAnimation>(c).is_some() {
568 out.push(c);
569 }
570 stack.extend(self.children(c).iter().copied());
571 }
572 out
573 }
574
575 pub fn has_animations(&self, root: ComponentId) -> bool {
578 !self.animations_within(root).is_empty()
579 }
580
581 pub fn reset_animations(&mut self, root: ComponentId) -> bool {
587 let mut appeared = false;
588 let animations = self.animations_within(root);
589 for &animation in &animations {
590 self.stop_animation(animation);
591 let Some(target) = self.parent(animation) else { continue };
592 let Some(a) = self.get_mut::<PropertyAnimation>(animation) else { continue };
593 let property = a.property.clone();
594 let original = a.original.take();
595 if a.trigger == Trigger::Appear {
596 appeared |= a.appeared;
597 a.appeared = false;
598 if let Some(waiting) = self.appear_waiting.as_mut().filter(|w| !w.contains(&animation)) {
600 waiting.push(animation);
601 }
602 }
603 if let Some(original) = original {
604 let _ = self.set_prop(target, &property, original);
605 }
606 }
607 for animation in animations {
608 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 };
609 let state = self.cb(target).map(|cb| cb.state()).unwrap_or_default();
610 let active = match trigger {
611 Trigger::Hover => state.hover,
612 Trigger::Pressed => state.pressed,
613 Trigger::Focused => state.focused,
614 Trigger::Checked => state.checked,
615 Trigger::HoverWithin => self.hover_within(target).0,
616 Trigger::None | Trigger::Appear => false,
617 };
618 if enabled && active {
619 self.settle_animation(animation, true);
620 }
621 }
622 appeared
623 }
624
625 pub fn finish_appear(&mut self, root: ComponentId) {
628 for animation in self.animations_within(root) {
629 let Some(a) = self.get_mut::<PropertyAnimation>(animation).filter(|a| a.trigger == Trigger::Appear && a.enabled) else { continue };
630 a.appeared = true;
631 if let Some(waiting) = self.appear_waiting.as_mut() {
632 waiting.retain(|w| *w != animation);
633 }
634 self.settle_animation(animation, true);
635 }
636 }
637
638 pub(crate) fn settle_triggers(&mut self, control: ComponentId, trigger: Trigger, active: bool) {
641 let animations: Vec<ComponentId> = self
642 .children(control)
643 .iter()
644 .copied()
645 .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == trigger))
646 .collect();
647 for animation in animations {
648 self.settle_animation(animation, active);
649 }
650 }
651
652 pub(crate) fn hover_within_hosts(&mut self) -> &[ComponentId] {
654 if self.hover_within_hosts.is_none() {
655 let mut hosts: Vec<ComponentId> = self
656 .components()
657 .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.trigger == Trigger::HoverWithin))
658 .filter_map(|c| self.parent(c))
659 .collect();
660 hosts.dedup();
661 self.hover_within_hosts = Some(hosts);
662 }
663 self.hover_within_hosts.as_deref().unwrap_or_default()
664 }
665
666 pub(crate) fn check_appear(&mut self) {
669 if self.appear_waiting.is_none() {
670 let waiting: Vec<ComponentId> = self
671 .components()
672 .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == Trigger::Appear && !a.appeared))
673 .collect();
674 self.appear_waiting = Some(waiting);
675 }
676 let Some(waiting) = self.appear_waiting.clone() else { return };
677 if waiting.is_empty() || self.design_mode {
678 return;
679 }
680 let mut left = Vec::new();
681 for animation in waiting {
682 let Some(target) = self.parent(animation) else { continue };
683 if self.visible_fraction(target) >= 0.15 {
684 if let Some(a) = self.get_mut::<PropertyAnimation>(animation) {
685 a.appeared = true;
686 }
687 let _ = self.play_animation(animation, true);
688 } else {
689 left.push(animation);
690 }
691 }
692 self.appear_waiting = Some(left);
693 }
694
695 fn visible_fraction(&self, id: ComponentId) -> f32 {
698 let root = self.root_of(id);
699 if !self.is_open(root) {
700 return 0.0;
701 }
702 let Some(r) = self.absolute_rect(id) else { return 0.0 };
703 if !self.cb(id).is_some_and(|cb| cb.visible()) {
704 return 0.0;
705 }
706 let area = (r.width * r.height).max(1.0);
707 let (mut x0, mut y0, mut x1, mut y1) = (r.x, r.y, r.right(), r.bottom());
708 let mut current = self.parent(id);
709 while let Some(p) = current {
710 if let Some(c) = self.absolute_rect(p) {
711 (x0, y0, x1, y1) = (x0.max(c.x), y0.max(c.y), x1.min(c.right()), y1.min(c.bottom()));
712 }
713 if !self.cb(p).is_none_or(|cb| cb.visible()) {
714 return 0.0;
715 }
716 current = self.parent(p);
717 }
718 ((x1 - x0).max(0.0) * (y1 - y0).max(0.0)) / area
719 }
720}
721
722#[derive(Clone, Debug, PartialEq)]
730pub struct PropertyAnimation {
731 color: bool,
732 pub property: String,
734 pub start_value: PropValue,
736 pub stop_value: PropValue,
738 pub duration: f32,
740 pub delay: f32,
742 pub easing: Easing,
744 pub trigger: Trigger,
747 pub auto_reverse: bool,
749 pub looping: bool,
751 pub enabled: bool,
753 pub keyframes: String,
756 original: Option<PropValue>,
758 pub(crate) appeared: bool,
760}
761
762impl PropertyAnimation {
763 fn new(color: bool, property: &str, stop_value: PropValue) -> Self {
764 Self {
765 color,
766 property: property.to_string(),
767 start_value: PropValue::Null,
768 stop_value,
769 duration: 200.0,
770 delay: 0.0,
771 easing: Easing::OutQuad,
772 trigger: Trigger::None,
773 auto_reverse: false,
774 looping: false,
775 enabled: true,
776 original: None,
777 keyframes: String::new(),
778 appeared: false,
779 }
780 }
781
782 pub fn float(property: &str, stop_value: f64) -> Self {
784 Self::new(false, property, PropValue::Float(stop_value))
785 }
786
787 pub fn color(property: &str, stop_value: Color) -> Self {
789 Self::new(true, property, PropValue::Color(stop_value))
790 }
791
792 pub fn with_trigger(mut self, trigger: Trigger) -> Self {
793 self.trigger = trigger;
794 self
795 }
796
797 pub fn with_duration(mut self, ms: f32) -> Self {
798 self.duration = ms;
799 self
800 }
801
802 pub fn with_easing(mut self, easing: Easing) -> Self {
803 self.easing = easing;
804 self
805 }
806
807 pub fn with_delay(mut self, ms: f32) -> Self {
808 self.delay = ms;
809 self
810 }
811}
812
813#[derive(Clone, Debug, PartialEq)]
815pub struct FloatAnimation(pub PropertyAnimation);
816
817impl Default for FloatAnimation {
818 fn default() -> Self {
819 Self(PropertyAnimation::float("opacity", 1.0))
820 }
821}
822
823#[derive(Clone, Debug, PartialEq)]
825pub struct ColorAnimation(pub PropertyAnimation);
826
827impl Default for ColorAnimation {
828 fn default() -> Self {
829 Self(PropertyAnimation::color("fill", Color::TRANSPARENT))
830 }
831}
832
833macro_rules! delegate_animation {
834 ($t:ty, $name:literal) => {
835 impl Component for $t {
836 fn class_name(&self) -> &'static str {
837 $name
838 }
839
840 fn inner(&self) -> Option<&dyn Component> {
841 Some(&self.0)
842 }
843
844 fn inner_mut(&mut self) -> Option<&mut dyn Component> {
845 Some(&mut self.0)
846 }
847
848 fn methods(&self) -> &'static [MethodInfo] {
849 self.0.methods()
850 }
851 }
852 };
853}
854
855delegate_animation!(FloatAnimation, "FloatAnimation");
856delegate_animation!(ColorAnimation, "ColorAnimation");
857
858const FLOAT_PROPS: &[PropInfo] = &[
859 PropInfo::new("property", PropKind::String, "Animation"),
860 PropInfo::new("start_value", PropKind::Float, "Animation"),
861 PropInfo::new("stop_value", PropKind::Float, "Animation"),
862 PropInfo::new("duration", PropKind::Duration, "Animation"),
863 PropInfo::new("delay", PropKind::Duration, "Animation"),
864 PropInfo::new("easing", PropKind::Easing, "Animation"),
865 PropInfo::new("trigger", PropKind::Enum(Trigger::NAMES), "Animation").rust_type("Trigger"),
866 PropInfo::new("auto_reverse", PropKind::Bool, "Animation"),
867 PropInfo::new("looping", PropKind::Bool, "Animation"),
868 PropInfo::new("enabled", PropKind::Bool, "Animation"),
869 PropInfo::new("keyframes", PropKind::String, "Animation"),
870];
871
872const COLOR_PROPS: &[PropInfo] = &[
873 PropInfo::new("property", PropKind::String, "Animation"),
874 PropInfo::new("start_value", PropKind::Color, "Animation"),
875 PropInfo::new("stop_value", PropKind::Color, "Animation"),
876 PropInfo::new("duration", PropKind::Duration, "Animation"),
877 PropInfo::new("delay", PropKind::Duration, "Animation"),
878 PropInfo::new("easing", PropKind::Easing, "Animation"),
879 PropInfo::new("trigger", PropKind::Enum(Trigger::NAMES), "Animation").rust_type("Trigger"),
880 PropInfo::new("auto_reverse", PropKind::Bool, "Animation"),
881 PropInfo::new("looping", PropKind::Bool, "Animation"),
882 PropInfo::new("enabled", PropKind::Bool, "Animation"),
883];
884
885impl Component for PropertyAnimation {
886 fn class_name(&self) -> &'static str {
887 if self.color { "ColorAnimation" } else { "FloatAnimation" }
888 }
889
890 fn props(&self) -> &'static [PropInfo] {
891 if self.color { COLOR_PROPS } else { FLOAT_PROPS }
892 }
893
894 fn get_prop(&self, name: &str) -> Option<PropValue> {
895 Some(match name {
896 "property" => self.property.clone().into(),
897 "start_value" => self.start_value.clone(),
898 "stop_value" => self.stop_value.clone(),
899 "duration" => self.duration.into(),
900 "delay" => self.delay.into(),
901 "easing" => self.easing.to_value(),
902 "trigger" => PropValue::enum_value(self.trigger),
903 "auto_reverse" => self.auto_reverse.into(),
904 "looping" => self.looping.into(),
905 "enabled" => self.enabled.into(),
906 "keyframes" => self.keyframes.clone().into(),
907 _ => return None,
908 })
909 }
910
911 fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
912 let value_of = |v: PropValue, color: bool| -> Result<PropValue> {
913 Ok(match v {
914 PropValue::Null => PropValue::Null,
915 v if color => PropValue::Color(v.to_color()?),
916 v => PropValue::Float(v.to_f64()?),
917 })
918 };
919 match name {
920 "property" => {
921 self.property = value.to_str()?.to_string();
922 self.original = None;
923 }
924 "start_value" => self.start_value = value_of(value, self.color)?,
925 "stop_value" => self.stop_value = value_of(value, self.color)?,
926 "duration" => self.duration = value.to_f32()?.max(0.0),
927 "delay" => self.delay = value.to_f32()?.max(0.0),
928 "easing" => self.easing = Easing::from_value(value)?,
929 "trigger" => self.trigger = value.to_enum()?,
930 "auto_reverse" => self.auto_reverse = value.to_bool()?,
931 "looping" => self.looping = value.to_bool()?,
932 "enabled" => self.enabled = value.to_bool()?,
933 "keyframes" => {
934 let text = value.to_str()?.to_string();
935 if !text.trim().is_empty() && parse_keyframes(&text).is_none() {
936 return Err(Error::invalid("use fração:valor separados por ; (0:0; 0.6:1.15; 1:1)"));
937 }
938 self.keyframes = text;
939 }
940 _ => return Err(Error::UnknownProperty(name.to_string())),
941 }
942 Ok(())
943 }
944
945 fn methods(&self) -> &'static [MethodInfo] {
946 const METHODS: &[MethodInfo] = &[MethodInfo::new("start", &[], None), MethodInfo::new("stop", &[], None)];
947 METHODS
948 }
949
950 fn invoke(&mut self, ctx: &mut crate::EventCtx<'_>, method: &str, _args: &[PropValue]) -> std::result::Result<PropValue, String> {
953 match method {
954 "start" => {
955 let id = ctx.id;
956 ctx.ui.play_with(id, self, true).map_err(|e| e.to_string())?;
957 }
958 "stop" => ctx.ui.stop_animation(ctx.id),
959 _ => return Err(format!("{} não tem o método '{method}'", self.class_name())),
960 }
961 Ok(PropValue::Null)
962 }
963}