zeph-tui 0.20.0

Ratatui-based TUI dashboard with real-time metrics for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::io::Write;
use std::sync::LazyLock;

use crossterm::cursor::MoveTo;
use crossterm::queue;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use regex::Regex;

use crate::widgets::chat::MdLink;

static URL_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"https?://[^\s<>\[\]()\x22'`]+").unwrap());

/// A detected hyperlink span in the rendered terminal buffer.
///
/// Carries the URL and the exact terminal cell range where the link text
/// appears. Used by [`write_osc8`] to emit OSC 8 escape sequences so that
/// supporting terminals display clickable hyperlinks.
///
/// # Examples
///
/// ```rust
/// use zeph_tui::hyperlink::HyperlinkSpan;
///
/// let span = HyperlinkSpan {
///     url: "https://example.com".to_string(),
///     row: 3,
///     start_col: 0,
///     end_col: 19,
/// };
/// assert!(span.url.starts_with("https://"));
/// ```
#[derive(Debug)]
pub struct HyperlinkSpan {
    /// The target URL (http/https only after sanitisation).
    pub url: String,
    /// Terminal row (0-based from the top of the viewport).
    pub row: u16,
    /// First terminal column of the link text (inclusive).
    pub start_col: u16,
    /// One past the last terminal column of the link text (exclusive).
    pub end_col: u16,
}

/// Find all HTTP/HTTPS URLs in `text` and return their byte ranges and URLs.
///
/// The returned ranges are byte-based and valid UTF-8 substrings of `text`.
///
/// # Examples
///
/// ```rust
/// use zeph_tui::hyperlink::detect_urls_in_text;
///
/// let hits = detect_urls_in_text("see https://example.com for details");
/// assert_eq!(hits.len(), 1);
/// assert_eq!(hits[0].1, "https://example.com");
/// ```
pub fn detect_urls_in_text(text: &str) -> Vec<(std::ops::Range<usize>, String)> {
    URL_RE
        .find_iter(text)
        .map(|m| (m.start()..m.end(), m.as_str().to_string()))
        .collect()
}

/// Scan the rendered terminal `buffer` within `area` for bare HTTP/HTTPS URLs.
///
/// Returns a [`HyperlinkSpan`] for each URL found, with accurate terminal
/// column positions.
///
/// # Examples
///
/// ```rust
/// use ratatui::buffer::Buffer;
/// use ratatui::layout::Rect;
/// use ratatui::style::Style;
/// use zeph_tui::hyperlink::collect_from_buffer;
///
/// let area = Rect::new(0, 0, 40, 1);
/// let mut buf = Buffer::empty(area);
/// buf.set_string(0, 0, "visit https://example.com", Style::default());
/// let spans = collect_from_buffer(&buf, area);
/// assert_eq!(spans.len(), 1);
/// assert_eq!(spans[0].url, "https://example.com");
/// ```
#[must_use]
pub fn collect_from_buffer(buffer: &Buffer, area: Rect) -> Vec<HyperlinkSpan> {
    let mut spans = Vec::new();
    for row in area.y..area.y + area.height {
        let mut row_text = String::new();
        let mut col_offsets: Vec<u16> = Vec::new();
        for col in area.x..area.x + area.width {
            let sym = buffer[(col, row)].symbol();
            for _ in sym.chars() {
                col_offsets.push(col);
            }
            row_text.push_str(sym);
        }
        for (range, url) in detect_urls_in_text(&row_text) {
            let Some(&start_col) = col_offsets.get(range.start) else {
                continue;
            };
            let end_col = col_offsets
                .get(range.end.saturating_sub(1))
                .map_or(start_col + 1, |c| c + 1);
            spans.push(HyperlinkSpan {
                url,
                row,
                start_col,
                end_col,
            });
        }
    }
    spans
}

fn is_safe_url(url: &str) -> bool {
    url.starts_with("https://") || url.starts_with("http://")
}

/// Collects hyperlink spans from the buffer in a single pass, merging regex-detected
/// bare URLs with markdown links. Markdown links take precedence: if a markdown link's
/// display text overlaps with a bare-URL span on the same row, the bare-URL span is
/// replaced. Only http(s) URLs are emitted for markdown links.
#[must_use]
pub fn collect_from_buffer_with_md_links(
    buffer: &Buffer,
    area: Rect,
    md_links: &[MdLink],
) -> Vec<HyperlinkSpan> {
    // Filter to safe-scheme, non-empty md_links up front.
    let safe_links: Vec<&MdLink> = md_links
        .iter()
        .filter(|l| !l.text.is_empty() && is_safe_url(&l.url))
        .collect();

    let mut spans: Vec<HyperlinkSpan> = Vec::new();

    for row in area.y..area.y + area.height {
        // Build row_text and char→col mapping in one pass.
        let mut row_chars: Vec<char> = Vec::new();
        let mut col_offsets: Vec<u16> = Vec::new();
        for col in area.x..area.x + area.width {
            let sym = buffer[(col, row)].symbol();
            for ch in sym.chars() {
                col_offsets.push(col);
                row_chars.push(ch);
            }
        }
        let row_text: String = row_chars.iter().collect();

        // Collect bare URL spans for this row.
        let mut row_spans: Vec<HyperlinkSpan> = Vec::new();
        for (range, url) in detect_urls_in_text(&row_text) {
            // range is byte-based; convert to char index via col_offsets.
            // Since URL_RE only matches ASCII characters, byte index == char index here,
            // but we use col_offsets for correctness regardless.
            let Some(&start_col) = col_offsets.get(range.start) else {
                continue;
            };
            let end_col = col_offsets
                .get(range.end.saturating_sub(1))
                .map_or(start_col + 1, |c| c + 1);
            row_spans.push(HyperlinkSpan {
                url,
                row,
                start_col,
                end_col,
            });
        }

        // Search for each markdown link text using char indices.
        for link in &safe_links {
            let link_chars: Vec<char> = link.text.chars().collect();
            let link_len = link_chars.len();
            if link_len == 0 || link_len > row_chars.len() {
                continue;
            }
            let mut search_from = 0;
            while search_from + link_len <= row_chars.len() {
                if row_chars[search_from..search_from + link_len] == link_chars[..] {
                    let start_col = col_offsets[search_from];
                    let end_col = col_offsets[search_from + link_len - 1] + 1;

                    // Remove bare-URL spans that overlap this region on the same row.
                    row_spans.retain(|s| s.end_col <= start_col || s.start_col >= end_col);

                    row_spans.push(HyperlinkSpan {
                        url: link.url.clone(),
                        row,
                        start_col,
                        end_col,
                    });

                    search_from += link_len;
                } else {
                    search_from += 1;
                }
            }
        }

        spans.extend(row_spans);
    }

    spans
}

/// Write OSC 8 escape sequences directly to the terminal writer.
/// Cursor is repositioned for each hyperlink; the visible text is untouched.
///
/// # Errors
///
/// Returns an error if writing to the terminal fails.
pub fn write_osc8(writer: &mut impl Write, spans: &[HyperlinkSpan]) -> std::io::Result<()> {
    for span in spans {
        // Strip ASCII control characters to prevent OSC 8 escape sequence injection.
        let safe_url: String = span.url.chars().filter(|c| !c.is_ascii_control()).collect();
        queue!(writer, MoveTo(span.start_col, span.row))?;
        write!(writer, "\x1b]8;;{safe_url}\x1b\\")?;
        queue!(writer, MoveTo(span.end_col, span.row))?;
        write!(writer, "\x1b]8;;\x1b\\")?;
    }
    Ok(())
}

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

    #[test]
    fn detect_urls_basic() {
        let urls = detect_urls_in_text("visit https://example.com for info");
        assert_eq!(urls.len(), 1);
        assert_eq!(urls[0].1, "https://example.com");
    }

    #[test]
    fn detect_urls_multiple() {
        let text = "see http://a.com and https://b.org/path?q=1";
        let urls = detect_urls_in_text(text);
        assert_eq!(urls.len(), 2);
        assert_eq!(urls[0].1, "http://a.com");
        assert_eq!(urls[1].1, "https://b.org/path?q=1");
    }

    #[test]
    fn detect_urls_none() {
        let urls = detect_urls_in_text("no links here");
        assert!(urls.is_empty());
    }

    #[test]
    fn detect_urls_in_markdown_brackets() {
        let urls = detect_urls_in_text("[text](https://example.com)");
        assert_eq!(urls.len(), 1);
        assert_eq!(urls[0].1, "https://example.com");
    }

    #[test]
    fn collect_from_buffer_finds_urls() {
        let area = Rect::new(0, 0, 40, 2);
        let mut buf = Buffer::empty(area);
        buf.set_string(
            0,
            0,
            "visit https://example.com now",
            ratatui::style::Style::default(),
        );
        buf.set_string(0, 1, "no links here", ratatui::style::Style::default());

        let spans = collect_from_buffer(&buf, area);
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].url, "https://example.com");
        assert_eq!(spans[0].row, 0);
        assert_eq!(spans[0].start_col, 6);
        assert_eq!(spans[0].end_col, 25);
    }

    #[test]
    fn collect_with_md_links_adds_link_span() {
        let area = Rect::new(0, 0, 40, 1);
        let mut buf = Buffer::empty(area);
        buf.set_string(
            0,
            0,
            "click here for info",
            ratatui::style::Style::default(),
        );

        let md_links = vec![MdLink {
            text: "click here".to_string(),
            url: "https://example.com".to_string(),
        }];
        let spans = collect_from_buffer_with_md_links(&buf, area, &md_links);
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].url, "https://example.com");
        assert_eq!(spans[0].start_col, 0);
        assert_eq!(spans[0].end_col, 10);
    }

    #[test]
    fn collect_with_md_links_replaces_bare_url_overlap() {
        let area = Rect::new(0, 0, 50, 1);
        let mut buf = Buffer::empty(area);
        // Display text is the URL itself — bare URL regex would also match.
        buf.set_string(
            0,
            0,
            "https://example.com",
            ratatui::style::Style::default(),
        );

        let md_links = vec![MdLink {
            text: "https://example.com".to_string(),
            url: "https://example.com".to_string(),
        }];
        let spans = collect_from_buffer_with_md_links(&buf, area, &md_links);
        // Deduplication: only one span should remain.
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].url, "https://example.com");
    }

    #[test]
    fn collect_with_md_links_non_ascii_text() {
        // Non-ASCII link text (CJK characters) must use char indices.
        // CJK chars are wide (2 columns each), so "日本語" occupies cols 0-5.
        let area = Rect::new(0, 0, 10, 1);
        let mut buf = Buffer::empty(area);
        buf.set_string(0, 0, "日本語", ratatui::style::Style::default());

        // Verify that the implementation can find CJK text in the buffer.
        // The row_chars built from the buffer symbols should contain the CJK chars.
        let mut row_chars: Vec<char> = Vec::new();
        for col in 0u16..10 {
            let sym = buf[(col, 0)].symbol();
            for ch in sym.chars() {
                row_chars.push(ch);
            }
        }
        // The buffer should contain the CJK chars in row_chars.
        let row_text: String = row_chars.iter().collect();
        // If CJK chars are present, the md_link test should find them.
        // If the buffer stores them differently (e.g. as placeholder spaces),
        // the test verifies the current actual behavior.
        let md_links = vec![MdLink {
            text: "日本語".to_string(),
            url: "https://example.com".to_string(),
        }];
        let spans = collect_from_buffer_with_md_links(&buf, area, &md_links);
        if row_text.contains("日本語") {
            // CJK chars stored as-is: link span should be found.
            assert_eq!(spans.len(), 1);
            assert_eq!(spans[0].url, "https://example.com");
        } else {
            // Buffer stores wide chars differently; no span produced (safe default).
            assert_eq!(spans.len(), 0);
        }
    }

    #[test]
    fn collect_with_md_links_rejects_unsafe_scheme() {
        let area = Rect::new(0, 0, 30, 1);
        let mut buf = Buffer::empty(area);
        buf.set_string(0, 0, "click me", ratatui::style::Style::default());

        let md_links = vec![MdLink {
            text: "click me".to_string(),
            url: "javascript:alert(1)".to_string(),
        }];
        let spans = collect_from_buffer_with_md_links(&buf, area, &md_links);
        assert!(spans.is_empty());
    }

    #[test]
    fn write_osc8_strips_control_chars() {
        let spans = vec![HyperlinkSpan {
            url: "https://x.com/\x1b]evil".to_string(),
            row: 0,
            start_col: 0,
            end_col: 5,
        }];
        let mut buf = Vec::new();
        write_osc8(&mut buf, &spans).unwrap();
        let output = String::from_utf8(buf).unwrap();
        // The injected ESC must not appear inside the OSC 8 URL parameter.
        assert!(output.contains("https://x.com/]evil"));
        assert!(!output.contains("https://x.com/\x1b]evil"));
    }

    #[test]
    fn write_osc8_produces_escape_sequences() {
        let spans = vec![HyperlinkSpan {
            url: "https://x.com".to_string(),
            row: 0,
            start_col: 0,
            end_col: 5,
        }];
        let mut buf = Vec::new();
        write_osc8(&mut buf, &spans).unwrap();
        let output = String::from_utf8(buf).unwrap();
        assert!(output.contains("\x1b]8;;https://x.com\x1b\\"));
        assert!(output.contains("\x1b]8;;\x1b\\"));
    }

    mod proptest_hyperlink {
        use super::*;
        use proptest::prelude::*;

        fn ascii_text() -> impl Strategy<Value = String> {
            "[a-zA-Z0-9 ]{1,60}"
        }

        fn safe_url() -> impl Strategy<Value = String> {
            "[a-zA-Z0-9/._~-]{1,40}".prop_map(|s| format!("https://example.com/{s}"))
        }

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(200))]

            #[test]
            fn collect_never_panics(
                text in ascii_text(),
                url in safe_url(),
                width in 20u16..120,
            ) {
                let area = Rect::new(0, 0, width, 3);
                let mut buf = Buffer::empty(area);
                buf.set_string(0, 0, &text, ratatui::style::Style::default());
                let md_links = vec![MdLink {
                    text: text.clone(),
                    url,
                }];
                let _ = collect_from_buffer_with_md_links(&buf, area, &md_links);
            }

            #[test]
            fn spans_within_buffer_bounds(
                text in "[a-z]{3,20}",
                url in safe_url(),
                width in 30u16..100,
            ) {
                let area = Rect::new(0, 0, width, 1);
                let mut buf = Buffer::empty(area);
                buf.set_string(0, 0, &text, ratatui::style::Style::default());
                let md_links = vec![MdLink { text, url }];
                let spans = collect_from_buffer_with_md_links(&buf, area, &md_links);
                for span in &spans {
                    prop_assert!(span.start_col < span.end_col);
                    prop_assert!(span.end_col <= area.x + area.width);
                    prop_assert!(span.row < area.y + area.height);
                }
            }

            #[test]
            fn empty_md_links_matches_collect_from_buffer(
                width in 30u16..80,
            ) {
                let area = Rect::new(0, 0, width, 1);
                let mut buf = Buffer::empty(area);
                buf.set_string(
                    0, 0,
                    "visit https://example.com now",
                    ratatui::style::Style::default(),
                );
                let baseline = collect_from_buffer(&buf, area);
                let with_empty = collect_from_buffer_with_md_links(&buf, area, &[]);
                prop_assert_eq!(baseline.len(), with_empty.len());
                for (a, b) in baseline.iter().zip(with_empty.iter()) {
                    prop_assert_eq!(&a.url, &b.url);
                    prop_assert_eq!(a.start_col, b.start_col);
                    prop_assert_eq!(a.end_col, b.end_col);
                }
            }
        }
    }
}