1use std::{
2 fmt::Display,
3 marker::PhantomData,
4 str::FromStr,
5};
6
7use tui_textarea::{Input, TextArea};
8
9pub struct Filtext<T: Default + Display + FromStr> {
10 pub input: TextArea<'static>,
11 pub validate_input: bool,
12 _phantom: PhantomData<T>,
13}
14
15impl<T: Default + Display + FromStr> Filtext<T> {
16 pub fn new() -> Self {
17 let input = T::default().to_string();
18 Self {
19 input: TextArea::from([input]),
20 validate_input: false,
21 _phantom: PhantomData,
22 }
23 }
24
25 pub fn input(&mut self, input: Input) -> bool {
26 if self.validate_input {
27 let prev = self.input.lines().to_vec();
28 let val = self.input.input(input);
29 let new = self.value_string();
30 if new.parse::<T>().is_err() && !prev.is_empty() {
31 self.input = TextArea::new(prev);
32 false
33 } else {
34 val
35 }
36 } else {
37 self.input.input(input)
38 }
39 }
40
41 pub fn value(&self) -> Option<T> {
42 T::from_str(&self.value_string()).ok()
43 }
44
45 pub fn value_string(&self) -> String {
46 self.input.lines().concat()
47 }
48}