leptos_controls_core/
signal.rs

1use crate::field::Field;
2use crate::meta::FieldMeta;
3use leptos::*;
4use std::borrow::Cow;
5use std::marker::PhantomData;
6
7pub struct SignalField<M, T>
8where
9    M: FieldMeta<Type = T>,
10    T: Clone + 'static,
11{
12    pub(crate) value: Signal<T>,
13    _mark: PhantomData<M>,
14}
15
16impl<M, T> SignalField<M, T>
17where
18    M: FieldMeta<Type = T>,
19    T: Clone + 'static,
20{
21    pub fn new(value: T) -> Self {
22        Self {
23            value: Signal::derive(move || value.clone()),
24            _mark: PhantomData,
25        }
26    }
27}
28
29impl<M, T> Field for SignalField<M, T>
30where
31    T: Clone + 'static,
32    M: FieldMeta<Type = T>,
33{
34    fn label(&self) -> &'static str {
35        M::LABEL
36    }
37
38    fn required(&self) -> bool {
39        M::REQUIRED
40    }
41
42    fn validate(&self) -> Option<Cow<'static, str>> {
43        M::VALIDATE(&self.get_untracked())
44    }
45
46    fn set_default(&self) {}
47}
48
49impl<M, T> Clone for SignalField<M, T>
50where
51    T: Clone + 'static,
52    M: FieldMeta<Type = T>,
53{
54    fn clone(&self) -> Self {
55        *self
56    }
57}
58
59impl<M, T> Copy for SignalField<M, T>
60where
61    T: Clone + 'static,
62    M: FieldMeta<Type = T>,
63{
64}
65
66impl<M, T> SignalWithUntracked for SignalField<M, T>
67where
68    T: Clone + 'static,
69    M: FieldMeta<Type = T>,
70{
71    type Value = T;
72
73    fn with_untracked<O>(&self, f: impl FnOnce(&Self::Value) -> O) -> O {
74        self.value.with_untracked(f)
75    }
76
77    fn try_with_untracked<O>(&self, f: impl FnOnce(&Self::Value) -> O) -> Option<O> {
78        self.value.try_with_untracked(f)
79    }
80}
81impl<M, T> SignalWith for SignalField<M, T>
82where
83    T: Clone + 'static,
84    M: FieldMeta<Type = T>,
85{
86    type Value = T;
87
88    fn with<O>(&self, f: impl FnOnce(&Self::Value) -> O) -> O {
89        self.value.with(f)
90    }
91
92    fn try_with<O>(&self, f: impl FnOnce(&Self::Value) -> O) -> Option<O> {
93        self.value.try_with(f)
94    }
95}
96
97impl<M, T> SignalGetUntracked for SignalField<M, T>
98where
99    T: Clone + 'static,
100    M: FieldMeta<Type = T>,
101{
102    type Value = T;
103
104    fn get_untracked(&self) -> Self::Value {
105        self.value.get_untracked()
106    }
107
108    fn try_get_untracked(&self) -> Option<Self::Value> {
109        self.value.try_get_untracked()
110    }
111}
112
113impl<M, T> SignalGet for SignalField<M, T>
114where
115    T: Clone + 'static,
116    M: FieldMeta<Type = T>,
117{
118    type Value = T;
119
120    fn get(&self) -> Self::Value {
121        self.value.get()
122    }
123
124    fn try_get(&self) -> Option<Self::Value> {
125        self.value.try_get()
126    }
127}