Skip to main content

vtcode_commons/
preview.rs

1//! Shared preview formatting helpers.
2
3use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
4
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6pub struct HeadTailPreview<'a, T> {
7    pub head: &'a [T],
8    pub tail: &'a [T],
9    pub hidden_count: usize,
10    pub total: usize,
11}
12
13#[derive(Clone, Debug, Eq, PartialEq)]
14pub struct TextLineExcerpt<'a> {
15    pub head: Vec<&'a str>,
16    pub tail: Vec<&'a str>,
17    pub hidden_count: usize,
18    pub total: usize,
19}
20
21pub fn display_width(text: &str) -> usize {
22    UnicodeWidthStr::width(text)
23}
24
25pub fn truncate_to_display_width(text: &str, max_width: usize) -> &str {
26    if max_width == 0 {
27        return "";
28    }
29    if display_width(text) <= max_width {
30        return text;
31    }
32
33    let mut consumed_width = 0usize;
34    for (idx, ch) in text.char_indices() {
35        let char_width = UnicodeWidthChar::width(ch).unwrap_or(0);
36        if consumed_width + char_width > max_width {
37            return &text[..idx];
38        }
39        consumed_width += char_width;
40    }
41
42    text
43}
44
45pub fn truncate_with_ellipsis(text: &str, max_width: usize, ellipsis: &str) -> String {
46    if max_width == 0 {
47        return String::new();
48    }
49    if display_width(text) <= max_width {
50        return text.to_string();
51    }
52
53    let ellipsis_width = display_width(ellipsis);
54    if ellipsis_width >= max_width {
55        return truncate_to_display_width(ellipsis, max_width).to_string();
56    }
57
58    let truncated = truncate_to_display_width(text, max_width - ellipsis_width);
59    format!("{truncated}{ellipsis}")
60}
61
62pub fn pad_to_display_width(text: &str, width: usize, pad_char: char) -> String {
63    let current = display_width(text);
64    if current >= width {
65        return text.to_string();
66    }
67
68    let padding = pad_char.to_string().repeat(width - current);
69    format!("{text}{padding}")
70}
71
72pub fn suffix_for_display_width(value: &str, max_width: usize) -> &str {
73    if display_width(value) <= max_width {
74        return value;
75    }
76    if max_width == 0 {
77        return "";
78    }
79
80    let mut consumed_width = 0usize;
81    let mut start_idx = value.len();
82    for (idx, ch) in value.char_indices().rev() {
83        let char_width = UnicodeWidthChar::width(ch).unwrap_or(0);
84        if consumed_width + char_width > max_width {
85            break;
86        }
87        consumed_width += char_width;
88        start_idx = idx;
89    }
90
91    &value[start_idx..]
92}
93
94pub fn format_hidden_lines_summary(hidden: usize) -> String {
95    if hidden == 1 {
96        "… +1 line".to_string()
97    } else {
98        format!("… +{hidden} lines")
99    }
100}
101
102pub fn split_head_tail_preview<'a, T>(items: &'a [T], head: usize, tail: usize) -> HeadTailPreview<'a, T> {
103    let total = items.len();
104    if total <= head.saturating_add(tail) {
105        return HeadTailPreview {
106            head: items,
107            tail: &items[total..],
108            hidden_count: 0,
109            total,
110        };
111    }
112
113    let head_count = head.min(total);
114    let tail_count = tail.min(total.saturating_sub(head_count));
115    let hidden_count = total.saturating_sub(head_count + tail_count);
116
117    HeadTailPreview {
118        head: &items[..head_count],
119        tail: &items[total - tail_count..],
120        hidden_count,
121        total,
122    }
123}
124
125pub fn split_head_tail_preview_with_limit<'a, T>(
126    items: &'a [T],
127    limit: usize,
128    preferred_head: usize,
129) -> HeadTailPreview<'a, T> {
130    if limit == 0 {
131        return HeadTailPreview {
132            head: &items[..0],
133            tail: &items[..0],
134            hidden_count: items.len(),
135            total: items.len(),
136        };
137    }
138
139    if items.len() <= limit {
140        return HeadTailPreview {
141            head: items,
142            tail: &items[items.len()..],
143            hidden_count: 0,
144            total: items.len(),
145        };
146    }
147
148    let (head, tail) = summary_window(limit, preferred_head);
149    split_head_tail_preview(items, head, tail)
150}
151
152pub fn summary_window(limit: usize, preferred_head: usize) -> (usize, usize) {
153    if limit <= 2 {
154        return (0, limit);
155    }
156
157    let head = preferred_head.min((limit - 1) / 2).max(1);
158    let tail = limit.saturating_sub(head + 1).max(1);
159    (head, tail)
160}
161
162pub fn excerpt_text_lines<'a>(text: &'a str, head: usize, tail: usize) -> TextLineExcerpt<'a> {
163    let lines: Vec<&str> = text.lines().collect();
164    let total = lines.len();
165    if total <= head.saturating_add(tail) {
166        return TextLineExcerpt {
167            head: lines,
168            tail: Vec::new(),
169            hidden_count: 0,
170            total,
171        };
172    }
173
174    let head_count = head.min(total);
175    let tail_count = tail.min(total.saturating_sub(head_count));
176    let hidden_count = total.saturating_sub(head_count + tail_count);
177
178    TextLineExcerpt {
179        head: lines[..head_count].to_vec(),
180        tail: lines[total - tail_count..].to_vec(),
181        hidden_count,
182        total,
183    }
184}
185
186pub fn excerpt_text_lines_with_limit<'a>(text: &'a str, limit: usize, preferred_head: usize) -> TextLineExcerpt<'a> {
187    let lines: Vec<&str> = text.lines().collect();
188    let preview = split_head_tail_preview_with_limit(lines.as_slice(), limit, preferred_head);
189
190    TextLineExcerpt {
191        head: preview.head.to_vec(),
192        tail: preview.tail.to_vec(),
193        hidden_count: preview.hidden_count,
194        total: preview.total,
195    }
196}
197
198pub fn format_hidden_bytes_summary(hidden: usize) -> String {
199    format!("… [{hidden} bytes omitted] …")
200}
201
202pub fn condense_text_bytes(content: &str, head_bytes: usize, tail_bytes: usize) -> String {
203    let byte_len = content.len();
204    let max_inline = head_bytes + tail_bytes;
205    if byte_len <= max_inline {
206        return content.to_string();
207    }
208
209    let head_end = floor_char_boundary(content, head_bytes);
210    let tail_start_raw = byte_len.saturating_sub(tail_bytes);
211    let tail_start = ceil_char_boundary(content, tail_start_raw);
212
213    let omitted = byte_len.saturating_sub(head_end).saturating_sub(byte_len - tail_start);
214
215    format!("{}\n\n{}\n\n{}", &content[..head_end], format_hidden_bytes_summary(omitted), &content[tail_start..])
216}
217
218pub fn tail_preview_text(content: &str, tail_bytes: usize, max_lines: usize) -> String {
219    if content.is_empty() {
220        return String::new();
221    }
222
223    let tail_start = ceil_char_boundary(content, content.len().saturating_sub(tail_bytes));
224    let tail_slice = &content[tail_start..];
225
226    let mut line_start = 0usize;
227    if max_lines > 0 {
228        let mut seen = 0usize;
229        for (idx, b) in tail_slice.as_bytes().iter().enumerate().rev() {
230            if *b == b'\n' {
231                seen += 1;
232                if seen >= max_lines {
233                    line_start = idx.saturating_add(1);
234                    break;
235                }
236            }
237        }
238    }
239
240    let preview = &tail_slice[line_start..];
241    let omitted = tail_start.saturating_add(line_start);
242    if omitted == 0 {
243        return preview.to_string();
244    }
245
246    format!("{}\n{}", format_hidden_bytes_summary(omitted), preview)
247}
248
249fn floor_char_boundary(value: &str, index: usize) -> usize {
250    if index >= value.len() {
251        return value.len();
252    }
253
254    let mut i = index;
255    while i > 0 && !value.is_char_boundary(i) {
256        i -= 1;
257    }
258    i
259}
260
261fn ceil_char_boundary(value: &str, index: usize) -> usize {
262    if index >= value.len() {
263        return value.len();
264    }
265
266    let mut i = index;
267    while i < value.len() && !value.is_char_boundary(i) {
268        i += 1;
269    }
270    i
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    #[test]
278    fn truncate_to_display_width_respects_wide_chars() {
279        let value = "表表表";
280        assert_eq!(truncate_to_display_width(value, 5), "表表");
281    }
282
283    #[test]
284    fn truncate_with_ellipsis_respects_width_budget() {
285        assert_eq!(truncate_with_ellipsis("abcdef", 4, "…"), "abc…");
286    }
287
288    #[test]
289    fn pad_to_display_width_handles_wide_chars() {
290        let padded = pad_to_display_width("表", 4, ' ');
291        assert_eq!(display_width(padded.as_str()), 4);
292    }
293
294    #[test]
295    fn suffix_for_display_width_preserves_tail() {
296        assert_eq!(suffix_for_display_width("hello/world.rs", 8), "world.rs");
297    }
298
299    #[test]
300    fn split_head_tail_preview_preserves_hidden_count() {
301        let items = [1, 2, 3, 4, 5, 6, 7];
302        let preview = split_head_tail_preview(&items, 2, 2);
303        assert_eq!(preview.head, &[1, 2]);
304        assert_eq!(preview.tail, &[6, 7]);
305        assert_eq!(preview.hidden_count, 3);
306        assert_eq!(preview.total, 7);
307    }
308
309    #[test]
310    fn split_head_tail_preview_keeps_short_input_intact() {
311        let items = [1, 2, 3];
312        let preview = split_head_tail_preview(&items, 2, 2);
313        assert_eq!(preview.head, &[1, 2, 3]);
314        assert!(preview.tail.is_empty());
315        assert_eq!(preview.hidden_count, 0);
316    }
317
318    #[test]
319    fn split_head_tail_preview_with_limit_preserves_total_and_gap() {
320        let items = [1, 2, 3, 4, 5, 6, 7];
321        let preview = split_head_tail_preview_with_limit(&items, 6, 3);
322        assert_eq!(preview.head, &[1, 2]);
323        assert_eq!(preview.tail, &[5, 6, 7]);
324        assert_eq!(preview.hidden_count, 2);
325        assert_eq!(preview.total, 7);
326    }
327
328    #[test]
329    fn summary_window_reserves_gap_row() {
330        assert_eq!(summary_window(6, 3), (2, 3));
331        assert_eq!(summary_window(2, 3), (0, 2));
332    }
333
334    #[test]
335    fn hidden_lines_summary_matches_existing_copy() {
336        assert_eq!(format_hidden_lines_summary(1), "… +1 line");
337        assert_eq!(format_hidden_lines_summary(4), "… +4 lines");
338    }
339
340    #[test]
341    fn excerpt_text_lines_builds_head_tail_vectors() {
342        let preview = excerpt_text_lines("l1\nl2\nl3\nl4\nl5\nl6", 2, 2);
343        assert_eq!(preview.head, vec!["l1", "l2"]);
344        assert_eq!(preview.tail, vec!["l5", "l6"]);
345        assert_eq!(preview.hidden_count, 2);
346        assert_eq!(preview.total, 6);
347    }
348
349    #[test]
350    fn condense_text_bytes_respects_utf8_boundaries() {
351        let mut content = "a".repeat(7);
352        content.push('é');
353        content.push_str("bbbbbbbb");
354
355        let preview = condense_text_bytes(&content, 8, 4);
356        assert!(preview.contains("bytes omitted"));
357        assert!(preview.is_char_boundary(0));
358    }
359
360    #[test]
361    fn tail_preview_text_keeps_last_lines_only() {
362        let input = (0..20).map(|index| format!("line-{index}")).collect::<Vec<_>>().join("\n");
363
364        let preview = tail_preview_text(&input, 40, 3);
365        assert!(preview.contains("bytes omitted"));
366        assert!(preview.contains("line-19"));
367        assert!(!preview.contains("line-1\n"));
368    }
369}