textual 1.0.0-dev

A reactive TUI framework inspired by the Python Textual library
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use std::sync::Arc;

#[derive(Debug, Clone, Default)]
pub struct ValidationResult {
    pub is_valid: bool,
    pub failure_descriptions: Vec<String>,
}

impl ValidationResult {
    pub fn success() -> Self {
        Self {
            is_valid: true,
            failure_descriptions: Vec::new(),
        }
    }

    pub fn failure(message: impl Into<String>) -> Self {
        Self {
            is_valid: false,
            failure_descriptions: vec![message.into()],
        }
    }
}

pub trait Validator {
    fn validate(&self, value: &str) -> ValidationResult;
}

pub type ValidatorRef = Arc<dyn Validator + Send + Sync>;

pub struct Function {
    predicate: Arc<dyn Fn(&str) -> bool + Send + Sync>,
    message: String,
}

impl Function {
    pub fn new(
        predicate: impl Fn(&str) -> bool + Send + Sync + 'static,
        message: impl Into<String>,
    ) -> Self {
        Self {
            predicate: Arc::new(predicate),
            message: message.into(),
        }
    }
}

impl Validator for Function {
    fn validate(&self, value: &str) -> ValidationResult {
        if (self.predicate)(value) {
            ValidationResult::success()
        } else {
            ValidationResult::failure(self.message.clone())
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Number {
    minimum: Option<f64>,
    maximum: Option<f64>,
}

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

impl Number {
    pub fn new() -> Self {
        Self {
            minimum: None,
            maximum: None,
        }
    }

    pub fn minimum(mut self, value: f64) -> Self {
        self.minimum = Some(value);
        self
    }

    pub fn maximum(mut self, value: f64) -> Self {
        self.maximum = Some(value);
        self
    }
}

impl Validator for Number {
    fn validate(&self, value: &str) -> ValidationResult {
        let value = value.trim();
        if value.is_empty() {
            return ValidationResult::failure("Value is required.");
        }

        let Ok(num) = value.parse::<f64>() else {
            return ValidationResult::failure("Value is not a number.");
        };

        if num.is_nan() || num.is_infinite() {
            return ValidationResult::failure("Value is not a number.");
        }

        if let Some(min) = self.minimum {
            if num < min {
                return ValidationResult::failure(format!("Value must be >= {min}."));
            }
        }
        if let Some(max) = self.maximum {
            if num > max {
                return ValidationResult::failure(format!("Value must be <= {max}."));
            }
        }

        ValidationResult::success()
    }
}

/// Validates that a string is a valid integer, optionally within a range.
///
/// Mirrors Python Textual's `Integer` validator: first validates as a number
/// (with optional min/max range), then ensures the value is an integer.
#[derive(Debug, Clone, Copy)]
pub struct Integer {
    minimum: Option<i64>,
    maximum: Option<i64>,
}

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

impl Integer {
    pub fn new() -> Self {
        Self {
            minimum: None,
            maximum: None,
        }
    }

    pub fn minimum(mut self, value: i64) -> Self {
        self.minimum = Some(value);
        self
    }

    pub fn maximum(mut self, value: i64) -> Self {
        self.maximum = Some(value);
        self
    }
}

impl Validator for Integer {
    fn validate(&self, value: &str) -> ValidationResult {
        let value = value.trim();
        if value.is_empty() {
            return ValidationResult::failure("Must be a valid integer.");
        }

        let Ok(num) = value.parse::<i64>() else {
            return ValidationResult::failure("Must be a valid integer.");
        };

        if let Some(min) = self.minimum {
            if num < min {
                return ValidationResult::failure(format!(
                    "Must be greater than or equal to {min}."
                ));
            }
        }
        if let Some(max) = self.maximum {
            if num > max {
                return ValidationResult::failure(format!("Must be less than or equal to {max}."));
            }
        }

        ValidationResult::success()
    }
}

/// Validates that a string's length falls within a range (inclusive).
///
/// Mirrors Python Textual's `Length` validator.
#[derive(Debug, Clone, Copy)]
pub struct Length {
    minimum: Option<usize>,
    maximum: Option<usize>,
}

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

impl Length {
    pub fn new() -> Self {
        Self {
            minimum: None,
            maximum: None,
        }
    }

    pub fn minimum(mut self, value: usize) -> Self {
        self.minimum = Some(value);
        self
    }

    pub fn maximum(mut self, value: usize) -> Self {
        self.maximum = Some(value);
        self
    }
}

impl Validator for Length {
    fn validate(&self, value: &str) -> ValidationResult {
        let len = value.len();
        let too_short = self.minimum.is_some_and(|min| len < min);
        let too_long = self.maximum.is_some_and(|max| len > max);

        if too_short || too_long {
            let msg = match (self.minimum, self.maximum) {
                (Some(min), None) => format!("Must be longer than {min} characters."),
                (None, Some(max)) => format!("Must be shorter than {max} characters."),
                (Some(min), Some(max)) => format!("Must be between {min} and {max} characters."),
                _ => "Invalid length.".to_string(),
            };
            return ValidationResult::failure(msg);
        }

        ValidationResult::success()
    }
}

/// Validates that a string is a valid URL (has both a scheme and host).
///
/// Mirrors Python Textual's `URL` validator. Uses basic parsing without
/// external crates — checks for `scheme://host` pattern.
#[derive(Debug, Clone, Copy)]
pub struct Url;

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

impl Url {
    pub fn new() -> Self {
        Self
    }
}

impl Validator for Url {
    fn validate(&self, value: &str) -> ValidationResult {
        let value = value.trim();
        // Check for scheme://netloc pattern (mirrors Python's urlparse check)
        let Some((scheme, rest)) = value.split_once("://") else {
            return ValidationResult::failure("Must be a valid URL.");
        };
        if scheme.is_empty() {
            return ValidationResult::failure("Must be a valid URL.");
        }
        // netloc must be non-empty (could be followed by /, ?, #, or end)
        let netloc = rest.split(&['/', '?', '#'][..]).next().unwrap_or("");
        if netloc.is_empty() {
            return ValidationResult::failure("Must be a valid URL.");
        }
        ValidationResult::success()
    }
}

/// Validates that a string fully matches a regular expression.
///
/// Mirrors Python Textual's `Regex` validator (uses `re.fullmatch` semantics).
/// The pattern must match the entire string.
pub struct Regex {
    pattern: regex::Regex,
}

impl Regex {
    pub fn new(pattern: regex::Regex) -> Self {
        Self { pattern }
    }

    /// Create from a pattern string. Panics if the pattern is invalid.
    pub fn compile(pattern: &str) -> Self {
        Self {
            pattern: regex::Regex::new(pattern).expect("invalid regex pattern"),
        }
    }

    /// Try to create from a pattern string, returning `None` if invalid.
    pub fn try_compile(pattern: &str) -> Option<Self> {
        regex::Regex::new(pattern).ok().map(|r| Self { pattern: r })
    }
}

impl std::fmt::Debug for Regex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Regex")
            .field("pattern", &self.pattern.as_str())
            .finish()
    }
}

impl Validator for Regex {
    fn validate(&self, value: &str) -> ValidationResult {
        // fullmatch semantics: the pattern must match the entire string
        if self
            .pattern
            .find(value)
            .is_some_and(|m| m.start() == 0 && m.end() == value.len())
        {
            ValidationResult::success()
        } else {
            ValidationResult::failure(format!(
                "Must match regular expression {:?}.",
                self.pattern.as_str()
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn integer_valid() {
        let v = Integer::new();
        assert!(v.validate("42").is_valid);
        assert!(v.validate("-7").is_valid);
        assert!(v.validate("0").is_valid);
    }

    #[test]
    fn integer_invalid() {
        let v = Integer::new();
        assert!(!v.validate("3.5").is_valid);
        assert!(!v.validate("abc").is_valid);
        assert!(!v.validate("").is_valid);
    }

    #[test]
    fn integer_range() {
        let v = Integer::new().minimum(0).maximum(100);
        assert!(v.validate("50").is_valid);
        assert!(!v.validate("-1").is_valid);
        assert!(!v.validate("101").is_valid);
    }

    #[test]
    fn length_valid() {
        let v = Length::new().minimum(2).maximum(5);
        assert!(v.validate("ab").is_valid);
        assert!(v.validate("abcde").is_valid);
    }

    #[test]
    fn length_invalid() {
        let v = Length::new().minimum(2).maximum(5);
        assert!(!v.validate("a").is_valid);
        assert!(!v.validate("abcdef").is_valid);
    }

    #[test]
    fn length_unbounded_min() {
        let v = Length::new().maximum(3);
        assert!(v.validate("").is_valid);
        assert!(v.validate("abc").is_valid);
        assert!(!v.validate("abcd").is_valid);
    }

    #[test]
    fn length_unbounded_max() {
        let v = Length::new().minimum(2);
        assert!(!v.validate("a").is_valid);
        assert!(v.validate("ab").is_valid);
        assert!(v.validate("abcdef").is_valid);
    }

    #[test]
    fn url_valid() {
        let v = Url::new();
        assert!(v.validate("https://example.com").is_valid);
        assert!(v.validate("http://foo.bar/path").is_valid);
        assert!(v.validate("ftp://files.example.com").is_valid);
    }

    #[test]
    fn url_invalid() {
        let v = Url::new();
        assert!(!v.validate("not-a-url").is_valid);
        assert!(!v.validate("://missing-scheme").is_valid);
        assert!(!v.validate("http://").is_valid);
        assert!(!v.validate("").is_valid);
    }

    #[test]
    fn regex_valid() {
        let v = Regex::compile(r"\d{3}-\d{4}");
        assert!(v.validate("123-4567").is_valid);
    }

    #[test]
    fn regex_invalid() {
        let v = Regex::compile(r"\d{3}-\d{4}");
        assert!(!v.validate("12-4567").is_valid);
        assert!(!v.validate("abc").is_valid);
    }

    #[test]
    fn regex_fullmatch_semantics() {
        // Pattern should match the entire string, not just a substring
        let v = Regex::compile(r"\d+");
        assert!(v.validate("123").is_valid);
        assert!(!v.validate("123abc").is_valid);
        assert!(!v.validate("abc123").is_valid);
    }

    #[test]
    fn regex_try_compile_invalid() {
        assert!(Regex::try_compile("[invalid").is_none());
    }

    #[test]
    fn number_rejects_nan_inf() {
        let v = Number::new();
        assert!(!v.validate("NaN").is_valid);
        assert!(!v.validate("inf").is_valid);
        assert!(!v.validate("-inf").is_valid);
        assert!(!v.validate("infinity").is_valid);
    }
}