1use std::borrow::ToOwned;
2
3use crate::{Event, Input};
4
5pub trait TextEvent: Sized {
7 fn from_text(text: &str, old_event: &Self) -> Option<Self>;
11 fn text<U, F>(&self, f: F) -> Option<U>
13 where
14 F: FnMut(&str) -> U;
15 fn text_args(&self) -> Option<String> {
17 self.text(|text| text.to_owned())
18 }
19}
20
21impl TextEvent for Event {
22 fn from_text(text: &str, old_event: &Self) -> Option<Self> {
23 let timestamp = if let Event::Input(_, x) = old_event {
24 *x
25 } else {
26 None
27 };
28 Some(Event::Input(Input::Text(text.into()), timestamp))
29 }
30
31 fn text<U, F>(&self, mut f: F) -> Option<U>
32 where
33 F: FnMut(&str) -> U,
34 {
35 match *self {
36 Event::Input(Input::Text(ref s), _) => Some(f(s)),
37 _ => None,
38 }
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 #[test]
47 fn test_input_text() {
48 use super::super::Input;
49
50 let e: Event = Input::Text("".to_string()).into();
51 let x: Option<Event> = TextEvent::from_text("hello", &e);
52 let y: Option<Event> = x
53 .clone()
54 .unwrap()
55 .text(|text| TextEvent::from_text(text, x.as_ref().unwrap()))
56 .unwrap();
57 assert_eq!(x, y);
58 }
59}