tui-canvas 0.8.10

Form/textarea/input for TUI
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// src/validation/state.rs
//! Validation state management

use crate::validation::{ExternalValidationState, ValidationConfig, ValidationResult};
use std::collections::HashMap;

/// Validation state for all fields in a form
#[derive(Debug, Clone, Default)]
pub struct ValidationState {
    /// Validation configurations per field index
    field_configs: HashMap<usize, ValidationConfig>,

    /// Current validation results per field index
    field_results: HashMap<usize, ValidationResult>,

    /// Track which fields have been validated
    validated_fields: std::collections::HashSet<usize>,

    /// Global validation enabled/disabled
    enabled: bool,

    /// External validation results per field (Feature 5)
    external_results: HashMap<usize, ExternalValidationState>,

    last_switch_block: Option<String>,
}

impl ValidationState {
    /// Create a new validation state
    pub fn new() -> Self {
        Self {
            field_configs: HashMap::new(),
            field_results: HashMap::new(),
            validated_fields: std::collections::HashSet::new(),
            enabled: true,
            external_results: HashMap::new(),
            last_switch_block: None,
        }
    }

    /// Enable or disable validation globally
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
        if !enabled {
            // Clear all validation results when disabled
            self.field_results.clear();
            self.validated_fields.clear();
            self.external_results.clear(); // Also clear external results
        }
    }

    /// Check if validation is enabled
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Set validation configuration for a field
    pub fn set_field_config(&mut self, field_index: usize, config: ValidationConfig) {
        if config.has_validation() || config.external_validation_enabled {
            self.field_configs.insert(field_index, config);
        } else {
            self.field_configs.remove(&field_index);
            self.field_results.remove(&field_index);
            self.validated_fields.remove(&field_index);
            self.external_results.remove(&field_index);
        }
    }

    /// Get validation configuration for a field
    pub fn get_field_config(&self, field_index: usize) -> Option<&ValidationConfig> {
        self.field_configs.get(&field_index)
    }

    /// Remove validation configuration for a field
    pub fn remove_field_config(&mut self, field_index: usize) {
        self.field_configs.remove(&field_index);
        self.field_results.remove(&field_index);
        self.validated_fields.remove(&field_index);
        self.external_results.remove(&field_index);
    }

    /// Set external validation state for a field (Feature 5)
    pub fn set_external_validation(&mut self, field_index: usize, state: ExternalValidationState) {
        self.external_results.insert(field_index, state);
    }

    /// Get current external validation state for a field
    pub fn get_external_validation(&self, field_index: usize) -> ExternalValidationState {
        self.external_results
            .get(&field_index)
            .cloned()
            .unwrap_or(ExternalValidationState::NotValidated)
    }

    /// Clear external validation state for a field
    pub fn clear_external_validation(&mut self, field_index: usize) {
        self.external_results.remove(&field_index);
    }

    /// Clear all external validation states
    pub fn clear_all_external_validation(&mut self) {
        self.external_results.clear();
    }

    /// Validate character insertion for a field
    pub fn validate_char_insertion(
        &mut self,
        field_index: usize,
        current_text: &str,
        position: usize,
        character: char,
    ) -> ValidationResult {
        if !self.enabled {
            return ValidationResult::Valid;
        }

        if let Some(config) = self.field_configs.get(&field_index) {
            let result = config.validate_char_insertion(current_text, position, character);

            // Store the validation result
            self.field_results.insert(field_index, result.clone());
            self.validated_fields.insert(field_index);

            result
        } else {
            ValidationResult::Valid
        }
    }

    /// Validate field content
    pub fn validate_field_content(&mut self, field_index: usize, text: &str) -> ValidationResult {
        if !self.enabled {
            return ValidationResult::Valid;
        }

        if let Some(config) = self.field_configs.get(&field_index) {
            let result = config.validate_content(text);

            // Store the validation result
            self.field_results.insert(field_index, result.clone());
            self.validated_fields.insert(field_index);

            result
        } else {
            ValidationResult::Valid
        }
    }

    /// Get current validation result for a field
    pub fn get_field_result(&self, field_index: usize) -> Option<&ValidationResult> {
        self.field_results.get(&field_index)
    }

    /// Get formatted display for a field if a custom formatter is configured.
    /// Returns (formatted_text, position_mapper, optional_warning_message).
    #[cfg(feature = "validation")]
    pub fn formatted_for(
        &self,
        field_index: usize,
        raw: &str,
    ) -> Option<(
        String,
        std::sync::Arc<dyn crate::validation::PositionMapper>,
        Option<String>,
    )> {
        let config = self.field_configs.get(&field_index)?;
        config.run_custom_formatter(raw)
    }

    /// Check if a field has been validated
    pub fn is_field_validated(&self, field_index: usize) -> bool {
        self.validated_fields.contains(&field_index)
    }

    /// Clear validation result for a field
    pub fn clear_field_result(&mut self, field_index: usize) {
        self.field_results.remove(&field_index);
        self.validated_fields.remove(&field_index);
    }

    /// Clear all validation results
    pub fn clear_all_results(&mut self) {
        self.field_results.clear();
        self.validated_fields.clear();
    }

    /// Get all field indices that have validation configured
    pub fn validated_field_indices(&self) -> impl Iterator<Item = usize> + '_ {
        self.field_configs.keys().copied()
    }

    /// Get all field indices with validation errors
    pub fn fields_with_errors(&self) -> impl Iterator<Item = usize> + '_ {
        self.field_results
            .iter()
            .filter(|(_, result)| result.is_error())
            .map(|(index, _)| *index)
    }

    /// Get all field indices with validation warnings
    pub fn fields_with_warnings(&self) -> impl Iterator<Item = usize> + '_ {
        self.field_results
            .iter()
            .filter(|(_, result)| matches!(result, ValidationResult::Warning { .. }))
            .map(|(index, _)| *index)
    }

    /// Check if any field has validation errors
    pub fn has_errors(&self) -> bool {
        self.field_results.values().any(|result| result.is_error())
    }

    /// Check if any field has validation warnings
    pub fn has_warnings(&self) -> bool {
        self.field_results
            .values()
            .any(|result| matches!(result, ValidationResult::Warning { .. }))
    }

    /// Get total count of fields with validation configured
    pub fn validated_field_count(&self) -> usize {
        self.field_configs.len()
    }

    /// Check if field switching is allowed for a specific field
    pub fn allows_field_switch(&self, field_index: usize, text: &str) -> bool {
        if !self.enabled {
            return true;
        }

        if let Some(config) = self.field_configs.get(&field_index) {
            config.allows_field_switch(text)
        } else {
            true // No validation configured, allow switching
        }
    }

    /// Get reason why field switching is blocked (if any)
    pub fn field_switch_block_reason(&self, field_index: usize, text: &str) -> Option<String> {
        if !self.enabled {
            return None;
        }

        if let Some(config) = self.field_configs.get(&field_index) {
            config.field_switch_block_reason(text)
        } else {
            None // No validation configured
        }
    }
    pub fn summary(&self) -> ValidationSummary {
        let total_validated = self.validated_fields.len();
        let errors = self.fields_with_errors().count();
        let warnings = self.fields_with_warnings().count();
        let valid = total_validated - errors - warnings;

        ValidationSummary {
            total_fields: self.field_configs.len(),
            validated_fields: total_validated,
            valid_fields: valid,
            warning_fields: warnings,
            error_fields: errors,
        }
    }

    /// Set the last switch block reason (for UI convenience)
    pub fn set_last_switch_block<S: Into<String>>(&mut self, reason: S) {
        self.last_switch_block = Some(reason.into());
    }

    /// Clear the last switch block reason
    pub fn clear_last_switch_block(&mut self) {
        self.last_switch_block = None;
    }

    /// Get the last switch block reason (if any)
    pub fn last_switch_block(&self) -> Option<&str> {
        self.last_switch_block.as_deref()
    }
}

/// Summary of validation state across all fields
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationSummary {
    /// Total number of fields with validation configured
    pub total_fields: usize,

    /// Number of fields that have been validated
    pub validated_fields: usize,

    /// Number of fields with valid validation results
    pub valid_fields: usize,

    /// Number of fields with warnings
    pub warning_fields: usize,

    /// Number of fields with errors
    pub error_fields: usize,
}

impl ValidationSummary {
    /// Check if all configured fields are valid
    pub fn is_all_valid(&self) -> bool {
        self.error_fields == 0 && self.validated_fields == self.total_fields
    }

    /// Check if there are any errors
    pub fn has_errors(&self) -> bool {
        self.error_fields > 0
    }

    /// Check if there are any warnings
    pub fn has_warnings(&self) -> bool {
        self.warning_fields > 0
    }

    /// Get completion percentage (validated fields / total fields)
    pub fn completion_percentage(&self) -> f32 {
        if self.total_fields == 0 {
            1.0
        } else {
            self.validated_fields as f32 / self.total_fields as f32
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::validation::{CharacterLimits, ValidationConfigBuilder};

    #[test]
    fn test_validation_state_creation() {
        let state = ValidationState::new();
        assert!(state.is_enabled());
        assert_eq!(state.validated_field_count(), 0);
    }

    #[test]
    fn test_enable_disable() {
        let mut state = ValidationState::new();

        // Add some validation config
        let config = ValidationConfigBuilder::new().with_max_length(10).build();
        state.set_field_config(0, config);

        // Validate something
        let result = state.validate_field_content(0, "test");
        assert!(result.is_acceptable());
        assert!(state.is_field_validated(0));

        // Disable validation
        state.set_enabled(false);
        assert!(!state.is_enabled());
        assert!(!state.is_field_validated(0)); // Should be cleared

        // Validation should now return valid regardless
        let result = state.validate_field_content(0, "this is way too long for the limit");
        assert!(result.is_acceptable());
    }

    #[test]
    fn test_field_config_management() {
        let mut state = ValidationState::new();

        let config = ValidationConfigBuilder::new().with_max_length(5).build();

        // Set config
        state.set_field_config(0, config);
        assert_eq!(state.validated_field_count(), 1);
        assert!(state.get_field_config(0).is_some());

        // Remove config
        state.remove_field_config(0);
        assert_eq!(state.validated_field_count(), 0);
        assert!(state.get_field_config(0).is_none());
    }

    #[test]
    fn test_character_insertion_validation() {
        let mut state = ValidationState::new();

        let config = ValidationConfigBuilder::new().with_max_length(5).build();
        state.set_field_config(0, config);

        // Valid insertion
        let result = state.validate_char_insertion(0, "test", 4, 'x');
        assert!(result.is_acceptable());

        // Invalid insertion
        let result = state.validate_char_insertion(0, "tests", 5, 'x');
        assert!(!result.is_acceptable());

        // Check that result was stored
        assert!(state.is_field_validated(0));
        let stored_result = state.get_field_result(0);
        assert!(stored_result.is_some());
        assert!(!stored_result.unwrap().is_acceptable());
    }

    #[test]
    fn test_validation_summary() {
        let mut state = ValidationState::new();

        // Configure two fields
        let config1 = ValidationConfigBuilder::new().with_max_length(5).build();
        let config2 = ValidationConfigBuilder::new().with_max_length(10).build();
        state.set_field_config(0, config1);
        state.set_field_config(1, config2);

        // Validate field 0 (valid)
        state.validate_field_content(0, "test");

        // Validate field 1 (error)
        state.validate_field_content(1, "this is too long");

        let summary = state.summary();
        assert_eq!(summary.total_fields, 2);
        assert_eq!(summary.validated_fields, 2);
        assert_eq!(summary.valid_fields, 1);
        assert_eq!(summary.error_fields, 1);
        assert_eq!(summary.warning_fields, 0);

        assert!(!summary.is_all_valid());
        assert!(summary.has_errors());
        assert!(!summary.has_warnings());
        assert_eq!(summary.completion_percentage(), 1.0);
    }

    #[test]
    fn test_error_and_warning_tracking() {
        let mut state = ValidationState::new();

        let config = ValidationConfigBuilder::new()
            .with_character_limits(CharacterLimits::new_range(3, 10).with_warning_threshold(8))
            .build();
        state.set_field_config(0, config);

        // Too short (warning)
        state.validate_field_content(0, "hi");
        assert!(state.has_warnings());
        assert!(!state.has_errors());

        // Just right
        state.validate_field_content(0, "hello");
        assert!(!state.has_warnings());
        assert!(!state.has_errors());

        // Too long (error)
        state.validate_field_content(0, "hello world!");
        assert!(!state.has_warnings());
        assert!(state.has_errors());
    }
}