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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
//! Rich error messages for CSS parsing
//!
//! Provides detailed error messages with source snippets, suggestions,
//! and error codes for easy debugging.
//!
//! # Example
//!
//! ```rust,ignore
//! use revue::style::parse_css;
//!
//! let css = ".button { colr: red; }"; // typo in "color"
//!
//! match parse_css(css) {
//!     Ok(_) => println!("Parsed successfully"),
//!     Err(e) => {
//!         // Rich error output with suggestions
//!         eprintln!("{}", e.pretty_print(css));
//!     }
//! }
//! ```

use std::fmt;

// =============================================================================
// Error Code
// =============================================================================

/// CSS error codes for documentation lookup
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorCode {
    /// E001: Invalid syntax
    InvalidSyntax,
    /// E002: Unknown property
    UnknownProperty,
    /// E003: Invalid value for property
    InvalidValue,
    /// E004: Missing closing brace
    MissingBrace,
    /// E005: Missing semicolon
    MissingSemicolon,
    /// E006: Invalid selector
    InvalidSelector,
    /// E007: Undefined variable
    UndefinedVariable,
    /// E008: Invalid color format
    InvalidColor,
    /// E009: Invalid number/unit
    InvalidNumber,
    /// E010: Empty rule
    EmptyRule,
}

impl ErrorCode {
    /// Get the error code string (e.g., "E001")
    pub fn code(&self) -> &'static str {
        match self {
            Self::InvalidSyntax => "E001",
            Self::UnknownProperty => "E002",
            Self::InvalidValue => "E003",
            Self::MissingBrace => "E004",
            Self::MissingSemicolon => "E005",
            Self::InvalidSelector => "E006",
            Self::UndefinedVariable => "E007",
            Self::InvalidColor => "E008",
            Self::InvalidNumber => "E009",
            Self::EmptyRule => "E010",
        }
    }

    /// Get a short description
    pub fn description(&self) -> &'static str {
        match self {
            Self::InvalidSyntax => "invalid syntax",
            Self::UnknownProperty => "unknown CSS property",
            Self::InvalidValue => "invalid property value",
            Self::MissingBrace => "missing closing brace '}'",
            Self::MissingSemicolon => "missing semicolon ';'",
            Self::InvalidSelector => "invalid CSS selector",
            Self::UndefinedVariable => "undefined CSS variable",
            Self::InvalidColor => "invalid color format",
            Self::InvalidNumber => "invalid number or unit",
            Self::EmptyRule => "empty CSS rule",
        }
    }

    /// Get help text with more details
    pub fn help(&self) -> &'static str {
        match self {
            Self::InvalidSyntax => {
                "Check for mismatched brackets, quotes, or unexpected characters"
            }
            Self::UnknownProperty => "Check spelling or see the supported properties list",
            Self::InvalidValue => "The value format doesn't match what this property expects",
            Self::MissingBrace => "Every '{' must have a matching '}'",
            Self::MissingSemicolon => "Each CSS declaration should end with ';'",
            Self::InvalidSelector => "Selectors should be like '.class', '#id', or 'element'",
            Self::UndefinedVariable => "Define variables in :root { --name: value; }",
            Self::InvalidColor => "Use formats like #rgb, #rrggbb, rgb(r,g,b), or named colors",
            Self::InvalidNumber => "Numbers should be like '10', '10px', '50%', or '0.5'",
            Self::EmptyRule => "Add at least one property declaration inside the rule",
        }
    }
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.code())
    }
}

// =============================================================================
// Error Severity
// =============================================================================

/// Error severity level
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    /// Error - parsing failed
    Error,
    /// Warning - parsed with issues
    Warning,
    /// Hint - suggestion for improvement
    Hint,
}

impl Severity {
    /// Get ANSI color for terminal output
    pub fn color(&self) -> &'static str {
        match self {
            Self::Error => "\x1b[31m",   // Red
            Self::Warning => "\x1b[33m", // Yellow
            Self::Hint => "\x1b[36m",    // Cyan
        }
    }

    /// Get label text
    pub fn label(&self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warning => "warning",
            Self::Hint => "hint",
        }
    }
}

// =============================================================================
// Source Location
// =============================================================================

/// Source code location
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SourceLocation {
    /// Line number (1-indexed)
    pub line: usize,
    /// Column number (1-indexed)
    pub column: usize,
    /// Byte offset in source
    pub offset: usize,
    /// Length of the problematic span
    pub length: usize,
}

impl SourceLocation {
    /// Create a new source location
    pub fn new(line: usize, column: usize, offset: usize, length: usize) -> Self {
        Self {
            line,
            column,
            offset,
            length,
        }
    }

    /// Create from byte offset in source
    pub fn from_offset(source: &str, offset: usize) -> Self {
        let mut line = 1;
        let mut column = 1;

        for (i, ch) in source.char_indices() {
            if i >= offset {
                break;
            }
            if ch == '\n' {
                line += 1;
                column = 1;
            } else {
                column += 1;
            }
        }

        Self {
            line,
            column,
            offset,
            length: 1,
        }
    }

    /// Create from byte offset with length
    pub fn from_offset_len(source: &str, offset: usize, length: usize) -> Self {
        let mut loc = Self::from_offset(source, offset);
        loc.length = length;
        loc
    }
}

// =============================================================================
// Suggestion
// =============================================================================

/// A suggestion for fixing an error
#[derive(Debug, Clone)]
pub struct Suggestion {
    /// What to suggest
    pub message: String,
    /// Optional replacement text
    pub replacement: Option<String>,
}

impl Suggestion {
    /// Create a simple suggestion
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            replacement: None,
        }
    }

    /// Create a suggestion with replacement
    pub fn with_fix(message: impl Into<String>, replacement: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            replacement: Some(replacement.into()),
        }
    }
}

// =============================================================================
// Rich Parse Error
// =============================================================================

/// Rich CSS parsing error with context
#[derive(Debug, Clone)]
pub struct RichParseError {
    /// Error code
    pub code: ErrorCode,
    /// Severity level
    pub severity: Severity,
    /// Error message
    pub message: String,
    /// Source location
    pub location: SourceLocation,
    /// Suggestions for fixing
    pub suggestions: Vec<Suggestion>,
    /// Additional notes
    pub notes: Vec<String>,
}

impl RichParseError {
    /// Create a new error
    pub fn new(code: ErrorCode, message: impl Into<String>, location: SourceLocation) -> Self {
        Self {
            code,
            severity: Severity::Error,
            message: message.into(),
            location,
            suggestions: Vec::new(),
            notes: Vec::new(),
        }
    }

    /// Set severity
    pub fn severity(mut self, severity: Severity) -> Self {
        self.severity = severity;
        self
    }

    /// Add a suggestion
    pub fn suggest(mut self, suggestion: Suggestion) -> Self {
        self.suggestions.push(suggestion);
        self
    }

    /// Add a note
    pub fn note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }

    /// Pretty print the error with source context
    pub fn pretty_print(&self, source: &str) -> String {
        let mut output = String::new();
        let reset = "\x1b[0m";
        let bold = "\x1b[1m";
        let dim = "\x1b[2m";
        let blue = "\x1b[34m";
        let cyan = "\x1b[36m";

        // Error header
        output.push_str(&format!(
            "{}{}{}: {}[{}]{} {}\n",
            bold,
            self.severity.color(),
            self.severity.label(),
            reset,
            self.code,
            reset,
            self.message
        ));

        // Location
        output.push_str(&format!(
            "  {}-->{} line {}, column {}\n",
            blue, reset, self.location.line, self.location.column
        ));

        // Source snippet
        let lines: Vec<&str> = source.lines().collect();
        let line_idx = self.location.line.saturating_sub(1);

        if line_idx < lines.len() {
            let line_num_width = (self.location.line + 1).to_string().len().max(3);

            // Context line before
            if line_idx > 0 {
                output.push_str(&format!(
                    "  {}{:>width$} |{} {}\n",
                    dim,
                    line_idx,
                    reset,
                    lines[line_idx - 1],
                    width = line_num_width
                ));
            }

            // Error line
            output.push_str(&format!(
                "  {}{:>width$} |{} {}\n",
                blue,
                self.location.line,
                reset,
                lines[line_idx],
                width = line_num_width
            ));

            // Pointer line
            let pointer_offset = self.location.column.saturating_sub(1);
            let pointer_len = self.location.length.max(1);
            output.push_str(&format!(
                "  {:>width$} {} {}{}{}{}",
                "",
                "|",
                " ".repeat(pointer_offset),
                self.severity.color(),
                "^".repeat(pointer_len),
                reset,
                width = line_num_width
            ));

            // Inline hint
            if !self.suggestions.is_empty() {
                output.push_str(&format!(" {}", self.suggestions[0].message));
            }
            output.push('\n');

            // Context line after
            if line_idx + 1 < lines.len() {
                output.push_str(&format!(
                    "  {}{:>width$} |{} {}\n",
                    dim,
                    self.location.line + 1,
                    reset,
                    lines[line_idx + 1],
                    width = line_num_width
                ));
            }
        }

        // Suggestions
        for suggestion in &self.suggestions {
            if let Some(replacement) = &suggestion.replacement {
                output.push_str(&format!("\n  {}help:{} try `{}`", cyan, reset, replacement));
            }
        }

        // Notes
        for note in &self.notes {
            output.push_str(&format!("\n  {}note:{} {}", cyan, reset, note));
        }

        // Help
        output.push_str(&format!(
            "\n  {}help:{} {}\n",
            cyan,
            reset,
            self.code.help()
        ));

        output
    }

    /// Format without ANSI colors (for logs)
    pub fn plain_text(&self, source: &str) -> String {
        let mut output = String::new();

        // Error header
        output.push_str(&format!(
            "{}: [{}] {}\n",
            self.severity.label(),
            self.code,
            self.message
        ));

        // Location
        output.push_str(&format!(
            "  --> line {}, column {}\n",
            self.location.line, self.location.column
        ));

        // Source snippet
        let lines: Vec<&str> = source.lines().collect();
        let line_idx = self.location.line.saturating_sub(1);

        if line_idx < lines.len() {
            output.push_str(&format!("  {} | {}\n", self.location.line, lines[line_idx]));

            let pointer_offset = self.location.column.saturating_sub(1);
            let pointer_len = self.location.length.max(1);
            output.push_str(&format!(
                "    | {}{}\n",
                " ".repeat(pointer_offset),
                "^".repeat(pointer_len)
            ));
        }

        // Suggestions
        for suggestion in &self.suggestions {
            output.push_str(&format!("  help: {}\n", suggestion.message));
            if let Some(replacement) = &suggestion.replacement {
                output.push_str(&format!("    try: {}\n", replacement));
            }
        }

        // Notes
        for note in &self.notes {
            output.push_str(&format!("  note: {}\n", note));
        }

        output
    }
}

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

impl fmt::Display for RichParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{}] {} (line {}, column {})",
            self.code, self.message, self.location.line, self.location.column
        )
    }
}

// =============================================================================
// Error Collection
// =============================================================================

/// Collection of parse errors for error recovery
#[derive(Debug, Default)]
pub struct ParseErrors {
    /// Collected errors
    errors: Vec<RichParseError>,
    /// Maximum errors before giving up
    max_errors: usize,
}

impl ParseErrors {
    /// Create a new error collection
    pub fn new() -> Self {
        Self {
            errors: Vec::new(),
            max_errors: 10,
        }
    }

    /// Set maximum errors
    pub fn max_errors(mut self, max: usize) -> Self {
        self.max_errors = max;
        self
    }

    /// Add an error
    pub fn push(&mut self, error: RichParseError) {
        self.errors.push(error);
    }

    /// Check if we've hit max errors
    pub fn is_full(&self) -> bool {
        self.errors.len() >= self.max_errors
    }

    /// Check if there are any errors
    pub fn has_errors(&self) -> bool {
        self.errors.iter().any(|e| e.severity == Severity::Error)
    }

    /// Get all errors
    pub fn errors(&self) -> &[RichParseError] {
        &self.errors
    }

    /// Get error count
    pub fn len(&self) -> usize {
        self.errors.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Pretty print all errors
    pub fn pretty_print(&self, source: &str) -> String {
        let mut output = String::new();

        for error in &self.errors {
            output.push_str(&error.pretty_print(source));
            output.push('\n');
        }

        // Summary
        let error_count = self
            .errors
            .iter()
            .filter(|e| e.severity == Severity::Error)
            .count();
        let warning_count = self
            .errors
            .iter()
            .filter(|e| e.severity == Severity::Warning)
            .count();

        if error_count > 0 || warning_count > 0 {
            output.push_str(&format!(
                "\x1b[1m{} error(s), {} warning(s)\x1b[0m\n",
                error_count, warning_count
            ));
        }

        output
    }
}

// =============================================================================
// Property Suggestions (Did you mean?)
// =============================================================================

/// Common CSS properties for suggestions
pub const KNOWN_PROPERTIES: &[&str] = &[
    "color",
    "background",
    "background-color",
    "border",
    "border-color",
    "border-width",
    "border-style",
    "border-radius",
    "padding",
    "padding-top",
    "padding-right",
    "padding-bottom",
    "padding-left",
    "margin",
    "margin-top",
    "margin-right",
    "margin-bottom",
    "margin-left",
    "width",
    "height",
    "min-width",
    "min-height",
    "max-width",
    "max-height",
    "display",
    "flex-direction",
    "justify-content",
    "align-items",
    "align-self",
    "flex-grow",
    "flex-shrink",
    "flex-basis",
    "flex-wrap",
    "gap",
    "position",
    "top",
    "right",
    "bottom",
    "left",
    "font-weight",
    "font-style",
    "text-align",
    "text-decoration",
    "opacity",
    "visibility",
    "overflow",
    "cursor",
    "transition",
    "animation",
    "grid-template-columns",
    "grid-template-rows",
    "grid-column",
    "grid-row",
];

/// Find similar property names (Levenshtein distance)
pub fn suggest_property(unknown: &str) -> Vec<&'static str> {
    let mut suggestions: Vec<(&str, usize)> = KNOWN_PROPERTIES
        .iter()
        .filter_map(|prop| {
            let dist = levenshtein_distance(unknown, prop);
            // Only suggest if distance is reasonable
            if dist <= 3 && dist < unknown.len() {
                Some((*prop, dist))
            } else {
                None
            }
        })
        .collect();

    suggestions.sort_by_key(|(_, d)| *d);
    suggestions.into_iter().take(3).map(|(p, _)| p).collect()
}

/// Calculate Levenshtein distance between two strings
fn levenshtein_distance(a: &str, b: &str) -> usize {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();
    let a_len = a_chars.len();
    let b_len = b_chars.len();

    if a_len == 0 {
        return b_len;
    }
    if b_len == 0 {
        return a_len;
    }

    let mut prev: Vec<usize> = (0..=b_len).collect();
    let mut curr = vec![0; b_len + 1];

    for i in 1..=a_len {
        curr[0] = i;
        for j in 1..=b_len {
            let cost = if a_chars[i - 1] == b_chars[j - 1] {
                0
            } else {
                1
            };
            curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
        }
        std::mem::swap(&mut prev, &mut curr);
    }

    prev[b_len]
}

// Most tests moved to tests/style_tests.rs
// Tests below use private function levenshtein_distance

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

    #[test]
    fn test_levenshtein_identical() {
        assert_eq!(levenshtein_distance("test", "test"), 0);
    }

    #[test]
    fn test_levenshtein_one_char_diff() {
        assert_eq!(levenshtein_distance("test", "tset"), 2); // swap = 2
        assert_eq!(levenshtein_distance("test", "tests"), 1); // insert
        assert_eq!(levenshtein_distance("test", "tes"), 1); // delete
        assert_eq!(levenshtein_distance("test", "fest"), 1); // substitute
    }

    #[test]
    fn test_levenshtein_empty_strings() {
        assert_eq!(levenshtein_distance("", ""), 0);
        assert_eq!(levenshtein_distance("abc", ""), 3);
        assert_eq!(levenshtein_distance("", "xyz"), 3);
    }

    #[test]
    fn test_levenshtein_completely_different() {
        assert_eq!(levenshtein_distance("abc", "xyz"), 3);
    }
}