Skip to main content

patternfly_yew/
validation.rs

1//! Validation
2
3#[derive(Clone, Debug)]
4pub struct ValidationContext<T> {
5    pub value: T,
6    pub initial: bool,
7}
8
9impl<T> From<T> for ValidationContext<T> {
10    fn from(value: T) -> Self {
11        ValidationContext {
12            value,
13            initial: false,
14        }
15    }
16}
17
18#[derive(Clone, Default)]
19pub enum Validator<T, S> {
20    #[default]
21    None,
22    Custom(std::rc::Rc<dyn Fn(ValidationContext<T>) -> S>),
23}
24
25impl<T, S> Validator<T, S> {
26    pub fn is_custom(&self) -> bool {
27        matches!(self, Self::Custom(_))
28    }
29
30    /// Convert into the context and run
31    pub fn run<C>(&self, ctx: C) -> Option<S>
32    where
33        C: Into<ValidationContext<T>>,
34    {
35        self.run_if(|| ctx.into())
36    }
37
38    /// Only convert when necessary, and run.
39    pub fn run_if<F>(&self, f: F) -> Option<S>
40    where
41        F: FnOnce() -> ValidationContext<T>,
42    {
43        match self {
44            Self::Custom(validator) => Some(validator(f())),
45            _ => None,
46        }
47    }
48
49    /// Run with the provided context.
50    pub fn run_ctx(&self, ctx: ValidationContext<T>) -> Option<S> {
51        match self {
52            Self::Custom(validator) => Some(validator(ctx)),
53            _ => None,
54        }
55    }
56}
57
58/// Validators are equal if they are still None. Everything else is a change.
59impl<T, S> PartialEq for Validator<T, S> {
60    fn eq(&self, other: &Self) -> bool {
61        matches!((self, other), (Validator::None, Validator::None))
62    }
63}
64
65impl<F, T, S> From<F> for Validator<T, S>
66where
67    F: Fn(ValidationContext<T>) -> S + 'static,
68{
69    fn from(v: F) -> Self {
70        Self::Custom(std::rc::Rc::new(v))
71    }
72}
73
74pub trait IntoValidator<T, S> {
75    fn into_validator(self) -> Validator<T, S>;
76}
77
78impl<F, T, S> IntoValidator<T, S> for F
79where
80    F: Fn(ValidationContext<T>) -> S + 'static,
81{
82    fn into_validator(self) -> Validator<T, S> {
83        Validator::Custom(std::rc::Rc::new(self))
84    }
85}