fc_ui/capabilities/controls/
validation.rs1use gpui::{prelude::FluentBuilder as _, *};
8use std::sync::Arc;
9
10use crate::capabilities::foundation::theme::ThemeTokens;
11use crate::capabilities::layout::HStack;
12
13pub type ValidationCallback = Arc<dyn Fn(&str) -> Result<(), ValidationError>>;
14pub type TextTransformer = Arc<dyn Fn(&str) -> String>;
15
16#[derive(Debug, Clone)]
18pub struct ValidationError {
19 pub message: SharedString,
20 pub field_name: Option<SharedString>,
21}
22
23#[derive(Clone, Default)]
25pub struct ValidationRules {
26 pub min_length: Option<usize>,
28 pub max_length: Option<usize>,
30 pub min_value: Option<f64>,
32 pub max_value: Option<f64>,
34 pub pattern: Option<String>,
36 pub custom_validator: Option<ValidationCallback>,
38 pub custom_filter: Option<TextTransformer>,
40 pub custom_formatter: Option<TextTransformer>,
42 pub required: bool,
44}
45
46impl std::fmt::Debug for ValidationRules {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 f.debug_struct("ValidationRules")
49 .field("min_length", &self.min_length)
50 .field("max_length", &self.max_length)
51 .field("min_value", &self.min_value)
52 .field("max_value", &self.max_value)
53 .field("pattern", &self.pattern)
54 .field("custom_validator", &self.custom_validator.is_some())
55 .field("custom_filter", &self.custom_filter.is_some())
56 .field("custom_formatter", &self.custom_formatter.is_some())
57 .field("required", &self.required)
58 .finish()
59 }
60}
61
62pub(crate) fn check_required_empty(
69 required: bool,
70 value: &str,
71 field_name: Option<SharedString>,
72) -> Option<Result<(), ValidationError>> {
73 if required && value.trim().is_empty() {
74 return Some(Err(ValidationError {
75 message: "This field is required".into(),
76 field_name,
77 }));
78 }
79 if !required && value.trim().is_empty() {
80 return Some(Ok(()));
81 }
82 None
83}
84
85pub(crate) fn check_constraints(
89 rules: &ValidationRules,
90 value: &str,
91 field_name: Option<SharedString>,
92) -> Result<(), ValidationError> {
93 if let Some(min_length) = rules.min_length {
94 if value.chars().count() < min_length {
95 return Err(ValidationError {
96 message: format!("Must be at least {} characters", min_length).into(),
97 field_name,
98 });
99 }
100 }
101
102 if let Some(max_length) = rules.max_length {
103 if value.chars().count() > max_length {
104 return Err(ValidationError {
105 message: format!("Must be no more than {} characters", max_length).into(),
106 field_name,
107 });
108 }
109 }
110
111 if let Some(pattern) = rules.pattern.as_deref() {
112 match regex::Regex::new(pattern) {
113 Ok(regex) if !regex.is_match(value) => {
114 return Err(ValidationError {
115 message: "Value does not match the required pattern".into(),
116 field_name,
117 });
118 }
119 Err(_) => {
120 return Err(ValidationError {
121 message: "Invalid validation pattern".into(),
122 field_name,
123 });
124 }
125 Ok(_) => {}
126 }
127 }
128
129 if let Some(ref validator) = rules.custom_validator {
130 validator(value)?;
131 }
132
133 Ok(())
134}
135
136pub(crate) struct CharacterCount {
138 pub committed: usize,
140 pub composing: usize,
142 pub max: Option<usize>,
144}
145
146pub(crate) fn format_character_count(
154 committed: usize,
155 composing: usize,
156 max: Option<usize>,
157) -> (String, bool) {
158 let mut text = committed.to_string();
159 if composing > 0 {
160 text.push('+');
161 text.push_str(&composing.to_string());
162 }
163 if let Some(max) = max {
164 text.push('/');
165 text.push_str(&max.to_string());
166 }
167 let over = max.is_some_and(|max| committed >= max || committed + composing > max);
168 (text, over)
169}
170
171pub(crate) enum FooterMessage<'a> {
174 Error(&'a ValidationError),
175 Success(&'a SharedString),
176 Helper(&'a SharedString),
177 Blank,
179}
180
181pub(crate) fn validation_footer(
188 tokens: &ThemeTokens,
189 message: FooterMessage,
190 character_count: Option<CharacterCount>,
191) -> impl IntoElement {
192 let message_element = match message {
193 FooterMessage::Error(error) => div()
194 .text_color(tokens.destructive)
195 .child(error.message.clone()),
196 FooterMessage::Success(success) => div().text_color(tokens.primary).child(success.clone()),
197 FooterMessage::Helper(helper) => div()
198 .text_color(tokens.muted_foreground)
199 .child(helper.clone()),
200 FooterMessage::Blank => div(),
201 };
202
203 HStack::new()
204 .w_full()
205 .px(px(2.0))
206 .child(
207 div()
208 .flex_1()
209 .text_size(tokens.text_xs)
210 .font_family(tokens.font_family.clone())
211 .child(message_element),
212 )
213 .when_some(character_count, |h, count| {
214 let (text, over) = format_character_count(count.committed, count.composing, count.max);
215 h.child(
216 div()
217 .text_size(tokens.text_xs)
218 .font_family(tokens.font_family.clone())
219 .text_color(if over {
220 tokens.destructive
221 } else {
222 tokens.muted_foreground
223 })
224 .child(text),
225 )
226 })
227}
228
229#[cfg(test)]
230mod tests {
231 use super::{
234 check_constraints, check_required_empty, format_character_count, CharacterCount,
235 ValidationError, ValidationRules,
236 };
237 use std::sync::Arc;
238
239 #[test]
240 fn required_empty_fails() {
241 let result = check_required_empty(true, " ", None);
242 assert!(matches!(result, Some(Err(_))));
243 }
244
245 #[test]
246 fn optional_empty_passes_without_constraint_checks() {
247 let rules = ValidationRules {
248 min_length: Some(3),
249 ..Default::default()
250 };
251 assert!(matches!(
252 check_required_empty(false, "", None),
253 Some(Ok(()))
254 ));
255 assert!(check_required_empty(rules.required, "", None).is_some());
257 }
258
259 #[test]
260 fn constraints_enforce_lengths() {
261 let rules = ValidationRules {
262 min_length: Some(2),
263 max_length: Some(4),
264 ..Default::default()
265 };
266 assert!(check_constraints(&rules, "a", None).is_err());
267 assert!(check_constraints(&rules, "abcde", None).is_err());
268 assert!(check_constraints(&rules, "abc", None).is_ok());
269 }
270
271 #[test]
272 fn constraints_count_chars_not_bytes() {
273 let rules = ValidationRules {
274 max_length: Some(2),
275 ..Default::default()
276 };
277 assert!(check_constraints(&rules, "你好", None).is_ok());
278 assert!(check_constraints(&rules, "你好呀", None).is_err());
279 }
280
281 #[test]
282 fn constraints_apply_pattern_and_custom_validator() {
283 let rules = ValidationRules {
284 pattern: Some(r"^\d+$".to_string()),
285 ..Default::default()
286 };
287 assert!(check_constraints(&rules, "123", None).is_ok());
288 assert!(check_constraints(&rules, "12a", None).is_err());
289
290 let rules = ValidationRules {
291 custom_validator: Some(Arc::new(|value| {
292 if value.contains('x') {
293 Ok(())
294 } else {
295 Err(ValidationError {
296 message: "needs x".into(),
297 field_name: None,
298 })
299 }
300 })),
301 ..Default::default()
302 };
303 assert!(check_constraints(&rules, "oxo", None).is_ok());
304 assert!(check_constraints(&rules, "ooo", None).is_err());
305 }
306
307 #[test]
308 fn character_count_formats_plain_and_max() {
309 assert_eq!(
310 format_character_count(12, 0, None),
311 ("12".to_string(), false)
312 );
313 assert_eq!(
314 format_character_count(12, 0, Some(140)),
315 ("12/140".to_string(), false)
316 );
317 }
318
319 #[test]
320 fn character_count_shows_composition_separately() {
321 assert_eq!(
322 format_character_count(12, 3, Some(140)),
323 ("12+3/140".to_string(), false)
324 );
325 }
326
327 #[test]
328 fn character_count_flags_full_and_impending_overflow() {
329 assert_eq!(
331 format_character_count(140, 0, Some(140)),
332 ("140/140".to_string(), true)
333 );
334 assert_eq!(
336 format_character_count(138, 5, Some(140)),
337 ("138+5/140".to_string(), true)
338 );
339 assert_eq!(
341 format_character_count(138, 2, Some(140)),
342 ("138+2/140".to_string(), false)
343 );
344 assert_eq!(
346 format_character_count(10, 50, None),
347 ("10+50".to_string(), false)
348 );
349 }
350
351 #[test]
352 fn character_count_struct_is_what_footer_consumes() {
353 let count = CharacterCount {
354 committed: 3,
355 composing: 2,
356 max: Some(4),
357 };
358 let (_, over) = format_character_count(count.committed, count.composing, count.max);
359 assert!(over);
360 }
361}