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
//! Text highlighting utilities
//!
//! Provides utilities for highlighting matched text in search results,
//! fuzzy matches, and other highlighting scenarios.
//!
//! # Example
//!
//! ```rust,ignore
//! use revue::utils::{highlight_matches, HighlightSpan};
//!
//! // Highlight fuzzy match
//! let indices = vec![0, 3, 7];  // Matched character positions
//! let spans = highlight_matches("CommandPalette", &indices);
//!
//! // Highlight search term
//! let spans = highlight_substring("Hello World", "World");
//! ```

use crate::style::Color;

/// A span of text with optional highlighting
#[derive(Clone, Debug, PartialEq)]
pub struct HighlightSpan {
    /// The text content
    pub text: String,
    /// Whether this span is highlighted
    pub highlighted: bool,
    /// Start index in original string
    pub start: usize,
    /// End index in original string (exclusive)
    pub end: usize,
}

impl HighlightSpan {
    /// Create a new highlight span
    pub fn new(text: impl Into<String>, highlighted: bool, start: usize, end: usize) -> Self {
        Self {
            text: text.into(),
            highlighted,
            start,
            end,
        }
    }

    /// Create a normal (non-highlighted) span
    pub fn normal(text: impl Into<String>, start: usize, end: usize) -> Self {
        Self::new(text, false, start, end)
    }

    /// Create a highlighted span
    pub fn highlighted(text: impl Into<String>, start: usize, end: usize) -> Self {
        Self::new(text, true, start, end)
    }
}

/// Highlight specific character indices in a string
///
/// Creates spans where characters at the given indices are highlighted.
/// Useful for fuzzy match highlighting.
///
/// # Example
///
/// ```rust,ignore
/// use revue::utils::highlight_matches;
///
/// let spans = highlight_matches("CommandPalette", &[0, 7]);
/// // Returns: [("C", true), ("ommand", false), ("P", true), ("alette", false)]
/// ```
pub fn highlight_matches(text: &str, indices: &[usize]) -> Vec<HighlightSpan> {
    if indices.is_empty() {
        return vec![HighlightSpan::normal(text.to_string(), 0, text.len())];
    }

    let chars: Vec<char> = text.chars().collect();
    let mut spans = Vec::new();
    let mut current_start = 0;
    let mut current_text = String::new();
    let mut in_highlight = false;

    for (i, &ch) in chars.iter().enumerate() {
        let should_highlight = indices.contains(&i);

        if should_highlight != in_highlight {
            // State change
            if !current_text.is_empty() {
                let byte_start = text
                    .char_indices()
                    .nth(current_start)
                    .map(|(i, _)| i)
                    .unwrap_or(0);
                let byte_end = text
                    .char_indices()
                    .nth(current_start + current_text.chars().count())
                    .map(|(i, _)| i)
                    .unwrap_or(text.len());

                spans.push(HighlightSpan::new(
                    current_text.clone(),
                    in_highlight,
                    byte_start,
                    byte_end,
                ));
            }
            current_text.clear();
            current_start = i;
            in_highlight = should_highlight;
        }

        current_text.push(ch);
    }

    // Final span
    if !current_text.is_empty() {
        let byte_start = text
            .char_indices()
            .nth(current_start)
            .map(|(i, _)| i)
            .unwrap_or(0);

        spans.push(HighlightSpan::new(
            current_text,
            in_highlight,
            byte_start,
            text.len(),
        ));
    }

    spans
}

/// Highlight all occurrences of a substring
///
/// Case-insensitive by default.
///
/// # Example
///
/// ```rust,ignore
/// use revue::utils::highlight_substring;
///
/// let spans = highlight_substring("Hello World, Hello!", "hello");
/// // Highlights both "Hello" occurrences
/// ```
pub fn highlight_substring(text: &str, pattern: &str) -> Vec<HighlightSpan> {
    highlight_substring_case(text, pattern, false)
}

/// Highlight all occurrences of a substring with case sensitivity option
pub fn highlight_substring_case(
    text: &str,
    pattern: &str,
    case_sensitive: bool,
) -> Vec<HighlightSpan> {
    if pattern.is_empty() {
        return vec![HighlightSpan::normal(text.to_string(), 0, text.len())];
    }

    let search_text = if case_sensitive {
        text.to_string()
    } else {
        text.to_lowercase()
    };
    let search_pattern = if case_sensitive {
        pattern.to_string()
    } else {
        pattern.to_lowercase()
    };

    let mut spans = Vec::new();
    let mut last_end = 0;

    for (start, _) in search_text.match_indices(&search_pattern) {
        let end = start + pattern.len();

        // Add non-highlighted span before match
        if start > last_end {
            spans.push(HighlightSpan::normal(
                text[last_end..start].to_string(),
                last_end,
                start,
            ));
        }

        // Add highlighted span
        spans.push(HighlightSpan::highlighted(
            text[start..end].to_string(),
            start,
            end,
        ));

        last_end = end;
    }

    // Add remaining non-highlighted text
    if last_end < text.len() {
        spans.push(HighlightSpan::normal(
            text[last_end..].to_string(),
            last_end,
            text.len(),
        ));
    }

    if spans.is_empty() {
        spans.push(HighlightSpan::normal(text.to_string(), 0, text.len()));
    }

    spans
}

/// Highlight a range in a string
pub fn highlight_range(text: &str, start: usize, end: usize) -> Vec<HighlightSpan> {
    let end = end.min(text.len());
    let start = start.min(end);

    let mut spans = Vec::new();

    if start > 0 {
        spans.push(HighlightSpan::normal(text[..start].to_string(), 0, start));
    }

    if start < end {
        spans.push(HighlightSpan::highlighted(
            text[start..end].to_string(),
            start,
            end,
        ));
    }

    if end < text.len() {
        spans.push(HighlightSpan::normal(
            text[end..].to_string(),
            end,
            text.len(),
        ));
    }

    if spans.is_empty() {
        spans.push(HighlightSpan::normal(text.to_string(), 0, text.len()));
    }

    spans
}

/// Highlight multiple ranges in a string
///
/// Ranges are merged if they overlap.
pub fn highlight_ranges(text: &str, ranges: &[(usize, usize)]) -> Vec<HighlightSpan> {
    if ranges.is_empty() {
        return vec![HighlightSpan::normal(text.to_string(), 0, text.len())];
    }

    // Sort and merge overlapping ranges
    let mut sorted: Vec<(usize, usize)> = ranges.to_vec();
    sorted.sort_by_key(|r| r.0);

    let mut merged = Vec::new();
    let mut current = sorted[0];

    for &(start, end) in &sorted[1..] {
        if start <= current.1 {
            // Overlapping, merge
            current.1 = current.1.max(end);
        } else {
            merged.push(current);
            current = (start, end);
        }
    }
    merged.push(current);

    // Create spans
    let mut spans = Vec::new();
    let mut last_end = 0;

    for (start, end) in merged {
        let start = start.min(text.len());
        let end = end.min(text.len());

        if start > last_end {
            spans.push(HighlightSpan::normal(
                text[last_end..start].to_string(),
                last_end,
                start,
            ));
        }

        if start < end {
            spans.push(HighlightSpan::highlighted(
                text[start..end].to_string(),
                start,
                end,
            ));
        }

        last_end = end;
    }

    if last_end < text.len() {
        spans.push(HighlightSpan::normal(
            text[last_end..].to_string(),
            last_end,
            text.len(),
        ));
    }

    spans
}

/// Builder for applying different highlight styles
#[derive(Clone, Debug)]
pub struct Highlighter {
    /// Highlight foreground color
    pub highlight_fg: Option<Color>,
    /// Highlight background color
    pub highlight_bg: Option<Color>,
    /// Normal foreground color
    pub normal_fg: Option<Color>,
    /// Normal background color
    pub normal_bg: Option<Color>,
}

impl Default for Highlighter {
    fn default() -> Self {
        Self {
            highlight_fg: Some(Color::BLACK),
            highlight_bg: Some(Color::YELLOW),
            normal_fg: None,
            normal_bg: None,
        }
    }
}

impl Highlighter {
    /// Create a new highlighter with default colors
    pub fn new() -> Self {
        Self::default()
    }

    /// Set highlight foreground color
    pub fn highlight_fg(mut self, color: Color) -> Self {
        self.highlight_fg = Some(color);
        self
    }

    /// Set highlight background color
    pub fn highlight_bg(mut self, color: Color) -> Self {
        self.highlight_bg = Some(color);
        self
    }

    /// Set normal foreground color
    pub fn normal_fg(mut self, color: Color) -> Self {
        self.normal_fg = Some(color);
        self
    }

    /// Set normal background color
    pub fn normal_bg(mut self, color: Color) -> Self {
        self.normal_bg = Some(color);
        self
    }

    /// Create a highlighter with custom highlight color
    pub fn with_color(fg: Color, bg: Color) -> Self {
        Self {
            highlight_fg: Some(fg),
            highlight_bg: Some(bg),
            normal_fg: None,
            normal_bg: None,
        }
    }

    /// Get foreground color for a span
    pub fn fg_for(&self, span: &HighlightSpan) -> Option<Color> {
        if span.highlighted {
            self.highlight_fg
        } else {
            self.normal_fg
        }
    }

    /// Get background color for a span
    pub fn bg_for(&self, span: &HighlightSpan) -> Option<Color> {
        if span.highlighted {
            self.highlight_bg
        } else {
            self.normal_bg
        }
    }
}

/// Highlight style presets
impl Highlighter {
    /// Yellow background highlight (default)
    pub fn yellow() -> Self {
        Self::with_color(Color::BLACK, Color::YELLOW)
    }

    /// Cyan/blue highlight
    pub fn cyan() -> Self {
        Self::with_color(Color::BLACK, Color::CYAN)
    }

    /// Green highlight
    pub fn green() -> Self {
        Self::with_color(Color::BLACK, Color::GREEN)
    }

    /// Red highlight
    pub fn red() -> Self {
        Self::with_color(Color::WHITE, Color::RED)
    }

    /// Magenta highlight
    pub fn magenta() -> Self {
        Self::with_color(Color::WHITE, Color::MAGENTA)
    }

    /// Underline style (foreground only)
    pub fn underline() -> Self {
        Self {
            highlight_fg: Some(Color::CYAN),
            highlight_bg: None,
            normal_fg: None,
            normal_bg: None,
        }
    }
}