revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Form validation utilities
//!
//! Provides composable validators for form inputs.
//!
//! # Example
//!
//! ```rust,ignore
//! use revue::utils::validation::{Validator, required, min_length, email, all_of};
//!
//! // Simple validation
//! let result = required()("hello");
//! assert!(result.is_ok());
//!
//! // Chained validators
//! let email_validator = all_of(&[
//!     required(),
//!     min_length(5),
//!     email(),
//! ]);
//!
//! assert!(email_validator("user@example.com").is_ok());
//! assert!(email_validator("").is_err());
//! ```

use std::fmt;

/// Validation error with message
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ValidationError {
    /// Error message
    pub message: String,
    /// Optional field name
    pub field: Option<String>,
}

impl ValidationError {
    /// Create new validation error
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            field: None,
        }
    }

    /// Create validation error with field name
    pub fn with_field(message: impl Into<String>, field: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            field: Some(field.into()),
        }
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.field {
            Some(field) => write!(f, "{}: {}", field, self.message),
            None => write!(f, "{}", self.message),
        }
    }
}

impl std::error::Error for ValidationError {}

/// Result type for validation
pub type ValidationResult = Result<(), ValidationError>;

/// Validator function type
pub type Validator = Box<dyn Fn(&str) -> ValidationResult + Send + Sync>;

/// Create a required field validator
pub fn required() -> Validator {
    Box::new(|value: &str| {
        if value.trim().is_empty() {
            Err(ValidationError::new("This field is required"))
        } else {
            Ok(())
        }
    })
}

/// Create a minimum length validator
pub fn min_length(min: usize) -> Validator {
    Box::new(move |value: &str| {
        if value.len() < min {
            Err(ValidationError::new(format!(
                "Must be at least {} characters",
                min
            )))
        } else {
            Ok(())
        }
    })
}

/// Create a maximum length validator
pub fn max_length(max: usize) -> Validator {
    Box::new(move |value: &str| {
        if value.len() > max {
            Err(ValidationError::new(format!(
                "Must be at most {} characters",
                max
            )))
        } else {
            Ok(())
        }
    })
}

/// Create a length range validator
pub fn length_range(min: usize, max: usize) -> Validator {
    Box::new(move |value: &str| {
        let len = value.len();
        if len < min || len > max {
            Err(ValidationError::new(format!(
                "Must be between {} and {} characters",
                min, max
            )))
        } else {
            Ok(())
        }
    })
}

/// Create an email validator
pub fn email() -> Validator {
    Box::new(|value: &str| {
        if value.is_empty() {
            return Ok(()); // Use required() for mandatory
        }

        // Simple email validation
        let parts: Vec<&str> = value.split('@').collect();
        if parts.len() != 2 {
            return Err(ValidationError::new("Invalid email format"));
        }

        let (local, domain) = (parts[0], parts[1]);

        if local.is_empty() || domain.is_empty() {
            return Err(ValidationError::new("Invalid email format"));
        }

        if !domain.contains('.') {
            return Err(ValidationError::new("Invalid email domain"));
        }

        Ok(())
    })
}

/// Create a URL validator
pub fn url() -> Validator {
    Box::new(|value: &str| {
        if value.is_empty() {
            return Ok(());
        }

        if !value.starts_with("http://") && !value.starts_with("https://") {
            return Err(ValidationError::new(
                "URL must start with http:// or https://",
            ));
        }

        let rest = value
            .trim_start_matches("https://")
            .trim_start_matches("http://");
        if rest.is_empty() || !rest.contains('.') {
            return Err(ValidationError::new("Invalid URL format"));
        }

        Ok(())
    })
}

/// Create a pattern validator using regex-like matching
pub fn pattern(pattern: &'static str, message: &'static str) -> Validator {
    Box::new(move |value: &str| {
        if value.is_empty() {
            return Ok(());
        }

        // Simple pattern matching (no full regex to avoid dependency)
        let matches = match pattern {
            r"^\d+$" => value.chars().all(|c| c.is_ascii_digit()),
            r"^[a-zA-Z]+$" => value.chars().all(|c| c.is_ascii_alphabetic()),
            r"^[a-zA-Z0-9]+$" => value.chars().all(|c| c.is_ascii_alphanumeric()),
            r"^[a-zA-Z0-9_]+$" => value.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
            r"^[a-zA-Z0-9_-]+$" => value
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
            r"^[a-z]+$" => value.chars().all(|c| c.is_ascii_lowercase()),
            r"^[A-Z]+$" => value.chars().all(|c| c.is_ascii_uppercase()),
            _ => true, // Unknown pattern, pass through
        };

        if matches {
            Ok(())
        } else {
            Err(ValidationError::new(message))
        }
    })
}

/// Create a numeric validator
pub fn numeric() -> Validator {
    pattern(r"^\d+$", "Must be a number")
}

/// Create an alphabetic validator
pub fn alphabetic() -> Validator {
    pattern(r"^[a-zA-Z]+$", "Must contain only letters")
}

/// Create an alphanumeric validator
pub fn alphanumeric() -> Validator {
    pattern(r"^[a-zA-Z0-9]+$", "Must contain only letters and numbers")
}

/// Create a lowercase validator
pub fn lowercase() -> Validator {
    pattern(r"^[a-z]+$", "Must be lowercase")
}

/// Create an uppercase validator
pub fn uppercase() -> Validator {
    pattern(r"^[A-Z]+$", "Must be uppercase")
}

/// Create a minimum value validator for numeric strings
pub fn min_value(min: i64) -> Validator {
    Box::new(move |value: &str| {
        if value.is_empty() {
            return Ok(());
        }

        match value.parse::<i64>() {
            Ok(n) if n >= min => Ok(()),
            Ok(_) => Err(ValidationError::new(format!("Must be at least {}", min))),
            Err(_) => Err(ValidationError::new("Must be a number")),
        }
    })
}

/// Create a maximum value validator for numeric strings
pub fn max_value(max: i64) -> Validator {
    Box::new(move |value: &str| {
        if value.is_empty() {
            return Ok(());
        }

        match value.parse::<i64>() {
            Ok(n) if n <= max => Ok(()),
            Ok(_) => Err(ValidationError::new(format!("Must be at most {}", max))),
            Err(_) => Err(ValidationError::new("Must be a number")),
        }
    })
}

/// Create a value range validator for numeric strings
pub fn value_range(min: i64, max: i64) -> Validator {
    Box::new(move |value: &str| {
        if value.is_empty() {
            return Ok(());
        }

        match value.parse::<i64>() {
            Ok(n) if n >= min && n <= max => Ok(()),
            Ok(_) => Err(ValidationError::new(format!(
                "Must be between {} and {}",
                min, max
            ))),
            Err(_) => Err(ValidationError::new("Must be a number")),
        }
    })
}

/// Create a custom validator with a predicate function
pub fn custom<F>(predicate: F, message: &'static str) -> Validator
where
    F: Fn(&str) -> bool + Send + Sync + 'static,
{
    Box::new(move |value: &str| {
        if predicate(value) {
            Ok(())
        } else {
            Err(ValidationError::new(message))
        }
    })
}

/// Create a validator that passes if any of the validators pass
pub fn any_of(validators: Vec<Validator>) -> Validator {
    Box::new(move |value: &str| {
        for validator in &validators {
            if validator(value).is_ok() {
                return Ok(());
            }
        }
        Err(ValidationError::new("None of the conditions were met"))
    })
}

/// Create a validator that passes if all validators pass
pub fn all_of(validators: Vec<Validator>) -> Validator {
    Box::new(move |value: &str| {
        for validator in &validators {
            validator(value)?;
        }
        Ok(())
    })
}

/// Create a validator that matches one of the allowed values
pub fn one_of(values: &'static [&'static str]) -> Validator {
    Box::new(move |value: &str| {
        if value.is_empty() || values.contains(&value) {
            Ok(())
        } else {
            Err(ValidationError::new(format!(
                "Must be one of: {}",
                values.join(", ")
            )))
        }
    })
}

/// Create a validator that ensures value is not in the list
pub fn not_one_of(values: &'static [&'static str]) -> Validator {
    Box::new(move |value: &str| {
        if values.contains(&value) {
            Err(ValidationError::new("This value is not allowed"))
        } else {
            Ok(())
        }
    })
}

/// Create a validator that ensures value matches another field
pub fn matches(other_value: String, field_name: &'static str) -> Validator {
    Box::new(move |value: &str| {
        if value == other_value {
            Ok(())
        } else {
            Err(ValidationError::new(format!("Must match {}", field_name)))
        }
    })
}

/// Form validation helper
pub struct FormValidator {
    fields: Vec<(String, Vec<Validator>)>,
}

impl FormValidator {
    /// Create new form validator
    pub fn new() -> Self {
        Self { fields: Vec::new() }
    }

    /// Add field with validators
    pub fn field(mut self, name: impl Into<String>, validators: Vec<Validator>) -> Self {
        self.fields.push((name.into(), validators));
        self
    }

    /// Validate all fields
    ///
    /// # Errors
    ///
    /// Returns `Err(Vec<ValidationError>)` with a list of validation errors
    /// if any field fails validation. Each error includes the field name
    /// and a description of what went wrong.
    pub fn validate(&self, values: &[(&str, &str)]) -> Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();

        for (field_name, validators) in &self.fields {
            let value = values
                .iter()
                .find(|(name, _)| name == field_name)
                .map(|(_, v)| *v)
                .unwrap_or("");

            for validator in validators {
                if let Err(mut err) = validator(value) {
                    err.field = Some(field_name.clone());
                    errors.push(err);
                    break; // One error per field
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

impl Default for FormValidator {
    fn default() -> Self {
        Self::new()
    }
}