Skip to main content

aylis_core/
event_value.rs

1//! O argumento tipado dos eventos: cada componente declara o que o evento leva
2//! (`events: on_change: f64` no [`crate::properties!`]), o catálogo do acesso tipado escreve o
3//! handler com esse tipo nas 8 linguagens, e em Rust o [`EventValue`] tira o valor do
4//! [`EventArgs`] (o handler recebe `value: f64`, não o `args` para decifrar).
5
6use crate::component::ComponentId;
7use crate::event::{EventArgs, GestureEvent, KeyEvent, PointerEvent, SwipeEvent, WheelEvent};
8use crate::prop::{PropEnum, PropKind, PropValue};
9use crate::ui::Ui;
10use crate::{Color, Date, DateTime, Time};
11
12/// O que um evento leva no `args`.
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub enum EventArg {
15    /// Ainda não declarado: o handler recebe o evento inteiro, como antes.
16    Unknown,
17    /// Nada (o clique, o foco): o handler recebe só quem disparou.
18    None,
19    Pointer,
20    Wheel,
21    Gesture,
22    Swipe,
23    Key,
24    /// O intervalo de datas (`início;fim`) do `Calendar` com `range`.
25    DateRange,
26    /// Um valor do tipo dado (o `PropKind::String` é o texto).
27    Value(PropKind),
28}
29
30/// Um tipo que um handler recebe como o argumento do evento.
31pub trait EventValue: Sized + 'static {
32    /// O que o evento declara no catálogo.
33    const ARG: EventArg;
34    /// O valor tirado do `args` (`None`: o evento veio com outra coisa).
35    fn from_args(args: &EventArgs) -> Option<Self>;
36}
37
38/// O texto do `args`, venha como `Text` ou como valor texto (ou enum).
39fn text_of(args: &EventArgs) -> Option<&str> {
40    match args {
41        EventArgs::Text(t) => Some(t),
42        EventArgs::Value(PropValue::String(t) | PropValue::Enum(t)) => Some(t),
43        _ => None,
44    }
45}
46
47impl EventValue for () {
48    const ARG: EventArg = EventArg::None;
49    fn from_args(_args: &EventArgs) -> Option<Self> {
50        Some(())
51    }
52}
53
54impl EventValue for bool {
55    const ARG: EventArg = EventArg::Value(PropKind::Bool);
56    fn from_args(args: &EventArgs) -> Option<Self> {
57        match args {
58            EventArgs::Value(v) => v.to_bool().ok(),
59            _ => None,
60        }
61    }
62}
63
64impl EventValue for i64 {
65    const ARG: EventArg = EventArg::Value(PropKind::Int);
66    fn from_args(args: &EventArgs) -> Option<Self> {
67        match args {
68            EventArgs::Value(v) => v.to_i64().ok(),
69            EventArgs::Text(t) => t.trim().parse().ok(),
70            _ => None,
71        }
72    }
73}
74
75impl EventValue for f64 {
76    const ARG: EventArg = EventArg::Value(PropKind::Float);
77    fn from_args(args: &EventArgs) -> Option<Self> {
78        match args {
79            EventArgs::Value(v) => v.to_f64().ok(),
80            EventArgs::Text(t) => t.trim().parse().ok(),
81            _ => None,
82        }
83    }
84}
85
86impl EventValue for String {
87    const ARG: EventArg = EventArg::Value(PropKind::String);
88    fn from_args(args: &EventArgs) -> Option<Self> {
89        text_of(args).map(str::to_string)
90    }
91}
92
93impl EventValue for Color {
94    const ARG: EventArg = EventArg::Value(PropKind::Color);
95    fn from_args(args: &EventArgs) -> Option<Self> {
96        match args {
97            EventArgs::Value(PropValue::Color(c)) => Some(*c),
98            _ => text_of(args).and_then(Color::from_hex),
99        }
100    }
101}
102
103impl EventValue for Option<Date> {
104    const ARG: EventArg = EventArg::Value(PropKind::Date);
105    fn from_args(args: &EventArgs) -> Option<Self> {
106        text_of(args).map(Date::parse_iso)
107    }
108}
109
110impl EventValue for Option<Time> {
111    const ARG: EventArg = EventArg::Value(PropKind::Time);
112    fn from_args(args: &EventArgs) -> Option<Self> {
113        text_of(args).map(Time::parse_iso)
114    }
115}
116
117impl EventValue for Option<DateTime> {
118    const ARG: EventArg = EventArg::Value(PropKind::DateTime);
119    fn from_args(args: &EventArgs) -> Option<Self> {
120        text_of(args).map(DateTime::parse_iso)
121    }
122}
123
124impl EventValue for Option<crate::Shadow> {
125    const ARG: EventArg = EventArg::Value(PropKind::Shadow);
126    fn from_args(args: &EventArgs) -> Option<Self> {
127        Some(text_of(args).and_then(crate::Shadow::parse))
128    }
129}
130
131impl EventValue for crate::Easing {
132    const ARG: EventArg = EventArg::Value(PropKind::Easing);
133    fn from_args(args: &EventArgs) -> Option<Self> {
134        Some(text_of(args).and_then(crate::Easing::parse).unwrap_or_default())
135    }
136}
137
138impl EventValue for Vec<String> {
139    const ARG: EventArg = EventArg::Value(PropKind::List);
140    fn from_args(args: &EventArgs) -> Option<Self> {
141        text_of(args).map(|t| t.split(';').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).collect())
142    }
143}
144
145impl EventValue for Option<ComponentId> {
146    const ARG: EventArg = EventArg::Value(PropKind::Component);
147    fn from_args(args: &EventArgs) -> Option<Self> {
148        match args {
149            EventArgs::Value(v) => v.to_component().ok(),
150            EventArgs::None => Some(None),
151            _ => None,
152        }
153    }
154}
155
156impl EventValue for PointerEvent {
157    const ARG: EventArg = EventArg::Pointer;
158    fn from_args(args: &EventArgs) -> Option<Self> {
159        match args {
160            EventArgs::Pointer(p) => Some(*p),
161            _ => None,
162        }
163    }
164}
165
166impl EventValue for WheelEvent {
167    const ARG: EventArg = EventArg::Wheel;
168    fn from_args(args: &EventArgs) -> Option<Self> {
169        match args {
170            EventArgs::Wheel(w) => Some(*w),
171            _ => None,
172        }
173    }
174}
175
176impl EventValue for GestureEvent {
177    const ARG: EventArg = EventArg::Gesture;
178    fn from_args(args: &EventArgs) -> Option<Self> {
179        match args {
180            EventArgs::Gesture(g) => Some(*g),
181            _ => None,
182        }
183    }
184}
185
186impl EventValue for SwipeEvent {
187    const ARG: EventArg = EventArg::Swipe;
188    fn from_args(args: &EventArgs) -> Option<Self> {
189        match args {
190            EventArgs::Swipe(s) => Some(*s),
191            _ => None,
192        }
193    }
194}
195
196impl EventValue for KeyEvent {
197    const ARG: EventArg = EventArg::Key;
198    fn from_args(args: &EventArgs) -> Option<Self> {
199        match args {
200            EventArgs::Key(k) => Some(*k),
201            _ => None,
202        }
203    }
204}
205
206impl EventValue for DateRange {
207    const ARG: EventArg = EventArg::DateRange;
208    fn from_args(args: &EventArgs) -> Option<Self> {
209        let text = text_of(args)?;
210        let (start, end) = text.split_once(';').unwrap_or((text, ""));
211        Some(DateRange { start: Date::parse_iso(start), end: Date::parse_iso(end) })
212    }
213}
214
215impl<E: PropEnum> EventValue for E {
216    const ARG: EventArg = EventArg::Value(PropKind::Enum(E::NAMES));
217    fn from_args(args: &EventArgs) -> Option<Self> {
218        text_of(args).and_then(E::from_name)
219    }
220}
221
222/// Um intervalo de datas: o `on_change` do `Calendar` com `range` (o fim é `None` enquanto só
223/// o começo foi escolhido).
224#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
225pub struct DateRange {
226    pub start: Option<Date>,
227    pub end: Option<Date>,
228}
229
230/// Quem disparou o evento, como o handler tipado recebe: o handle do componente com a classe
231/// dele (o que o acesso tipado gera), ou o `ComponentId`.
232pub trait FromSender: Sized {
233    fn from_sender(ui: &Ui, id: ComponentId) -> Option<Self>;
234}
235
236impl FromSender for ComponentId {
237    fn from_sender(_ui: &Ui, id: ComponentId) -> Option<Self> {
238        Some(id)
239    }
240}