patternfly_yew/
validation.rs1#[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)]
19pub enum Validator<T, S> {
20 None,
21 Custom(std::rc::Rc<dyn Fn(ValidationContext<T>) -> S>),
22}
23
24impl<T, S> Validator<T, S> {
25 pub fn is_custom(&self) -> bool {
26 matches!(self, Self::Custom(_))
27 }
28
29 pub fn run<C>(&self, ctx: C) -> Option<S>
31 where
32 C: Into<ValidationContext<T>>,
33 {
34 self.run_if(|| ctx.into())
35 }
36
37 pub fn run_if<F>(&self, f: F) -> Option<S>
39 where
40 F: FnOnce() -> ValidationContext<T>,
41 {
42 match self {
43 Self::Custom(validator) => Some(validator(f())),
44 _ => None,
45 }
46 }
47
48 pub fn run_ctx(&self, ctx: ValidationContext<T>) -> Option<S> {
50 match self {
51 Self::Custom(validator) => Some(validator(ctx)),
52 _ => None,
53 }
54 }
55}
56
57impl<T, S> Default for Validator<T, S> {
58 fn default() -> Self {
59 Self::None
60 }
61}
62
63impl<T, S> PartialEq for Validator<T, S> {
65 fn eq(&self, other: &Self) -> bool {
66 matches!((self, other), (Validator::None, Validator::None))
67 }
68}
69
70impl<F, T, S> From<F> for Validator<T, S>
71where
72 F: Fn(ValidationContext<T>) -> S + 'static,
73{
74 fn from(v: F) -> Self {
75 Self::Custom(std::rc::Rc::new(v))
76 }
77}
78
79pub trait IntoValidator<T, S> {
80 fn into_validator(self) -> Validator<T, S>;
81}
82
83impl<F, T, S> IntoValidator<T, S> for F
84where
85 F: Fn(ValidationContext<T>) -> S + 'static,
86{
87 fn into_validator(self) -> Validator<T, S> {
88 Validator::Custom(std::rc::Rc::new(self))
89 }
90}