termtui 0.1.0

A framework for building beautiful, responsive terminal user interfaces with a DOM-style hierarchical approach
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! Utility functions for terminal rendering and text manipulation.
//!
//! This module provides helper functions for various terminal rendering tasks,
//! including calculating the display width of Unicode strings and characters,
//! and text wrapping algorithms for fitting text within width constraints.

use crate::style::TextWrap;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

//--------------------------------------------------------------------------------------------------
// Macros: Debug Logging
//--------------------------------------------------------------------------------------------------

/// Debug logging macro that only compiles in debug builds.
/// Writes timestamped messages to /tmp/radical_debug.log
#[cfg(debug_assertions)]
#[macro_export]
macro_rules! debug_log {
    ($($arg:tt)*) => {
        {
            use std::fs::OpenOptions;
            use std::io::Write;
            if let Ok(mut file) = OpenOptions::new()
                .create(true)
                .write(true)
                .append(true)
                .open("/tmp/radical_debug.log")
            {
                let timestamp = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_millis();
                let _ = writeln!(file, "[{}] {}", timestamp, format!($($arg)*));
            }
        }
    };
}

/// No-op version for release builds
#[cfg(not(debug_assertions))]
#[macro_export]
macro_rules! debug_log {
    ($($arg:tt)*) => {};
}

//--------------------------------------------------------------------------------------------------
// Functions: Display Width
//--------------------------------------------------------------------------------------------------

/// Returns the display width of a string in terminal columns.
///
/// This accounts for:
/// - Wide characters (CJK, emojis) that take 2 columns
/// - Zero-width characters (combining marks) that take 0 columns
/// - Control characters are handled as per unicode-width rules
pub fn display_width(s: &str) -> usize {
    UnicodeWidthStr::width(s)
}

/// Returns the display width of a character in terminal columns.
///
/// Returns:
/// - 0 for zero-width characters and control characters
/// - 1 for regular characters
/// - 2 for wide characters (CJK, full-width, emojis)
pub fn char_width(c: char) -> usize {
    UnicodeWidthChar::width(c).unwrap_or(0)
}

/// Truncates a string to fit within the specified display width.
///
/// Returns a substring that fits within max_width columns when displayed.
/// If the string needs to be truncated at a wide character boundary,
/// the wide character is excluded to avoid exceeding the width.
pub fn truncate_to_width(s: &str, max_width: usize) -> &str {
    if max_width == 0 {
        return "";
    }

    let mut width = 0;
    let mut end_byte = 0;

    for (byte_idx, ch) in s.char_indices() {
        let ch_width = char_width(ch);

        if width + ch_width > max_width {
            break;
        }

        width += ch_width;
        end_byte = byte_idx + ch.len_utf8();
    }

    &s[..end_byte]
}

/// Calculates the byte index in a string that corresponds to a given display column.
///
/// This is useful for cursor positioning and text selection.
/// Returns None if the column is beyond the string's display width.
pub fn byte_index_from_column(s: &str, target_column: usize) -> Option<usize> {
    let mut current_column = 0;

    for (byte_idx, ch) in s.char_indices() {
        if current_column == target_column {
            return Some(byte_idx);
        }

        let ch_width = char_width(ch);
        if current_column + ch_width > target_column {
            // Target column falls in the middle of a wide character
            return None;
        }

        current_column += ch_width;
    }

    // If we've reached the end and the column matches, return the string length
    if current_column == target_column {
        Some(s.len())
    } else {
        None
    }
}

/// Pads a string with spaces to reach the specified display width.
///
/// If the string is already wider than the target width, it's returned as-is.
pub fn pad_to_width(s: &str, target_width: usize) -> String {
    let current_width = display_width(s);

    if current_width >= target_width {
        s.to_string()
    } else {
        let padding = target_width - current_width;
        format!("{}{}", s, " ".repeat(padding))
    }
}

/// Extracts a substring based on display column positions.
///
/// Returns a substring that starts at `start_col` and ends at `end_col` display columns.
/// Handles multibyte UTF-8 characters correctly. If a wide character spans the boundary,
/// it is excluded to maintain valid UTF-8.
pub fn substring_by_columns(s: &str, start_col: usize, end_col: usize) -> &str {
    if start_col >= end_col {
        return "";
    }

    let mut current_col = 0;
    let mut start_byte = None;
    let mut end_byte = s.len();

    for (byte_idx, ch) in s.char_indices() {
        let ch_width = char_width(ch);

        // Find start byte index
        if start_byte.is_none() {
            if current_col >= start_col {
                start_byte = Some(byte_idx);
            } else if current_col + ch_width > start_col {
                // Wide character spans the start boundary, start after it
                start_byte = Some(byte_idx + ch.len_utf8());
            }
        }

        // Find end byte index
        if current_col >= end_col {
            end_byte = byte_idx;
            break;
        } else if current_col + ch_width > end_col {
            // Wide character spans the end boundary, end before it
            end_byte = byte_idx;
            break;
        }

        current_col += ch_width;
    }

    let start = start_byte.unwrap_or(s.len());
    if start >= end_byte {
        ""
    } else {
        &s[start..end_byte]
    }
}

//--------------------------------------------------------------------------------------------------
// Functions: Text Wrapping
//--------------------------------------------------------------------------------------------------

/// Wraps text according to the specified mode and width constraint.
///
/// Returns a vector of lines that fit within the given width.
/// Empty lines are preserved in the output.
pub fn wrap_text(text: &str, width: u16, mode: TextWrap) -> Vec<String> {
    if width == 0 {
        return vec![];
    }

    match mode {
        TextWrap::None => {
            // No wrapping - return original text as single line
            vec![text.to_string()]
        }
        TextWrap::Character => {
            // Break at any character boundary
            wrap_character(text, width)
        }
        TextWrap::Word => {
            // Break at word boundaries only
            wrap_word(text, width)
        }
        TextWrap::WordBreak => {
            // Try word boundaries first, break words if necessary
            wrap_word_break(text, width)
        }
    }
}

/// Wraps text at character boundaries.
///
/// Breaks the text based on display width, accounting for wide characters.
fn wrap_character(text: &str, width: u16) -> Vec<String> {
    let width = width as usize;
    let mut lines = Vec::new();

    if text.is_empty() {
        return vec![String::new()];
    }

    let mut current_line = String::new();
    let mut current_width = 0;

    for ch in text.chars() {
        let ch_width = char_width(ch);

        if current_width + ch_width > width && !current_line.is_empty() {
            // Start a new line
            lines.push(current_line);
            current_line = String::new();
            current_width = 0;
        }

        // Add character if it fits (or if line is empty to avoid infinite loop)
        if current_width + ch_width <= width || current_line.is_empty() {
            current_line.push(ch);
            current_width += ch_width;
        } else {
            // Character doesn't fit even on empty line (width too small for wide char)
            // Start next line with this character
            lines.push(current_line);
            current_line = ch.to_string();
            current_width = ch_width;
        }
    }

    if !current_line.is_empty() {
        lines.push(current_line);
    }

    lines
}

/// Wraps text at word boundaries.
///
/// Attempts to break lines at spaces and other word boundaries.
/// If a word is longer than the line width, it will overflow.
/// Preserves all spaces (leading, trailing, and in-between).
fn wrap_word(text: &str, width: u16) -> Vec<String> {
    let width = width as usize;
    let mut lines = Vec::new();
    let mut current_line = String::new();
    let mut current_width = 0;

    // Process character by character to preserve all spaces
    let mut in_word = false;
    let mut word = String::new();
    let mut word_width = 0;
    let mut pending_spaces = String::new();
    let mut pending_spaces_width = 0;

    for ch in text.chars() {
        if ch.is_whitespace() {
            // Handle any accumulated word first
            if in_word {
                // Check if word fits on current line
                if current_width == 0 {
                    // First content on line
                    current_line.push_str(&word);
                    current_width = word_width;
                } else if current_width + word_width <= width {
                    // Word fits on current line
                    current_line.push_str(&word);
                    current_width += word_width;
                } else {
                    // Word doesn't fit, start new line
                    lines.push(current_line.clone());
                    current_line = word.clone();
                    current_width = word_width;
                }
                word.clear();
                word_width = 0;
                in_word = false;
            }

            // Now accumulate the space
            pending_spaces.push(ch);
            pending_spaces_width += char_width(ch);
        } else {
            // Non-whitespace character

            // If we have pending spaces, handle them first
            if !pending_spaces.is_empty() {
                // Check if spaces fit on current line
                if current_width + pending_spaces_width <= width {
                    current_line.push_str(&pending_spaces);
                    current_width += pending_spaces_width;
                } else {
                    // Spaces don't fit, wrap to new line
                    // But only if we have content on the current line
                    if current_width > 0 {
                        lines.push(current_line.clone());
                        current_line = pending_spaces.clone();
                        current_width = pending_spaces_width;
                    } else {
                        // Line is empty, add the spaces anyway
                        current_line.push_str(&pending_spaces);
                        current_width = pending_spaces_width;
                    }
                }
                pending_spaces.clear();
                pending_spaces_width = 0;
            }

            // Start or continue building a word
            in_word = true;
            word.push(ch);
            word_width += char_width(ch);
        }
    }

    // Handle any remaining word
    if in_word {
        if current_width == 0 || current_width + word_width <= width {
            current_line.push_str(&word);
        } else {
            lines.push(current_line.clone());
            current_line = word;
        }
    }

    // Handle any trailing spaces
    if !pending_spaces.is_empty() {
        if current_width + pending_spaces_width <= width {
            current_line.push_str(&pending_spaces);
        } else if current_width > 0 {
            lines.push(current_line.clone());
            current_line = pending_spaces;
        } else {
            current_line.push_str(&pending_spaces);
        }
    }

    // Add the last line
    if !current_line.is_empty() || lines.is_empty() {
        lines.push(current_line);
    }

    lines
}

/// Wraps text at word boundaries, breaking words if necessary.
///
/// First attempts to break at word boundaries. If a word is longer than
/// the line width, it breaks the word at character boundaries considering display width.
fn wrap_word_break(text: &str, width: u16) -> Vec<String> {
    let width = width as usize;
    let mut lines = Vec::new();
    let mut current_line = String::new();
    let mut current_width = 0;

    // Process text character by character to preserve spaces
    let chars = text.chars();
    let mut in_word = false;
    let mut word = String::new();
    let mut word_width = 0;

    for ch in chars {
        if ch.is_whitespace() {
            // Handle any accumulated word first
            if in_word {
                // Try to add the word to current line
                if current_width == 0 {
                    // First word on line
                    if word_width <= width {
                        current_line.push_str(&word);
                        current_width = word_width;
                    } else {
                        // Word too long, break it
                        for word_ch in word.chars() {
                            let ch_width = char_width(word_ch);
                            if current_width + ch_width > width && current_width > 0 {
                                lines.push(current_line.clone());
                                current_line.clear();
                                current_width = 0;
                            }
                            current_line.push(word_ch);
                            current_width += ch_width;
                        }
                    }
                } else if current_width + word_width <= width {
                    // Word fits on current line
                    current_line.push_str(&word);
                    current_width += word_width;
                } else {
                    // Word doesn't fit, start new line
                    lines.push(current_line.clone());
                    current_line.clear();
                    current_width = 0;

                    // Add word to new line (possibly breaking it)
                    if word_width <= width {
                        current_line.push_str(&word);
                        current_width = word_width;
                    } else {
                        // Break the word
                        for word_ch in word.chars() {
                            let ch_width = char_width(word_ch);
                            if current_width + ch_width > width && current_width > 0 {
                                lines.push(current_line.clone());
                                current_line.clear();
                                current_width = 0;
                            }
                            current_line.push(word_ch);
                            current_width += ch_width;
                        }
                    }
                }

                word.clear();
                word_width = 0;
                in_word = false;
            }

            // Now handle the whitespace character
            let ch_width = char_width(ch);
            if current_width + ch_width > width && current_width > 0 {
                // Whitespace would exceed width, start new line
                lines.push(current_line.clone());
                current_line.clear();
                // Always preserve the whitespace character, even at line start
                current_line.push(ch);
                current_width = ch_width;
            } else {
                // Add the whitespace character
                current_line.push(ch);
                current_width += ch_width;
            }
        } else {
            // Non-whitespace character - accumulate in word
            in_word = true;
            word.push(ch);
            word_width += char_width(ch);
        }
    }

    // Handle any remaining word
    if in_word {
        if current_width == 0 {
            // First word on line
            if word_width <= width {
                current_line.push_str(&word);
            } else {
                // Word too long, break it
                for word_ch in word.chars() {
                    let ch_width = char_width(word_ch);
                    if current_width + ch_width > width && current_width > 0 {
                        lines.push(current_line.clone());
                        current_line.clear();
                        current_width = 0;
                    }
                    current_line.push(word_ch);
                    current_width += ch_width;
                }
            }
        } else if current_width + word_width <= width {
            // Word fits on current line
            current_line.push_str(&word);
        } else {
            // Word doesn't fit, start new line
            lines.push(current_line.clone());
            current_line.clear();

            // Add word to new line (possibly breaking it)
            if word_width <= width {
                current_line = word;
            } else {
                // Break the word
                current_width = 0;
                for word_ch in word.chars() {
                    let ch_width = char_width(word_ch);
                    if current_width + ch_width > width && current_width > 0 {
                        lines.push(current_line.clone());
                        current_line.clear();
                        current_width = 0;
                    }
                    current_line.push(word_ch);
                    current_width += ch_width;
                }
            }
        }
    }

    // Add the last line if not empty
    if !current_line.is_empty() {
        lines.push(current_line);
    } else if lines.is_empty() {
        // Handle empty text
        lines.push(String::new());
    }

    lines
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

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

    //----------------------------------------------------------------------------------------------
    // Tests: Display Width Functions
    //----------------------------------------------------------------------------------------------

    #[test]
    fn test_display_width_ascii() {
        assert_eq!(display_width("Hello"), 5);
        assert_eq!(display_width(""), 0);
        assert_eq!(display_width("Test 123"), 8);
    }

    #[test]
    fn test_display_width_unicode() {
        // CJK characters (2 width each)
        assert_eq!(display_width("世界"), 4);
        assert_eq!(display_width("Hello 世界"), 10);

        // Emoji (typically 2 width)
        assert_eq!(display_width("😀"), 2);
        assert_eq!(display_width("Test 😀"), 7);
    }

    #[test]
    fn test_char_width() {
        assert_eq!(char_width('A'), 1);
        assert_eq!(char_width(''), 2);
        assert_eq!(char_width('😀'), 2);
        assert_eq!(char_width('\0'), 0); // Control character
    }

    #[test]
    fn test_truncate_to_width() {
        assert_eq!(truncate_to_width("Hello World", 5), "Hello");
        assert_eq!(truncate_to_width("Hello", 10), "Hello");

        // Wide characters
        assert_eq!(truncate_to_width("Hello 世界", 7), "Hello ");
        assert_eq!(truncate_to_width("世界", 2), "");
        assert_eq!(truncate_to_width("世界", 3), ""); // Can't fit the second char
        assert_eq!(truncate_to_width("世界", 4), "世界");
    }

    #[test]
    fn test_byte_index_from_column() {
        let text = "Hello";
        assert_eq!(byte_index_from_column(text, 0), Some(0));
        assert_eq!(byte_index_from_column(text, 3), Some(3));
        assert_eq!(byte_index_from_column(text, 5), Some(5));
        assert_eq!(byte_index_from_column(text, 6), None);

        // Wide characters
        let text = "世界";
        assert_eq!(byte_index_from_column(text, 0), Some(0));
        assert_eq!(byte_index_from_column(text, 1), None); // Middle of first char
        assert_eq!(byte_index_from_column(text, 2), Some(3)); // After first char
        assert_eq!(byte_index_from_column(text, 4), Some(6)); // End of string
    }

    #[test]
    fn test_pad_to_width() {
        assert_eq!(pad_to_width("Hi", 5), "Hi   ");
        assert_eq!(pad_to_width("Hello", 5), "Hello");
        assert_eq!(pad_to_width("Hello", 3), "Hello");

        // With wide characters
        assert_eq!(pad_to_width("", 5), "");
        assert_eq!(pad_to_width("Hi世", 6), "Hi世  ");
    }

    #[test]
    fn test_substring_by_columns() {
        // ASCII tests
        assert_eq!(substring_by_columns("Hello World", 0, 5), "Hello");
        assert_eq!(substring_by_columns("Hello World", 6, 11), "World");
        assert_eq!(substring_by_columns("Hello World", 3, 8), "lo Wo");

        // Wide character tests
        assert_eq!(substring_by_columns("Hello 世界", 0, 6), "Hello ");
        assert_eq!(substring_by_columns("Hello 世界", 6, 10), "世界");
        assert_eq!(substring_by_columns("Hello 世界", 0, 8), "Hello 世");
        assert_eq!(substring_by_columns("Hello 世界", 7, 10), ""); // Start in middle of 世
        assert_eq!(substring_by_columns("Hello 世界", 0, 7), "Hello "); // End in middle of 世

        // Emoji tests
        assert_eq!(substring_by_columns("Test😀End", 0, 4), "Test");
        assert_eq!(substring_by_columns("Test😀End", 4, 6), "😀");
        assert_eq!(substring_by_columns("Test😀End", 6, 9), "End");
        assert_eq!(substring_by_columns("Test😀End", 0, 5), "Test"); // End in middle of emoji
        assert_eq!(substring_by_columns("Test😀End", 5, 9), "End"); // Start in middle of emoji

        // Edge cases
        assert_eq!(substring_by_columns("", 0, 5), "");
        assert_eq!(substring_by_columns("Hello", 5, 5), "");
        assert_eq!(substring_by_columns("Hello", 10, 20), "");
    }

    //----------------------------------------------------------------------------------------------
    // Tests: Text Wrapping Functions
    //----------------------------------------------------------------------------------------------

    #[test]
    fn test_wrap_none() {
        let text = "This is a very long line that should not be wrapped";
        let wrapped = wrap_text(text, 10, TextWrap::None);
        assert_eq!(wrapped, vec![text]);
    }

    #[test]
    fn test_wrap_character() {
        let text = "Hello World";
        let wrapped = wrap_text(text, 5, TextWrap::Character);
        assert_eq!(wrapped, vec!["Hello", " Worl", "d"]);
    }

    #[test]
    fn test_wrap_character_exact() {
        let text = "12345678901234567890";
        let wrapped = wrap_text(text, 10, TextWrap::Character);
        assert_eq!(wrapped, vec!["1234567890", "1234567890"]);
    }

    #[test]
    fn test_wrap_word() {
        let text = "The quick brown fox jumps";
        let wrapped = wrap_text(text, 10, TextWrap::Word);
        assert_eq!(wrapped, vec!["The quick ", "brown fox ", "jumps"]);
    }

    #[test]
    fn test_wrap_word_long_word() {
        let text = "A verylongword that exceeds width";
        let wrapped = wrap_text(text, 10, TextWrap::Word);
        // Long word overflows in Word mode, spaces are preserved
        assert_eq!(
            wrapped,
            vec!["A ", "verylongword", " that ", "exceeds ", "width"]
        );
    }

    #[test]
    fn test_wrap_word_break() {
        let text = "A verylongword that exceeds";
        let wrapped = wrap_text(text, 10, TextWrap::WordBreak);
        assert_eq!(wrapped, vec!["A ", "verylongwo", "rd that ", "exceeds"]);
    }

    #[test]
    fn test_wrap_word_break_preserves_leading_spaces() {
        let text = "        _ => calculate";
        let wrapped = wrap_text(text, 15, TextWrap::WordBreak);
        assert_eq!(wrapped, vec!["        _ => ", "calculate"]);
    }

    #[test]
    fn test_wrap_empty_text() {
        assert_eq!(wrap_text("", 10, TextWrap::Character), vec![""]);
        assert_eq!(wrap_text("", 10, TextWrap::Word), vec![""]);
        assert_eq!(wrap_text("", 10, TextWrap::WordBreak), vec![""]);
    }

    #[test]
    fn test_wrap_zero_width() {
        let text = "Hello";
        assert_eq!(
            wrap_text(text, 0, TextWrap::Character),
            Vec::<String>::new()
        );
        assert_eq!(wrap_text(text, 0, TextWrap::Word), Vec::<String>::new());
    }

    #[test]
    fn test_wrap_unicode() {
        // Note: 世 and 界 are each 2 display width
        let text = "Hello 世界";
        let wrapped = wrap_text(text, 8, TextWrap::Character);
        assert_eq!(wrapped, vec!["Hello 世", ""]); // "Hello " = 6, "世" = 2

        let wrapped = wrap_text(text, 7, TextWrap::Character);
        assert_eq!(wrapped, vec!["Hello ", "世界"]); // Can't fit 世 with Hello in 7 width

        // Test word wrapping with Unicode
        let text = "Hello 世界 World";
        let wrapped = wrap_text(text, 10, TextWrap::Word);
        assert_eq!(wrapped, vec!["Hello 世界", " World"]); // "Hello " = 6, "世界" = 4, space goes to next line
    }

    #[test]
    fn test_wrap_emoji() {
        // Emoji typically have width 2
        let text = "Test 😀 emoji";
        let wrapped = wrap_text(text, 8, TextWrap::Character);
        assert_eq!(wrapped, vec!["Test 😀 ", "emoji"]); // "Test " = 5, "😀" = 2, " " = 1

        let wrapped = wrap_text(text, 7, TextWrap::Word);
        assert_eq!(wrapped, vec!["Test 😀", " emoji"]); // "Test " = 5, "😀" = 2, space goes to next line
    }

    #[test]
    fn test_wrap_word_multiple_spaces() {
        let text = "Hello     World   Test";
        let wrapped = wrap_text(text, 10, TextWrap::Word);
        // Spaces should be preserved
        assert_eq!(wrapped, vec!["Hello     ", "World   ", "Test"]);
    }

    #[test]
    fn test_wrap_preserves_leading_spaces() {
        let text = "    Hello World";
        let wrapped = wrap_text(text, 10, TextWrap::Word);
        assert_eq!(wrapped, vec!["    Hello ", "World"]);
    }

    #[test]
    fn test_wrap_preserves_trailing_spaces() {
        let text = "Hello World    ";
        let wrapped = wrap_text(text, 10, TextWrap::Word);
        assert_eq!(wrapped, vec!["Hello ", "World    "]);
    }
}