Skip to main content

euv_ui/hook/form/
impl.rs

1use super::*;
2
3/// Implements [`HookContextFormExt`] for [`HookContext`].
4impl HookContextFormExt for HookContext {
5    /// Returns a fresh [`FormState`] bound to the current component scope.
6    ///
7    /// # Returns
8    ///
9    /// - `FormState` - A `FormState` value.
10    fn form() -> FormState {
11        HookContext::use_hook(|| {
12            FormState::new(
13                Signal::create(HashMap::new()),
14                Signal::create(HashMap::new()),
15                Signal::create(HashSet::new()),
16                Signal::create(false),
17            )
18        })
19    }
20}
21
22/// Inherent implementation of [`FormState`].
23impl FormState {
24    /// Returns the current value of the named field, or
25    /// `""` if the field has never been set.
26    ///
27    /// This is a snapshot read, not a subscription —
28    /// callers inside a render closure that want to
29    /// re-render on value changes should use
30    /// `state.get_values().get().get(name).cloned().unwrap_or_default()`
31    /// instead, so the closure actually subscribes.
32    ///
33    /// # Arguments
34    ///
35    /// - `&'static str` - Shared reference to a `'static str`.
36    ///
37    /// # Returns
38    ///
39    /// - `String` - A `String` value.
40    pub fn field(&self, name: &'static str) -> String {
41        self.get_values()
42            .get()
43            .get(name)
44            .cloned()
45            .unwrap_or_default()
46    }
47
48    /// Returns the current error for the named field, or
49    /// `""` if the field has no error.
50    ///
51    /// Snapshot read — see `field` for the subscription
52    /// caveat.
53    ///
54    /// # Arguments
55    ///
56    /// - `&'static str` - Shared reference to a `'static str`.
57    ///
58    /// # Returns
59    ///
60    /// - `String` - A `String` value.
61    pub fn error(&self, name: &'static str) -> String {
62        self.get_errors()
63            .get()
64            .get(name)
65            .cloned()
66            .unwrap_or_default()
67    }
68
69    /// Returns `true` if the user has interacted with the
70    /// named field.
71    ///
72    /// # Arguments
73    ///
74    /// - `&'static str` - Field name.
75    ///
76    /// # Returns
77    ///
78    /// - `bool` - `true` when the field has been touched.
79    pub fn is_touched(&self, name: &'static str) -> bool {
80        self.get_touched().get().contains(name)
81    }
82
83    /// Sets the value of the named field.
84    ///
85    /// Marks the field as touched (mirroring the
86    /// `oninput` event that triggered the call) and
87    /// clears any prior error for the field. The error
88    /// clear is a UX choice — the next `validate` call
89    /// will repopulate it if the new value is still
90    /// invalid.
91    ///
92    /// # Arguments
93    ///
94    /// - `&'static str` - Shared reference to a `'static str`.
95    /// - `&str` - Shared reference to a `'static str`.
96    pub fn set_field(&self, name: &'static str, value: &str) {
97        let mut current: HashMap<&'static str, String> = self.get_values().get();
98        current.insert(name, value.to_string());
99        self.get_values().set(current);
100        let mut touched: HashSet<&'static str> = self.get_touched().get();
101        touched.insert(name);
102        self.get_touched().set(touched);
103        let mut errors: HashMap<&'static str, String> = self.get_errors().get();
104        errors.remove(name);
105        self.get_errors().set(errors);
106    }
107
108    /// Marks the named field as touched without changing
109    /// its value. Used by `onblur` handlers — "the user
110    /// left this field, so it counts as interacted".
111    ///
112    /// # Arguments
113    ///
114    /// - `&'static str` - Shared reference to a `'static str`.
115    pub fn touch(&self, name: &'static str) {
116        let mut touched: HashSet<&'static str> = self.get_touched().get();
117        touched.insert(name);
118        self.get_touched().set(touched);
119    }
120
121    /// Runs every validator in `validators` and updates the
122    /// `errors` signal.
123    ///
124    /// Returns `true` if every field validated
125    /// successfully (i.e. every validator returned
126    /// `None`), `false` otherwise. The errors signal is
127    /// always updated, regardless of return value —
128    /// callers should call `validate` and then branch on
129    /// the boolean.
130    ///
131    /// Fields with no validator are silently skipped —
132    /// they cannot produce an error.
133    ///
134    /// # Arguments
135    ///
136    /// - `&HashMap<&'static str, Validator>` - Per-field validator map. Each
137    ///   validator is a closure that takes the current value and returns
138    ///   `Some(error_message)` or `None`.
139    ///
140    /// # Returns
141    ///
142    /// - `bool` - A boolean.
143    pub fn validate(&self, validators: &HashMap<&'static str, Validator>) -> bool {
144        let values: HashMap<&'static str, String> = self.get_values().get();
145        let mut next_errors: HashMap<&'static str, String> = HashMap::new();
146        let mut all_valid: bool = true;
147        for (name, validator) in validators.iter() {
148            let current_value: &str = values.get(name).map(String::as_str).unwrap_or("");
149            if let Some(error_message) = validator(current_value) {
150                if !error_message.is_empty() {
151                    all_valid = false;
152                }
153                next_errors.insert(name, error_message);
154            }
155        }
156        self.get_errors().set(next_errors);
157        all_valid
158    }
159
160    /// Runs the user-supplied submit handler if all
161    /// validators pass.
162    ///
163    /// Sets `submitting` to `true` for the duration of the
164    /// call (so a `disabled={state.get_submitting().get()}`
165    /// button stays disabled until the handler returns),
166    /// then resets it to `false`. If validators were
167    /// supplied AND at least one field failed validation,
168    /// the submit handler is NOT invoked and `submitting`
169    /// is left `false`.
170    ///
171    /// Returns `true` if the handler was invoked,
172    /// `false` if validation failed and the handler was
173    /// skipped.
174    ///
175    /// # Arguments
176    ///
177    /// - `&HashMap<&'static str, Validator>` - Validators to run before
178    ///   invoking the handler. Pass an empty map to skip validation entirely
179    ///   (the handler always runs).
180    /// - `F` - The submit handler. Receives the current values map by
181    ///   reference — clone what you need to keep past the call.
182    ///
183    /// # Returns
184    ///
185    /// - `bool` - A boolean.
186    pub fn submit<F>(&self, validators: &HashMap<&'static str, Validator>, on_submit: F) -> bool
187    where
188        F: FnOnce(&HashMap<&'static str, String>),
189    {
190        let all_valid: bool = if validators.is_empty() {
191            true
192        } else {
193            self.validate(validators)
194        };
195        if !all_valid {
196            return false;
197        }
198        self.get_submitting().set(true);
199        let snapshot: HashMap<&'static str, String> = self.get_values().get();
200        on_submit(&snapshot);
201        self.get_submitting().set(false);
202        true
203    }
204
205    /// Clears values, errors, and touched state. Leaves
206    /// `submitting` untouched (it should already be
207    /// `false`).
208    ///
209    /// Useful for "form submitted successfully, reset for
210    /// the next entry" UX flows.
211    pub fn reset(&self) {
212        self.get_values().set(HashMap::new());
213        self.get_errors().set(HashMap::new());
214        self.get_touched().set(HashSet::new());
215    }
216
217    /// Returns the number of fields that currently have
218    /// a non-empty error. Useful for "submit button stays
219    /// disabled until form is valid" without re-running
220    /// validation.
221    ///
222    /// # Returns
223    ///
224    /// - `usize` - Count of currently-registered errors.
225    pub fn error_count(&self) -> usize {
226        self.get_errors()
227            .get()
228            .values()
229            .filter(|message: &&String| !message.is_empty())
230            .count()
231    }
232}