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
//! Text wrapping and formatting utilities

use crate::utils::unicode::{char_width, display_width, truncate_to_width};
use textwrap::{Options, WordSeparator, WordSplitter};

/// Text wrapping mode
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WrapMode {
    /// No wrapping, truncate at width
    NoWrap,
    /// Wrap at word boundaries
    #[default]
    Word,
    /// Wrap at character boundaries
    Char,
}

/// Text overflow handling
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Overflow {
    /// Clip text at boundary
    #[default]
    Clip,
    /// Show ellipsis at end
    Ellipsis,
    /// Show ellipsis in middle
    EllipsisMiddle,
}

/// Text wrapper with configurable options
#[derive(Clone)]
pub struct TextWrapper {
    width: usize,
    mode: WrapMode,
    overflow: Overflow,
    indent: String,
    subsequent_indent: String,
    break_words: bool,
}

impl TextWrapper {
    /// Create a new text wrapper
    pub fn new(width: usize) -> Self {
        Self {
            width,
            mode: WrapMode::Word,
            overflow: Overflow::Clip,
            indent: String::new(),
            subsequent_indent: String::new(),
            break_words: true,
        }
    }

    /// Set wrap mode
    pub fn mode(mut self, mode: WrapMode) -> Self {
        self.mode = mode;
        self
    }

    /// Set overflow handling
    pub fn overflow(mut self, overflow: Overflow) -> Self {
        self.overflow = overflow;
        self
    }

    /// Set first line indent
    pub fn indent(mut self, indent: impl Into<String>) -> Self {
        self.indent = indent.into();
        self
    }

    /// Set subsequent line indent
    pub fn subsequent_indent(mut self, indent: impl Into<String>) -> Self {
        self.subsequent_indent = indent.into();
        self
    }

    /// Set whether to break long words
    pub fn break_words(mut self, break_words: bool) -> Self {
        self.break_words = break_words;
        self
    }

    /// Wrap text
    pub fn wrap(&self, text: &str) -> Vec<String> {
        match self.mode {
            WrapMode::NoWrap => text
                .lines()
                .map(|line| self.handle_overflow(line))
                .collect(),
            WrapMode::Word => {
                let options = Options::new(self.width)
                    .initial_indent(&self.indent)
                    .subsequent_indent(&self.subsequent_indent)
                    .word_separator(WordSeparator::UnicodeBreakProperties)
                    .word_splitter(if self.break_words {
                        WordSplitter::HyphenSplitter
                    } else {
                        WordSplitter::NoHyphenation
                    });

                textwrap::wrap(text, options)
                    .into_iter()
                    .map(|cow| cow.into_owned())
                    .collect()
            }
            WrapMode::Char => {
                let mut lines = Vec::new();

                for line in text.lines() {
                    let indent = if lines.is_empty() {
                        &self.indent
                    } else {
                        &self.subsequent_indent
                    };

                    // Use display_width for indent width
                    let indent_width = display_width(indent);
                    let remaining_width = self.width.saturating_sub(indent_width);

                    if remaining_width == 0 {
                        lines.push(indent.clone());
                        continue;
                    }

                    // If line fits, just add it
                    if display_width(line) <= remaining_width {
                        lines.push(format!("{}{}", indent, line));
                        continue;
                    }

                    // Split by display width, not character count
                    let mut pos = 0;
                    let mut first_line = true;

                    while pos < line.len() {
                        // Get substring starting at pos
                        let remaining_str = &line[pos..];

                        // Get indent for this line
                        let current_indent = if first_line {
                            &self.indent
                        } else {
                            &self.subsequent_indent
                        };

                        let indent_width = display_width(current_indent);
                        let remaining_width = self.width.saturating_sub(indent_width);

                        if remaining_width == 0 {
                            break;
                        }

                        // Truncate to fit in remaining width
                        let chunk = truncate_to_width(remaining_str, remaining_width);
                        lines.push(format!("{}{}", current_indent, chunk));

                        pos += chunk.len();
                        first_line = false;
                    }

                    if line.is_empty() && !indent.is_empty() {
                        lines.push(indent.clone());
                    }
                }

                lines
            }
        }
    }

    /// Handle overflow for a single line
    fn handle_overflow(&self, text: &str) -> String {
        let text_width = display_width(text);
        if text_width <= self.width {
            return text.to_string();
        }

        match self.overflow {
            Overflow::Clip => truncate_to_width(text, self.width).to_string(),
            Overflow::Ellipsis => {
                if self.width <= 3 {
                    "...".chars().take(self.width).collect()
                } else {
                    let visible = self.width - 3;
                    let truncated = truncate_to_width(text, visible);
                    format!("{}...", truncated)
                }
            }
            Overflow::EllipsisMiddle => {
                if self.width <= 3 {
                    "...".chars().take(self.width).collect()
                } else {
                    // Use saturating arithmetic to prevent overflow
                    let width_minus_3 = self.width.saturating_sub(3);
                    let half = width_minus_3 / 2;
                    // Get first half
                    let first = truncate_to_width(text, half);
                    // Get second half from the end (also using saturating_sub)
                    let from_end = width_minus_3.saturating_sub(half);
                    let second = if from_end > 0 {
                        // Need to get last 'from_end' display columns
                        let mut total = 0;
                        let chars: Vec<char> = text.chars().rev().collect();
                        let mut rev_chars = Vec::new();
                        for ch in chars {
                            let ch_width = char_width(ch);
                            if total + ch_width > from_end {
                                break;
                            }
                            total += ch_width;
                            rev_chars.push(ch);
                        }
                        rev_chars.into_iter().rev().collect()
                    } else {
                        String::new()
                    };
                    format!("{}...{}", first, second)
                }
            }
        }
    }
}

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

/// Wrap text to fit within width
pub fn wrap_text(text: &str, width: usize) -> Vec<String> {
    TextWrapper::new(width).wrap(text)
}

/// Wrap text with word boundaries
pub fn wrap_words(text: &str, width: usize) -> Vec<String> {
    TextWrapper::new(width).mode(WrapMode::Word).wrap(text)
}

/// Wrap text at character boundaries
pub fn wrap_chars(text: &str, width: usize) -> Vec<String> {
    TextWrapper::new(width).mode(WrapMode::Char).wrap(text)
}

/// Truncate text with ellipsis
pub fn truncate(text: &str, width: usize) -> String {
    TextWrapper::new(width)
        .mode(WrapMode::NoWrap)
        .overflow(Overflow::Ellipsis)
        .wrap(text)
        .into_iter()
        .next()
        .unwrap_or_default()
}

/// Truncate text with ellipsis in the middle
pub fn truncate_middle(text: &str, width: usize) -> String {
    TextWrapper::new(width)
        .mode(WrapMode::NoWrap)
        .overflow(Overflow::EllipsisMiddle)
        .wrap(text)
        .into_iter()
        .next()
        .unwrap_or_default()
}

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

    #[test]
    fn test_wrap_text() {
        let wrapped = wrap_text("Hello world", 5);
        assert!(wrapped.len() >= 2);
    }

    #[test]
    fn test_wrap_words() {
        let wrapped = wrap_words("The quick brown fox", 10);
        assert!(wrapped.len() >= 2);
    }

    #[test]
    fn test_wrap_chars() {
        let wrapped = wrap_chars("Hello", 3);
        assert_eq!(wrapped.len(), 2);
        assert_eq!(wrapped[0], "Hel");
        assert_eq!(wrapped[1], "lo");
    }

    #[test]
    fn test_truncate() {
        let result = truncate("Hello World", 8);
        assert_eq!(result, "Hello...");
    }

    #[test]
    fn test_truncate_short() {
        let result = truncate("Hi", 10);
        assert_eq!(result, "Hi");
    }

    #[test]
    fn test_truncate_middle() {
        let result = truncate_middle("Hello World", 9);
        assert!(result.contains("..."));
        assert_eq!(result.len(), 9);
    }

    #[test]
    fn test_wrapper_new() {
        let wrapper = TextWrapper::new(40);
        assert_eq!(wrapper.width, 40);
    }

    #[test]
    fn test_wrapper_mode() {
        let wrapper = TextWrapper::new(40).mode(WrapMode::Char);
        assert_eq!(wrapper.mode, WrapMode::Char);
    }

    #[test]
    fn test_wrapper_overflow() {
        let wrapper = TextWrapper::new(40).overflow(Overflow::Ellipsis);
        assert_eq!(wrapper.overflow, Overflow::Ellipsis);
    }

    #[test]
    fn test_wrapper_indent() {
        let wrapper = TextWrapper::new(40).indent("  ").subsequent_indent("    ");

        let wrapped = wrapper.wrap("This is a test line that should wrap");
        assert!(wrapped[0].starts_with("  "));
        if wrapped.len() > 1 {
            assert!(wrapped[1].starts_with("    "));
        }
    }

    #[test]
    fn test_no_wrap_mode() {
        let wrapper = TextWrapper::new(5).mode(WrapMode::NoWrap);
        let wrapped = wrapper.wrap("Hello World");

        assert_eq!(wrapped.len(), 1);
        assert_eq!(wrapped[0], "Hello");
    }

    #[test]
    fn test_overflow_clip() {
        let wrapper = TextWrapper::new(5)
            .mode(WrapMode::NoWrap)
            .overflow(Overflow::Clip);

        let wrapped = wrapper.wrap("Hello World");
        assert_eq!(wrapped[0], "Hello");
    }

    #[test]
    fn test_wrapper_break_words() {
        let wrapper = TextWrapper::new(40).break_words(false);
        assert!(!wrapper.break_words);
    }

    #[test]
    fn test_wrap_multiline() {
        let text = "Line1\nLine2\nLine3";
        let wrapped = wrap_text(text, 10);
        assert!(wrapped.len() >= 3);
    }

    #[test]
    fn test_wrap_empty() {
        let wrapped = wrap_text("", 10);
        assert!(wrapped.is_empty() || wrapped[0].is_empty());
    }

    // =============================================================================
    // Edge Case Tests
    // =============================================================================

    #[test]
    fn test_wrap_unicode_emoji() {
        // Each emoji is 1 char but may be multiple bytes
        let text = "Hello 👋 World 🌍";
        let wrapped = wrap_chars(text, 10);
        assert!(wrapped.len() >= 1);
        // Ensure emojis are not broken
        for line in &wrapped {
            assert!(line.is_char_boundary(line.len()));
        }
    }

    #[test]
    fn test_wrap_unicode_cjk() {
        // CJK characters are 2 columns wide
        let text = "你好世界こんにちは";
        let wrapped = wrap_chars(text, 4);
        assert!(wrapped.len() >= 2);
        // Width 4 means 2 CJK chars fit (each is 2 columns wide)
        assert_eq!(display_width(&wrapped[0]), 4);
        assert_eq!(wrapped[0].chars().count(), 2); // 2 CJK chars
    }

    #[test]
    fn test_wrap_unicode_mixed() {
        // Mix of ASCII (width 1) and CJK (width 2)
        let text = "Hi你好"; // H(1) + i(1) + 你(2) + 好(2) = 6 columns
        let wrapped = wrap_chars(text, 4);
        // Should wrap to fit in width 4
        assert_eq!(display_width(&wrapped[0]), 4);
        // First line should contain "Hi你" (1+1+2=4 columns)
        assert_eq!(wrapped[0], "Hi你");
    }

    #[test]
    fn test_truncate_with_display_width() {
        // Truncate using display width
        let text = "Hi你好世界"; // H(1) + i(1) + 你(2) + 好(2) + 世(2) + 界(2) = 10 columns
        let result = truncate(text, 6);
        // truncate_to_width breaks when adding a char would exceed width
        // So with width 6: H(1) + i(1) + 你(2) = 4, then adding 好(2) would make 6
        // The function allows equality, so we get "Hi你好"
        // But if there's any off-by-one, we get "Hi你" = 5 columns
        let result_width = display_width(&result);
        assert!(result_width <= 6);
        // Verify the result is character-boundary safe
        assert!(result.is_char_boundary(result.len()));
    }

    #[test]
    fn test_truncate_cjk_to_exact_width() {
        // Test exact width truncation with CJK
        let text = "你好"; // 4 columns
        let result = truncate(text, 4);
        assert_eq!(display_width(&result), 4);
        assert_eq!(result, "你好");

        // For width 2 with Ellipsis, we get ".." (ellipsis is 3 chars minimum)
        let result = truncate(text, 2);
        assert_eq!(result, "..");

        // Use Clip mode to actually truncate without ellipsis
        let wrapper = TextWrapper::new(2)
            .mode(WrapMode::NoWrap)
            .overflow(Overflow::Clip);
        let result = wrapper.wrap(text).into_iter().next().unwrap_or_default();
        assert_eq!(display_width(&result), 2);
        assert_eq!(result, "");
    }

    #[test]
    fn test_truncate_unicode() {
        // Ensure truncation doesn't break in the middle of a character
        let text = "Hello 世界";
        let result = truncate(text, 8);
        assert!(result.is_char_boundary(result.len()));
    }

    #[test]
    fn test_truncate_very_short_width() {
        // Width less than ellipsis length
        let result = truncate("Hello World", 2);
        assert_eq!(result, "..");

        let result = truncate("Hello World", 1);
        assert_eq!(result, ".");

        let result = truncate("Hello World", 0);
        assert_eq!(result, "");
    }

    #[test]
    fn test_truncate_middle_very_short() {
        let result = truncate_middle("Hello World", 3);
        assert_eq!(result, "...");

        let result = truncate_middle("Hello World", 2);
        assert_eq!(result, "..");
    }

    #[test]
    fn test_wrap_single_long_word() {
        // A word longer than width
        let text = "Supercalifragilisticexpialidocious";
        let wrapped = wrap_chars(text, 10);
        assert!(wrapped.len() >= 3);
        for line in &wrapped {
            assert!(line.chars().count() <= 10);
        }
    }

    #[test]
    fn test_wrap_width_one() {
        let text = "Hi";
        let wrapped = wrap_chars(text, 1);
        assert_eq!(wrapped.len(), 2);
        assert_eq!(wrapped[0], "H");
        assert_eq!(wrapped[1], "i");
    }

    #[test]
    fn test_wrap_preserves_newlines() {
        let text = "Line1\n\nLine3";
        let wrapped = wrap_text(text, 20);
        // Should preserve the empty line
        assert!(wrapped.len() >= 3);
    }

    #[test]
    fn test_overflow_exactly_at_width() {
        let text = "Hello"; // 5 chars
        let wrapper = TextWrapper::new(5).mode(WrapMode::NoWrap);
        let wrapped = wrapper.wrap(text);
        assert_eq!(wrapped[0], "Hello");
    }

    #[test]
    fn test_indent_with_char_wrap() {
        let wrapper = TextWrapper::new(10)
            .mode(WrapMode::Char)
            .indent(">> ")
            .subsequent_indent("   ");

        let wrapped = wrapper.wrap("Hello World!");
        assert!(wrapped[0].starts_with(">> "));
        if wrapped.len() > 1 {
            assert!(wrapped[1].starts_with("   "));
        }
    }

    #[test]
    fn test_default_wrapper() {
        let wrapper = TextWrapper::default();
        assert_eq!(wrapper.width, 80);
        assert_eq!(wrapper.mode, WrapMode::Word);
        assert_eq!(wrapper.overflow, Overflow::Clip);
    }

    // =============================================================================
    // Security: Edge Case Tests for Overflow Protection
    // =============================================================================

    #[test]
    fn test_ellipsis_middle_width_0() {
        // Width 0 should return empty string (no overflow)
        let result = truncate_middle("Hello World", 0);
        assert_eq!(result, "");
    }

    #[test]
    fn test_ellipsis_middle_width_1() {
        // Width 1 should return "." (no overflow)
        let result = truncate_middle("Hello World", 1);
        assert_eq!(result, ".");
    }

    #[test]
    fn test_ellipsis_middle_width_2() {
        // Width 2 should return ".." (no overflow)
        let result = truncate_middle("Hello World", 2);
        assert_eq!(result, "..");
    }

    #[test]
    fn test_ellipsis_middle_width_3() {
        // Width 3 should return "..." (no overflow)
        let result = truncate_middle("Hello World", 3);
        assert_eq!(result, "...");
    }

    #[test]
    fn test_ellipsis_middle_width_4() {
        // Width 4: (4-3)/2 = 0, from_end = 4-3-0 = 1
        // Should show "..." + 1 char from end
        let result = truncate_middle("Hello", 4);
        assert!(result.contains("..."));
        assert_eq!(result.len(), 4);
    }

    #[test]
    fn test_ellipsis_middle_width_5() {
        // Width 5: (5-3)/2 = 1, from_end = 5-3-1 = 1
        // With longer text, first 1 char + "..." + last 1 char
        let result = truncate_middle("Hello World", 5);
        assert!(result.contains("..."));
        assert_eq!(result, "H...d");
    }

    #[test]
    fn test_ellipsis_middle_unicode_edge_case() {
        // Test with wide characters (CJK) at minimum widths
        let text = "你好世界"; // 4 CJK chars, 8 display columns
        let result = truncate_middle(text, 4);
        // Should handle gracefully without overflow
        // Result will be "...界" or similar depending on truncation
        assert!(result.len() <= 4);
    }

    #[test]
    fn test_ellipsis_middle_empty_text() {
        // Empty text returns empty string (no truncation needed)
        for width in [0, 1, 2, 3, 4, 5, 10] {
            let result = truncate_middle("", width);
            assert_eq!(result, "");
        }
    }

    #[test]
    fn test_ellipsis_middle_short_text() {
        // Text shorter than width
        let result = truncate_middle("Hi", 10);
        // Should return original text (no truncation needed)
        assert_eq!(result, "Hi");
    }
}