vtcode-ui 0.159.1

Unified UI crate for VT Code: design system, theme registry, and TUI framework
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
//! URL and path-preserving text wrapping.
//!
//! Wraps text while keeping URLs and file paths as atomic units to preserve
//! terminal link detection and transcript file hit-testing.

use ratatui::prelude::*;
use ratatui::widgets::Paragraph;
use regex::Regex;
use std::borrow::Cow;
use std::sync::LazyLock;

/// URL/file token detection pattern - matches common URL formats and path-like tokens.
static PRESERVED_TOKEN_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r#"[a-zA-Z][a-zA-Z0-9+.-]*://[^\s<>\[\]{}|^]+|[a-zA-Z0-9][-a-zA-Z0-9]*\.[a-zA-Z]{2,}(/[^\s<>\[\]{}|^]*)?|localhost:\d+|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?|`(?:file://|~/|/|\./|\.\./|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/])[^`]+`|"(?:file://|~/|/|\./|\.\./|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/])[^"]+"|'(?:file://|~/|/|\./|\.\./|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/])[^']+'|(?:\./|\../|~/|/)[^\s<>\[\]{}|^]+|(?:[A-Za-z]:[\\/][^\s<>\[\]{}|^]+)|(?:[A-Za-z0-9._-]+[\\/][^\s<>\[\]{}|^]+)"#,
    )
    .expect("invalid URL/path token regex")
});

/// Check if text contains a preserved URL/path token.
fn contains_preserved_token(text: &str) -> bool {
    PRESERVED_TOKEN_PATTERN.is_match(text)
}

#[derive(Clone, Copy)]
struct SourceSpan {
    start: usize,
    end: usize,
    style: Style,
}

fn source_spans(line: &Line<'_>) -> Vec<SourceSpan> {
    let mut start = 0usize;
    let mut source_spans = Vec::with_capacity(line.spans.len());
    for span in &line.spans {
        let end = start.saturating_add(span.content.len());
        if start != end {
            source_spans.push(SourceSpan { start, end, style: span.style });
        }
        start = end;
    }
    source_spans
}

fn push_styled_span(spans: &mut Vec<Span<'static>>, text: &str, style: Style) {
    if text.is_empty() {
        return;
    }

    if let Some(last) = spans.last_mut().filter(|last| last.style == style) {
        last.content.to_mut().push_str(text);
    } else {
        spans.push(Span::styled(text.to_owned(), style));
    }
}

fn push_source_range(
    spans: &mut Vec<Span<'static>>,
    source_spans: &[SourceSpan],
    text: &str,
    start: usize,
    end: usize,
    fallback_style: Style,
) {
    let mut matched_source = false;
    let first_source = source_spans.partition_point(|source| source.end <= start);
    for source in source_spans.iter().skip(first_source) {
        if source.start >= end {
            break;
        }
        let fragment_start = start.max(source.start);
        let fragment_end = end.min(source.end);
        if fragment_start < fragment_end {
            push_styled_span(spans, &text[fragment_start..fragment_end], source.style);
            matched_source = true;
        }
    }

    if !matched_source {
        push_styled_span(spans, &text[start..end], fallback_style);
    }
}

/// Wrap a line, preserving URLs as atomic units.
///
/// - Lines without URLs: delegated to standard wrapping
/// - URL-only lines: returned unwrapped if they fit
/// - Mixed lines: URLs kept intact, surrounding text wrapped normally
pub(crate) fn wrap_line_preserving_urls(line: Line<'static>, max_width: usize) -> Vec<Line<'static>> {
    if max_width == 0 {
        return vec![Line::default()];
    }

    let text: Cow<'_, str> = match line.spans.as_slice() {
        [span] => span.content.clone(),
        _ => Cow::Owned(line.spans.iter().map(|s| s.content.as_ref()).collect()),
    };

    // No URLs - use standard wrapping (delegates to text_utils)
    if !contains_preserved_token(&text) {
        return super::text_utils::wrap_line(line, max_width);
    }

    // Find all preserved tokens in the text
    let urls: Vec<_> = PRESERVED_TOKEN_PATTERN
        .find_iter(&text)
        .map(|m| (m.start(), m.end(), m.as_str()))
        .collect();

    // Single URL that fits - return unwrapped for terminal link detection
    if urls.len() == 1
        && urls[0].0 == 0
        && urls[0].1 == text.len()
        && super::text_utils::display_width(&text) <= max_width
    {
        return vec![line];
    }
    // URL too wide - fall through to wrap it

    // Mixed content - split around URLs and wrap each segment.
    // For bullet / tree list items (e.g. "• Ran", "  └ ") preserve hanging
    // indent via the standard wrapper, which already handles bullet/tree
    // continuation. This fixes long tool headers like
    // "• Ran cat docs/guides/agent-loop-contract.md '2> /dev/null' ..." that
    // contain file paths and would otherwise lose hanging indent in the
    // URL-aware path. We sacrifice URL atomicity for these structured lines;
    // the hanging indent is more valuable for readability.
    let stripped = crate::tui::core_tui::session::text_utils::strip_ansi_codes(&text);
    let is_structured_bullet_or_tree = stripped.trim_start().starts_with("• ")
        || stripped.trim_start().starts_with("  â”” ")
        || stripped.trim_start().starts_with("  ├ ")
        || stripped.trim_start().starts_with("  │ ");
    if is_structured_bullet_or_tree {
        return super::text_utils::wrap_line(line, max_width);
    }
    wrap_mixed_content(line, &text, max_width, &urls)
}

/// Wrap text that contains URLs, keeping URLs intact.
fn wrap_mixed_content(
    line: Line<'static>,
    text: &str,
    max_width: usize,
    urls: &[(usize, usize, &str)],
) -> Vec<Line<'static>> {
    use unicode_segmentation::UnicodeSegmentation;

    let mut result = Vec::with_capacity(urls.len() + 1);
    let mut current_line: Vec<Span<'static>> = Vec::new();
    let mut current_width = 0usize;
    let mut text_pos = 0usize;
    let source_spans = source_spans(&line);
    let fallback_style = line.spans.first().map(|span| span.style).unwrap_or_default();

    fn trim_trailing_wrap_whitespace(spans: &mut Vec<Span<'static>>) {
        while let Some(last) = spans.last_mut() {
            let trimmed_len = last.content.trim_end_matches(char::is_whitespace).len();
            if trimmed_len == last.content.len() {
                break;
            }
            if trimmed_len == 0 {
                spans.pop();
                continue;
            }
            last.content.to_mut().truncate(trimmed_len);
            break;
        }
    }

    let flush_line = |spans: &mut Vec<Span<'static>>, result: &mut Vec<Line<'static>>| {
        if spans.is_empty() {
            result.push(Line::default());
        } else {
            trim_trailing_wrap_whitespace(spans);
            result.push(Line::from(std::mem::take(spans)));
        }
    };

    let push_wrapped_token = |token: &str,
                              token_start: usize,
                              current_line: &mut Vec<Span<'static>>,
                              current_width: &mut usize,
                              result: &mut Vec<Line<'static>>| {
        for (offset, grapheme) in UnicodeSegmentation::grapheme_indices(token, true) {
            let grapheme_width = super::text_utils::display_width(grapheme);
            let grapheme_start = token_start + offset;
            let grapheme_end = grapheme_start + grapheme.len();
            if grapheme_width == 0 {
                push_source_range(current_line, &source_spans, text, grapheme_start, grapheme_end, fallback_style);
                continue;
            }
            if *current_width + grapheme_width > max_width && *current_width > 0 {
                flush_line(current_line, result);
                *current_width = 0;
            }
            push_source_range(current_line, &source_spans, text, grapheme_start, grapheme_end, fallback_style);
            *current_width += grapheme_width;
        }
    };

    let push_wrapped_text = |segment: &str,
                             segment_start: usize,
                             current_line: &mut Vec<Span<'static>>,
                             current_width: &mut usize,
                             result: &mut Vec<Line<'static>>| {
        let mut piece_offset = 0usize;
        for piece in segment.split_inclusive('\n') {
            let mut piece_text = piece;
            let mut had_newline = false;
            if let Some(stripped) = piece_text.strip_suffix('\n') {
                piece_text = stripped;
                had_newline = true;
                if let Some(without_carriage) = piece_text.strip_suffix('\r') {
                    piece_text = without_carriage;
                }
            }

            let piece_start = segment_start + piece_offset;
            let mut token_offset = 0usize;
            for token in UnicodeSegmentation::split_word_bounds(piece_text) {
                if token.is_empty() {
                    continue;
                }

                let token_width = super::text_utils::display_width(token);
                let token_start = piece_start + token_offset;
                let token_end = token_start + token.len();
                token_offset += token.len();
                if token_width == 0 {
                    push_source_range(current_line, &source_spans, text, token_start, token_end, fallback_style);
                    continue;
                }

                let token_is_whitespace = token.chars().all(char::is_whitespace);
                let has_content = *current_width > 0;

                if token_is_whitespace && !result.is_empty() && !has_content {
                    continue;
                }

                if *current_width + token_width <= max_width {
                    push_source_range(current_line, &source_spans, text, token_start, token_end, fallback_style);
                    *current_width += token_width;
                    continue;
                }

                if token_is_whitespace {
                    if has_content {
                        flush_line(current_line, result);
                        *current_width = 0;
                    }
                    continue;
                }

                if token_width <= max_width {
                    if has_content {
                        flush_line(current_line, result);
                        *current_width = 0;
                    }
                    push_source_range(current_line, &source_spans, text, token_start, token_end, fallback_style);
                    *current_width += token_width;
                    continue;
                }

                push_wrapped_token(token, token_start, current_line, current_width, result);
            }

            if had_newline {
                flush_line(current_line, result);
                *current_width = 0;
            }
            piece_offset += piece.len();
        }
    };

    for (url_start, url_end, url_text) in urls {
        // Process text before this URL
        if *url_start > text_pos {
            push_wrapped_text(
                &text[text_pos..*url_start],
                text_pos,
                &mut current_line,
                &mut current_width,
                &mut result,
            );
        }

        // Add URL — keep atomic if it fits, otherwise break it across lines
        let url_width = super::text_utils::display_width(url_text);
        if url_width <= max_width {
            if current_width > 0 && current_width + url_width > max_width {
                flush_line(&mut current_line, &mut result);
                current_width = 0;
            }
            push_source_range(&mut current_line, &source_spans, text, *url_start, *url_end, fallback_style);
            current_width += url_width;
        } else {
            // URL is wider than max_width — break it grapheme-by-grapheme
            if current_width > 0 {
                flush_line(&mut current_line, &mut result);
                current_width = 0;
            }
            push_wrapped_token(url_text, *url_start, &mut current_line, &mut current_width, &mut result);
        }

        text_pos = *url_end;
    }

    // Process remaining text after last URL
    if text_pos < text.len() {
        push_wrapped_text(&text[text_pos..], text_pos, &mut current_line, &mut current_width, &mut result);
    }

    flush_line(&mut current_line, &mut result);
    if result.is_empty() {
        result.push(Line::default());
    }
    result
}

/// Wrap multiple lines with URL preservation.
pub(crate) fn wrap_lines_preserving_urls(lines: Vec<Line<'static>>, max_width: usize) -> Vec<Line<'static>> {
    if max_width == 0 {
        return vec![Line::default()];
    }
    lines
        .into_iter()
        .flat_map(|line| wrap_line_preserving_urls(line, max_width))
        .collect()
}

/// Calculate wrapped height using Paragraph::line_count.
pub fn calculate_wrapped_height(text: &str, width: u16) -> usize {
    if width == 0 {
        return text.lines().count().max(1);
    }
    Paragraph::new(text).line_count(width)
}

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

    #[test]
    fn test_url_detection() {
        assert!(contains_preserved_token("https://example.com"));
        assert!(contains_preserved_token("example.com/path"));
        assert!(contains_preserved_token("localhost:8080"));
        assert!(contains_preserved_token("192.168.1.1:8080"));
        assert!(!contains_preserved_token("not a url"));
    }

    #[test]
    fn test_file_path_detection() {
        assert!(contains_preserved_token("src/main.rs"));
        assert!(contains_preserved_token("./src/main.rs"));
        assert!(contains_preserved_token("/tmp/example.txt"));
        assert!(contains_preserved_token("\"./docs/My Notes.md\""));
        assert!(contains_preserved_token("`/Users/example/Library/Application Support/Code/User/settings.json`"));
    }

    #[test]
    fn test_url_only_preserved() {
        let line = Line::from(Span::raw("https://example.com"));
        let wrapped = wrap_line_preserving_urls(line, 80);
        assert_eq!(wrapped.len(), 1);
        assert!(wrapped[0].spans.iter().any(|s| s.content.contains("https://")));
    }

    #[test]
    fn test_mixed_content() {
        let line = Line::from(Span::raw("See https://example.com for info"));
        let wrapped = wrap_line_preserving_urls(line, 25);
        let all_text: String = wrapped
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
            .collect();
        assert!(all_text.contains("https://example.com"));
        assert!(all_text.contains("See"));
    }

    #[test]
    fn test_quoted_path_with_spaces_is_preserved() {
        let line = Line::from(Span::raw("Open \"./docs/My Notes.md\" for details"));
        let wrapped = wrap_line_preserving_urls(line, 18);
        let all_text: String = wrapped
            .iter()
            .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref()))
            .collect();

        assert!(all_text.contains("\"./docs/My Notes.md\""));
    }

    #[test]
    fn test_long_url_breaks_across_lines() {
        let long_url = "https://auth.openai.com/oauth/authorize?response_type=code&client_id=app_EMoamEEZ73f0CkXaXp7hrann&redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback&scope=openid";
        let line = Line::from(Span::raw(long_url.to_string()));
        let wrapped = wrap_line_preserving_urls(line, 80);
        assert!(wrapped.len() > 1, "Long URL should wrap across multiple lines");
        let all_text: String = wrapped
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
            .collect();
        assert_eq!(all_text, long_url, "All characters should be preserved");
    }

    #[test]
    fn test_no_url_delegates() {
        let line = Line::from(Span::raw("Regular text without URLs"));
        let wrapped = wrap_line_preserving_urls(line, 10);
        assert!(!wrapped.is_empty());
    }

    #[test]
    fn test_mixed_content_prefers_word_boundaries_around_urls() {
        let line = Line::from(Span::raw("alpha https://x.io beta gamma"));
        let wrapped = wrap_line_preserving_urls(line, 12);
        let rendered: Vec<String> = wrapped
            .iter()
            .map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect())
            .collect();

        assert_eq!(
            rendered,
            vec![
                "alpha".to_string(),
                "https://x.io".to_string(),
                "beta gamma".to_string()
            ]
        );
    }

    #[test]
    fn mixed_url_wrapping_preserves_each_source_span_style() {
        let before_style = Style::default().fg(Color::Red);
        let url_scheme_style = Style::default().fg(Color::Blue);
        let url_path_style = Style::default().fg(Color::Green);
        let after_style = Style::default().fg(Color::Yellow);
        let line = Line::from(vec![
            Span::styled("open ", before_style),
            Span::styled("https://example.", url_scheme_style),
            Span::styled("com/path", url_path_style),
            Span::styled(" now", after_style),
        ]);

        let wrapped = wrap_line_preserving_urls(line, 80);
        assert_eq!(wrapped.len(), 1);
        assert_eq!(
            wrapped[0]
                .spans
                .iter()
                .map(|span| (span.content.as_ref(), span.style))
                .collect::<Vec<_>>(),
            vec![
                ("open ", before_style),
                ("https://example.", url_scheme_style),
                ("com/path", url_path_style),
                (" now", after_style),
            ]
        );
    }
}