1use crate::color::Color;
15use crate::component::{Component, ComponentId};
16use crate::error::{Error, Result};
17use crate::prop::{PropEnum, PropInfo, PropKind, PropType, PropValue};
18use crate::ui::Ui;
19
20#[derive(Clone, Copy, Debug, Default, PartialEq)]
23pub enum Easing {
24 #[default]
25 Linear,
26 InQuad,
27 OutQuad,
28 InOutQuad,
29 OutCubic,
30 InOutCubic,
31 OutBack,
33 CubicBezier(f32, f32, f32, f32),
36}
37
38impl Easing {
39 pub const ALL: [Easing; 7] = [
40 Easing::Linear,
41 Easing::InQuad,
42 Easing::OutQuad,
43 Easing::InOutQuad,
44 Easing::OutCubic,
45 Easing::InOutCubic,
46 Easing::OutBack,
47 ];
48
49 pub fn apply(self, t: f32) -> f32 {
51 let t = t.clamp(0.0, 1.0);
52 match self {
53 Easing::Linear => t,
54 Easing::InQuad => t * t,
55 Easing::OutQuad => 1.0 - (1.0 - t) * (1.0 - t),
56 Easing::InOutQuad => {
57 if t < 0.5 {
58 2.0 * t * t
59 } else {
60 1.0 - (-2.0 * t + 2.0).powi(2) / 2.0
61 }
62 }
63 Easing::OutCubic => 1.0 - (1.0 - t).powi(3),
64 Easing::InOutCubic => {
65 if t < 0.5 {
66 4.0 * t * t * t
67 } else {
68 1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
69 }
70 }
71 Easing::OutBack => {
72 let c1 = 1.70158;
73 let c3 = c1 + 1.0;
74 1.0 + c3 * (t - 1.0).powi(3) + c1 * (t - 1.0).powi(2)
75 }
76 Easing::CubicBezier(x1, y1, x2, y2) => cubic_bezier(x1.clamp(0.0, 1.0), y1, x2.clamp(0.0, 1.0), y2, t),
77 }
78 }
79
80 pub const NAMES: &'static [&'static str] =
82 &["linear", "in_quad", "out_quad", "in_out_quad", "out_cubic", "in_out_cubic", "out_back"];
83
84 pub const CSS: [(&'static str, [f32; 4]); 4] = [
86 ("ease", [0.25, 0.1, 0.25, 1.0]),
87 ("ease-in", [0.42, 0.0, 1.0, 1.0]),
88 ("ease-out", [0.0, 0.0, 0.58, 1.0]),
89 ("ease-in-out", [0.42, 0.0, 0.58, 1.0]),
90 ];
91
92 pub fn parse(text: &str) -> Option<Easing> {
95 let text = text.trim();
96 if let Some(args) = text.strip_prefix("cubic-bezier(").and_then(|a| a.strip_suffix(')')) {
97 let v: Vec<f32> = args.split(',').map(|n| n.trim().parse::<f32>()).collect::<Result<_, _>>().ok()?;
98 let [x1, y1, x2, y2] = v[..] else { return None };
99 return Some(Easing::CubicBezier(x1, y1, x2, y2));
100 }
101 if let Some((_, [a, b, c, d])) = Easing::CSS.iter().find(|(n, _)| n.eq_ignore_ascii_case(text)) {
102 return Some(Easing::CubicBezier(*a, *b, *c, *d));
103 }
104 let plain: String = text.chars().filter(|c| *c != '_' && *c != '-').collect();
105 Easing::NAMES
106 .iter()
107 .position(|n| n.replace('_', "").eq_ignore_ascii_case(&plain))
108 .map(|i| Easing::ALL[i])
109 }
110
111 pub fn to_spec(self) -> String {
113 match self {
114 Easing::CubicBezier(a, b, c, d) => {
115 if let Some((name, _)) = Easing::CSS.iter().find(|(_, p)| *p == [a, b, c, d]) {
116 return name.to_string();
117 }
118 let n = |v: f32| format!("{}", (v * 1000.0).round() / 1000.0);
119 format!("cubic-bezier({}, {}, {}, {})", n(a), n(b), n(c), n(d))
120 }
121 named => Easing::NAMES[Easing::ALL.iter().position(|e| *e == named).unwrap_or(0)].to_string(),
122 }
123 }
124
125 pub fn to_bezier(self) -> [f32; 4] {
128 match self {
129 Easing::Linear => [0.0, 0.0, 1.0, 1.0],
130 Easing::InQuad => [0.55, 0.085, 0.68, 0.53],
131 Easing::OutQuad => [0.25, 0.46, 0.45, 0.94],
132 Easing::InOutQuad => [0.455, 0.03, 0.515, 0.955],
133 Easing::OutCubic => [0.215, 0.61, 0.355, 1.0],
134 Easing::InOutCubic => [0.645, 0.045, 0.355, 1.0],
135 Easing::OutBack => [0.175, 0.885, 0.32, 1.275],
136 Easing::CubicBezier(a, b, c, d) => [a, b, c, d],
137 }
138 }
139}
140
141fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, x: f32) -> f32 {
144 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;
145 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;
146 let mut s = x;
147 for _ in 0..8 {
148 let err = curve(x1, x2, s) - x;
149 if err.abs() < 1e-5 {
150 return curve(y1, y2, s);
151 }
152 let d = slope(x1, x2, s);
153 if d.abs() < 1e-6 {
154 break;
155 }
156 s -= err / d;
157 }
158 let (mut lo, mut hi) = (0.0f32, 1.0f32);
159 s = x;
160 for _ in 0..40 {
161 let v = curve(x1, x2, s);
162 if (v - x).abs() < 1e-5 {
163 break;
164 }
165 if v < x { lo = s } else { hi = s }
166 s = (lo + hi) / 2.0;
167 }
168 curve(y1, y2, s)
169}
170
171impl std::str::FromStr for Easing {
172 type Err = Error;
173
174 fn from_str(s: &str) -> Result<Self> {
175 Easing::parse(s).ok_or_else(|| {
176 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(", ")))
177 })
178 }
179}
180
181impl PropType for Easing {
182 const KIND: PropKind = PropKind::Easing;
183 fn to_value(&self) -> PropValue {
184 PropValue::String(self.to_spec())
185 }
186 fn from_value(value: PropValue) -> Result<Self> {
187 value.to_str()?.parse()
188 }
189}
190
191#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
193pub enum Trigger {
194 #[default]
196 None,
197 Hover,
198 Pressed,
199 Focused,
200 Checked,
201 Appear,
204}
205
206impl PropEnum for Trigger {
207 const NAMES: &'static [&'static str] = &["none", "hover", "pressed", "focused", "checked", "appear"];
208
209 fn from_index(index: usize) -> Option<Self> {
210 [Trigger::None, Trigger::Hover, Trigger::Pressed, Trigger::Focused, Trigger::Checked, Trigger::Appear]
211 .get(index)
212 .copied()
213 }
214
215 fn index(self) -> usize {
216 self as usize
217 }
218}
219
220#[derive(Clone, Copy, Debug, PartialEq)]
221pub(crate) enum AnimValue {
222 Float(f64),
223 Color(Color),
224}
225
226impl AnimValue {
227 fn from_prop(v: &PropValue) -> Option<AnimValue> {
228 match v {
229 PropValue::Float(_) | PropValue::Int(_) => v.to_f64().ok().map(AnimValue::Float),
230 PropValue::Color(_) | PropValue::String(_) => v.to_color().ok().map(AnimValue::Color),
231 _ => None,
232 }
233 }
234
235 fn to_prop(self) -> PropValue {
236 match self {
237 AnimValue::Float(v) => PropValue::Float(v),
238 AnimValue::Color(c) => PropValue::Color(c),
239 }
240 }
241
242 fn lerp(self, to: AnimValue, t: f32) -> AnimValue {
243 match (self, to) {
244 (AnimValue::Float(a), AnimValue::Float(b)) => AnimValue::Float(a + (b - a) * t as f64),
245 (AnimValue::Color(a), AnimValue::Color(b)) => AnimValue::Color(a.lerp(b, t)),
246 (_, b) => b,
247 }
248 }
249}
250
251pub fn parse_keyframes(text: &str) -> Option<Vec<(f32, f64)>> {
253 let mut steps = Vec::new();
254 for item in text.split(';').map(str::trim).filter(|s| !s.is_empty()) {
255 let (t, v) = item.split_once(':')?;
256 let t: f32 = t.trim().replace(',', ".").parse().ok()?;
257 let v: f64 = v.trim().replace(',', ".").parse().ok()?;
258 steps.push((t.clamp(0.0, 1.0), v));
259 }
260 if steps.len() < 2 {
261 return None;
262 }
263 steps.sort_by(|a, b| a.0.total_cmp(&b.0));
264 Some(steps)
265}
266
267fn sample_keyframes(steps: &[(f32, f64)], t: f32) -> f64 {
269 let Some(first) = steps.first() else { return 0.0 };
270 if t <= first.0 {
271 return first.1;
272 }
273 for w in steps.windows(2) {
274 let ((t0, v0), (t1, v1)) = (w[0], w[1]);
275 if t <= t1 {
276 let f = if t1 > t0 { ((t - t0) / (t1 - t0)) as f64 } else { 1.0 };
277 return v0 + (v1 - v0) * f;
278 }
279 }
280 steps.last().map_or(0.0, |s| s.1)
281}
282
283#[derive(Clone, Debug)]
285pub(crate) struct Running {
286 pub(crate) target: ComponentId,
287 property: String,
288 from: AnimValue,
289 to: AnimValue,
290 start: f64,
292 duration: f64,
293 easing: Easing,
294 auto_reverse: bool,
295 looping: bool,
296 keyframes: std::rc::Rc<[(f32, f64)]>,
298 pub(crate) owner: Option<ComponentId>,
300}
301
302#[derive(Clone, Copy, Debug, PartialEq)]
304pub struct AnimationOptions {
305 pub duration_ms: f32,
306 pub delay_ms: f32,
308 pub easing: Easing,
309 pub auto_reverse: bool,
311 pub looping: bool,
313}
314
315impl Default for AnimationOptions {
316 fn default() -> Self {
317 Self { duration_ms: 200.0, delay_ms: 0.0, easing: Easing::OutQuad, auto_reverse: false, looping: false }
318 }
319}
320
321impl AnimationOptions {
322 pub fn new(duration_ms: f32, easing: Easing) -> Self {
323 Self { duration_ms, easing, ..Default::default() }
324 }
325}
326
327impl Ui {
328 pub fn animate(
333 &mut self,
334 id: ComponentId,
335 property: &str,
336 to: impl Into<PropValue>,
337 options: AnimationOptions,
338 ) -> Result<()> {
339 let current = self.get_prop(id, property)?;
340 self.animate_from_to(id, property, current, to.into(), options, None)
341 }
342
343 fn animate_from_to(
344 &mut self,
345 id: ComponentId,
346 property: &str,
347 from: PropValue,
348 to: PropValue,
349 options: AnimationOptions,
350 owner: Option<ComponentId>,
351 ) -> Result<()> {
352 let invalid = || Error::invalid("só propriedades numéricas ou de cor podem ser animadas").with_property(property);
353 let named = |v: PropValue| match v {
355 PropValue::String(s) if crate::palette::is_named(&s) => self.theme.resolve_color(&s).map_or(PropValue::String(s), PropValue::Color),
356 v => v,
357 };
358 let (from, to) = (named(from), named(to));
359 let from = AnimValue::from_prop(&from).ok_or_else(invalid)?;
360 let to = AnimValue::from_prop(&to).ok_or_else(invalid)?;
361 self.animations.retain(|a| !(a.target == id && a.property == property));
362 self.animations.push(Running {
363 target: id,
364 property: property.to_string(),
365 from,
366 to,
367 start: self.time + (options.delay_ms.max(0.0) / 1000.0) as f64,
368 duration: (options.duration_ms.max(0.0) / 1000.0) as f64,
369 easing: options.easing,
370 auto_reverse: options.auto_reverse,
371 looping: options.looping,
372 keyframes: std::rc::Rc::from(Vec::new()),
373 owner,
374 });
375 self.request_repaint();
376 Ok(())
377 }
378
379 pub fn stop_animations(&mut self, id: ComponentId) {
381 self.animations.retain(|a| a.target != id && a.owner != Some(id));
382 }
383
384 pub fn request_frames(&mut self, id: ComponentId) {
387 if !self.frame_hooks.contains(&id) {
388 self.frame_hooks.push(id);
389 }
390 self.repaint_requested = true;
392 }
393
394 fn tick_frame_hooks(&mut self) {
395 for id in std::mem::take(&mut self.frame_hooks) {
396 let more = self.with_component(id, |c, ctx| c.frame(ctx)).unwrap_or(false);
397 if more && self.contains(id) && !self.frame_hooks.contains(&id) {
398 self.frame_hooks.push(id);
399 }
400 }
401 }
402
403 pub(crate) fn animates_placement(&self, id: ComponentId) -> bool {
406 self.animations.iter().any(|a| a.target == id && matches!(a.property.as_str(), "translate_x" | "translate_y" | "opacity"))
407 }
408
409 pub fn is_animating(&self) -> bool {
411 !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.transitions.is_empty()
412 }
413
414 pub fn tick(&mut self) {
417 self.tick_flings();
418 self.tick_busy();
419 self.tick_transitions();
420 self.check_appear();
421 self.tick_frame_hooks();
422 if self.animations.is_empty() {
423 return;
424 }
425 let _profile = crate::profile::scope(crate::profile::Lane::Animation, || format!("{} animações", self.animations.len()));
426 let now = self.time;
427 let mut updates = Vec::with_capacity(self.animations.len());
428 self.animations.retain_mut(|a| {
429 let span = if a.auto_reverse { a.duration * 2.0 } else { a.duration };
430 let mut elapsed = (now - a.start).max(0.0);
431 let finished = !a.looping && elapsed >= span;
432 if a.looping && span > 0.0 {
433 elapsed %= span;
434 }
435 let mut t = if a.duration > 0.0 { (elapsed / a.duration) as f32 } else { 1.0 };
436 if finished {
437 t = if a.auto_reverse { 0.0 } else { 1.0 };
438 } else if a.auto_reverse && t > 1.0 {
439 t = 2.0 - t;
440 }
441 let eased = a.easing.apply(t.min(1.0));
442 let value = if a.keyframes.is_empty() { a.from.lerp(a.to, eased) } else { AnimValue::Float(sample_keyframes(&a.keyframes, eased)) };
443 updates.push((a.target, a.property.clone(), value.to_prop()));
444 !finished
445 });
446 for (id, property, value) in updates {
447 let _ = self.set_prop(id, &property, value);
449 }
450 }
451
452 pub fn start_animation(&mut self, animation: ComponentId) -> Result<()> {
454 self.play_animation(animation, true)
455 }
456
457 pub(crate) fn run_triggers(&mut self, control: ComponentId, trigger: Trigger, active: bool) {
460 let animations: Vec<ComponentId> = self
461 .children(control)
462 .iter()
463 .copied()
464 .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == trigger))
465 .collect();
466 for animation in animations {
467 let _ = self.play_animation(animation, active);
468 }
469 }
470
471 fn play_animation(&mut self, animation: ComponentId, forward: bool) -> Result<()> {
472 let target = self.parent(animation).ok_or(Error::InvalidId)?;
473 let a = self.get::<PropertyAnimation>(animation).ok_or(Error::InvalidId)?.clone();
474 let current = self.get_prop(target, &a.property)?;
475 let original = a.original.clone().unwrap_or_else(|| current.clone());
476 if a.original.is_none() {
477 if let Some(anim) = self.get_mut::<PropertyAnimation>(animation) {
478 anim.original = Some(original.clone());
479 }
480 }
481 let (from, to) = if forward {
482 let from = if a.start_value == PropValue::Null { current } else { a.start_value.clone() };
483 (from, a.stop_value.clone())
484 } else {
485 (current, original)
486 };
487 let options = AnimationOptions {
488 duration_ms: a.duration,
489 delay_ms: if forward { a.delay } else { 0.0 },
490 easing: a.easing,
491 auto_reverse: forward && a.auto_reverse,
492 looping: forward && a.looping,
493 };
494 self.animate_from_to(target, &a.property, from, to, options, Some(animation))?;
495 if forward {
497 if let Some(steps) = parse_keyframes(&a.keyframes) {
498 if let Some(run) = self.animations.iter_mut().find(|r| r.target == target && r.property == a.property) {
499 run.keyframes = std::rc::Rc::from(steps);
500 }
501 }
502 }
503 Ok(())
504 }
505
506 pub(crate) fn check_appear(&mut self) {
509 if self.appear_waiting.is_none() {
510 let waiting: Vec<ComponentId> = self
511 .components()
512 .filter(|&c| self.get::<PropertyAnimation>(c).is_some_and(|a| a.enabled && a.trigger == Trigger::Appear && !a.appeared))
513 .collect();
514 self.appear_waiting = Some(waiting);
515 }
516 let Some(waiting) = self.appear_waiting.clone() else { return };
517 if waiting.is_empty() || self.design_mode {
518 return;
519 }
520 let mut left = Vec::new();
521 for animation in waiting {
522 let Some(target) = self.parent(animation) else { continue };
523 if self.visible_fraction(target) >= 0.15 {
524 if let Some(a) = self.get_mut::<PropertyAnimation>(animation) {
525 a.appeared = true;
526 }
527 let _ = self.play_animation(animation, true);
528 } else {
529 left.push(animation);
530 }
531 }
532 self.appear_waiting = Some(left);
533 }
534
535 fn visible_fraction(&self, id: ComponentId) -> f32 {
538 let root = self.root_of(id);
539 if !self.is_open(root) {
540 return 0.0;
541 }
542 let Some(r) = self.absolute_rect(id) else { return 0.0 };
543 if !self.cb(id).is_some_and(|cb| cb.visible()) {
544 return 0.0;
545 }
546 let area = (r.width * r.height).max(1.0);
547 let (mut x0, mut y0, mut x1, mut y1) = (r.x, r.y, r.right(), r.bottom());
548 let mut current = self.parent(id);
549 while let Some(p) = current {
550 if let Some(c) = self.absolute_rect(p) {
551 (x0, y0, x1, y1) = (x0.max(c.x), y0.max(c.y), x1.min(c.right()), y1.min(c.bottom()));
552 }
553 if !self.cb(p).is_none_or(|cb| cb.visible()) {
554 return 0.0;
555 }
556 current = self.parent(p);
557 }
558 ((x1 - x0).max(0.0) * (y1 - y0).max(0.0)) / area
559 }
560}
561
562#[derive(Clone, Debug, PartialEq)]
570pub struct PropertyAnimation {
571 color: bool,
572 pub property: String,
573 pub start_value: PropValue,
575 pub stop_value: PropValue,
576 pub duration: f32,
578 pub delay: f32,
580 pub easing: Easing,
581 pub trigger: Trigger,
582 pub auto_reverse: bool,
583 pub looping: bool,
584 pub enabled: bool,
585 pub keyframes: String,
588 original: Option<PropValue>,
590 pub(crate) appeared: bool,
592}
593
594impl PropertyAnimation {
595 fn new(color: bool, property: &str, stop_value: PropValue) -> Self {
596 Self {
597 color,
598 property: property.to_string(),
599 start_value: PropValue::Null,
600 stop_value,
601 duration: 200.0,
602 delay: 0.0,
603 easing: Easing::OutQuad,
604 trigger: Trigger::None,
605 auto_reverse: false,
606 looping: false,
607 enabled: true,
608 original: None,
609 keyframes: String::new(),
610 appeared: false,
611 }
612 }
613
614 pub fn float(property: &str, stop_value: f64) -> Self {
616 Self::new(false, property, PropValue::Float(stop_value))
617 }
618
619 pub fn color(property: &str, stop_value: Color) -> Self {
621 Self::new(true, property, PropValue::Color(stop_value))
622 }
623
624 pub fn with_trigger(mut self, trigger: Trigger) -> Self {
625 self.trigger = trigger;
626 self
627 }
628
629 pub fn with_duration(mut self, ms: f32) -> Self {
630 self.duration = ms;
631 self
632 }
633
634 pub fn with_easing(mut self, easing: Easing) -> Self {
635 self.easing = easing;
636 self
637 }
638
639 pub fn with_delay(mut self, ms: f32) -> Self {
640 self.delay = ms;
641 self
642 }
643}
644
645#[derive(Clone, Debug, PartialEq)]
647pub struct FloatAnimation(pub PropertyAnimation);
648
649impl Default for FloatAnimation {
650 fn default() -> Self {
651 Self(PropertyAnimation::float("opacity", 1.0))
652 }
653}
654
655#[derive(Clone, Debug, PartialEq)]
657pub struct ColorAnimation(pub PropertyAnimation);
658
659impl Default for ColorAnimation {
660 fn default() -> Self {
661 Self(PropertyAnimation::color("fill", Color::TRANSPARENT))
662 }
663}
664
665macro_rules! delegate_animation {
666 ($t:ty, $name:literal) => {
667 impl Component for $t {
668 fn class_name(&self) -> &'static str {
669 $name
670 }
671
672 fn inner(&self) -> Option<&dyn Component> {
673 Some(&self.0)
674 }
675
676 fn inner_mut(&mut self) -> Option<&mut dyn Component> {
677 Some(&mut self.0)
678 }
679 }
680 };
681}
682
683delegate_animation!(FloatAnimation, "FloatAnimation");
684delegate_animation!(ColorAnimation, "ColorAnimation");
685
686const FLOAT_PROPS: &[PropInfo] = &[
687 PropInfo::new("property", PropKind::String, "Animation"),
688 PropInfo::new("start_value", PropKind::Float, "Animation"),
689 PropInfo::new("stop_value", PropKind::Float, "Animation"),
690 PropInfo::new("duration", PropKind::Duration, "Animation"),
691 PropInfo::new("delay", PropKind::Duration, "Animation"),
692 PropInfo::new("easing", PropKind::Easing, "Animation"),
693 PropInfo::new("trigger", PropKind::Enum(Trigger::NAMES), "Animation"),
694 PropInfo::new("auto_reverse", PropKind::Bool, "Animation"),
695 PropInfo::new("looping", PropKind::Bool, "Animation"),
696 PropInfo::new("enabled", PropKind::Bool, "Animation"),
697 PropInfo::new("keyframes", PropKind::String, "Animation"),
698];
699
700const COLOR_PROPS: &[PropInfo] = &[
701 PropInfo::new("property", PropKind::String, "Animation"),
702 PropInfo::new("start_value", PropKind::Color, "Animation"),
703 PropInfo::new("stop_value", PropKind::Color, "Animation"),
704 PropInfo::new("duration", PropKind::Duration, "Animation"),
705 PropInfo::new("delay", PropKind::Duration, "Animation"),
706 PropInfo::new("easing", PropKind::Easing, "Animation"),
707 PropInfo::new("trigger", PropKind::Enum(Trigger::NAMES), "Animation"),
708 PropInfo::new("auto_reverse", PropKind::Bool, "Animation"),
709 PropInfo::new("looping", PropKind::Bool, "Animation"),
710 PropInfo::new("enabled", PropKind::Bool, "Animation"),
711];
712
713impl Component for PropertyAnimation {
714 fn class_name(&self) -> &'static str {
715 if self.color { "ColorAnimation" } else { "FloatAnimation" }
716 }
717
718 fn props(&self) -> &'static [PropInfo] {
719 if self.color { COLOR_PROPS } else { FLOAT_PROPS }
720 }
721
722 fn get_prop(&self, name: &str) -> Option<PropValue> {
723 Some(match name {
724 "property" => self.property.clone().into(),
725 "start_value" => self.start_value.clone(),
726 "stop_value" => self.stop_value.clone(),
727 "duration" => self.duration.into(),
728 "delay" => self.delay.into(),
729 "easing" => self.easing.to_value(),
730 "trigger" => PropValue::enum_value(self.trigger),
731 "auto_reverse" => self.auto_reverse.into(),
732 "looping" => self.looping.into(),
733 "enabled" => self.enabled.into(),
734 "keyframes" => self.keyframes.clone().into(),
735 _ => return None,
736 })
737 }
738
739 fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
740 let value_of = |v: PropValue, color: bool| -> Result<PropValue> {
741 Ok(match v {
742 PropValue::Null => PropValue::Null,
743 v if color => PropValue::Color(v.to_color()?),
744 v => PropValue::Float(v.to_f64()?),
745 })
746 };
747 match name {
748 "property" => {
749 self.property = value.to_str()?.to_string();
750 self.original = None;
751 }
752 "start_value" => self.start_value = value_of(value, self.color)?,
753 "stop_value" => self.stop_value = value_of(value, self.color)?,
754 "duration" => self.duration = value.to_f32()?.max(0.0),
755 "delay" => self.delay = value.to_f32()?.max(0.0),
756 "easing" => self.easing = Easing::from_value(value)?,
757 "trigger" => self.trigger = value.to_enum()?,
758 "auto_reverse" => self.auto_reverse = value.to_bool()?,
759 "looping" => self.looping = value.to_bool()?,
760 "enabled" => self.enabled = value.to_bool()?,
761 "keyframes" => {
762 let text = value.to_str()?.to_string();
763 if !text.trim().is_empty() && parse_keyframes(&text).is_none() {
764 return Err(Error::invalid("use fração:valor separados por ; (0:0; 0.6:1.15; 1:1)"));
765 }
766 self.keyframes = text;
767 }
768 _ => return Err(Error::UnknownProperty(name.to_string())),
769 }
770 Ok(())
771 }
772}