croft-software 0.2.232

VSCode-style TUI written in Rust
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
//! VS Code "Go to Symbol in Editor" (Cmd/Ctrl+Shift+O): a fuzzy-filtered list
//! of the active file's symbols (functions, classes, methods, ...). Selecting
//! one jumps the editor to its definition. Typing a leading `:` switches to
//! Go to Line — `:42` jumps to line 42 — mirroring VS Code's shared quick
//! input. The widget owns only the query and selection; the app performs the
//! jump from `selected_target()` / `line_target()`.

use std::path::PathBuf;

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph, Widget},
};

use crate::icons::for_outline_kind;
use crate::lsp::manager::OutlineSymbol;
use crate::widgets::file_finder::fuzzy_score;
use crate::widgets::picker_colours;
use crate::widgets::picker_query;

pub struct SymbolPicker {
    pub query: String,
    pub cursor: usize,
    /// The active file the symbols belong to; the jump target's path.
    pub path: PathBuf,
    symbols: Vec<OutlineSymbol>,
    /// Indices into `symbols`, filtered + ranked against the query.
    pub results: Vec<usize>,
    pub selected: usize,
    pub scroll: usize,
    pub last_inner_height: u16,
    /// The popup's screen rect from the last render, for click-outside-to-close.
    pub last_rect: Rect,
}

impl SymbolPicker {
    pub fn new(path: PathBuf, symbols: Vec<OutlineSymbol>) -> Self {
        let mut me = Self {
            query: String::new(),
            cursor: 0,
            path,
            symbols,
            results: Vec::new(),
            selected: 0,
            scroll: 0,
            last_inner_height: 0,
            last_rect: Rect::default(),
        };
        me.refresh_results();
        me
    }

    /// True when the query is a Go to Line request (`:` then optional digits),
    /// so the app routes Enter to a line jump instead of a symbol jump.
    pub fn is_line_mode(&self) -> bool {
        self.query.trim_start().starts_with(':')
    }

    /// The 1-based line a `:N` query targets, if any.
    pub fn line_target(&self) -> Option<usize> {
        self.query
            .trim_start()
            .strip_prefix(':')
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .and_then(|s| s.parse::<usize>().ok())
            .filter(|&n| n >= 1)
    }

    /// The selected symbol's name, as screen reader mode reads it.
    pub fn selected_name(&self) -> Option<&str> {
        let idx = *self.results.get(self.selected)?;
        self.symbols.get(idx).map(|s| s.name.as_str())
    }

    /// The selected symbol's 0-based (line, character) jump target.
    pub fn selected_target(&self) -> Option<(u32, u32)> {
        let idx = *self.results.get(self.selected)?;
        let sym = self.symbols.get(idx)?;
        Some((sym.line, sym.character))
    }

    pub fn push_char(&mut self, c: char) {
        picker_query::insert(&mut self.query, &mut self.cursor, c);
        self.refresh_results();
        self.selected = 0;
        self.scroll = 0;
    }

    pub fn pop_char(&mut self) {
        if !picker_query::backspace(&mut self.query, &mut self.cursor) {
            return;
        }
        self.refresh_results();
        self.selected = 0;
        self.scroll = 0;
    }

    pub fn delete_char(&mut self) {
        if !picker_query::delete(&mut self.query, self.cursor) {
            return;
        }
        self.refresh_results();
        self.selected = 0;
        self.scroll = 0;
    }

    pub fn move_cursor_left(&mut self) {
        picker_query::left(&mut self.cursor);
    }

    pub fn move_cursor_right(&mut self) {
        picker_query::right(&self.query, &mut self.cursor);
    }

    pub fn move_cursor_home(&mut self) {
        self.cursor = 0;
    }

    pub fn move_cursor_end(&mut self) {
        picker_query::end(&self.query, &mut self.cursor);
    }

    pub fn select_next(&mut self) {
        if self.results.is_empty() {
            return;
        }
        if self.selected + 1 < self.results.len() {
            self.selected += 1;
        }
    }

    pub fn select_prev(&mut self) {
        self.selected = self.selected.saturating_sub(1);
    }

    /// The result index at screen row `y`, if `y` lands on a visible row.
    /// The list body starts three rows below `last_rect.y` (top border, the
    /// query prompt, then the separator) and runs `last_inner_height` rows,
    /// so this stays in lock-step with [`render_symbol_picker`]. Used to map
    /// a mouse click to a result row. Line mode (`:N`) renders a "Go to
    /// line" hint in the list area while `results` still holds every
    /// symbol, so clicks there map to nothing.
    pub fn row_index_at(&self, y: u16) -> Option<usize> {
        if self.is_line_mode() {
            return None;
        }
        let list_top = self.last_rect.y.saturating_add(3);
        if y < list_top || y - list_top >= self.last_inner_height {
            return None;
        }
        let idx = self.scroll + (y - list_top) as usize;
        (idx < self.results.len()).then_some(idx)
    }

    /// Re-rank the symbol list against the query. Line mode (`:`) shows the
    /// symbols untouched (the list is irrelevant; Enter jumps to the line). An
    /// empty query lists every symbol in document order; otherwise rows are
    /// kept when their lower-cased name fuzzy-matches, ranked by score, ties
    /// broken by document order for stability.
    fn refresh_results(&mut self) {
        if self.is_line_mode() {
            self.results = (0..self.symbols.len()).collect();
            return;
        }
        let needle = self.query.trim().to_lowercase();
        if needle.is_empty() {
            self.results = (0..self.symbols.len()).collect();
            return;
        }
        let mut scored: Vec<(i32, usize)> = self
            .symbols
            .iter()
            .enumerate()
            .filter_map(|(idx, sym)| {
                fuzzy_score(&needle, &sym.name.to_lowercase(), 0).map(|score| (score, idx))
            })
            .collect();
        scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
        self.results = scored.into_iter().map(|(_, idx)| idx).collect();
    }
}

pub fn render_symbol_picker(
    picker: &mut SymbolPicker,
    area: Rect,
    buf: &mut Buffer,
    theme: crate::theme::Theme,
    center: bool,
) {
    let width = area.width.saturating_mul(7) / 10;
    let width = width.clamp(40, 100).min(area.width);
    let height = area.height.saturating_mul(6) / 10;
    let height = height.max(10).min(area.height);
    let x = area.x + (area.width.saturating_sub(width)) / 2;
    let y = if center {
        area.y + (area.height.saturating_sub(height)) / 2
    } else {
        area.y + (area.height.saturating_sub(height)) / 4
    };
    let rect = Rect {
        x,
        y,
        width,
        height,
    };

    picker.last_rect = rect;
    Widget::render(Clear, rect, buf);
    let title = Span::styled(
        " Go to Symbol — Esc to close, ↑/↓ to navigate, Enter to go, : for line ",
        Style::default()
            .fg(theme.ui(Color::Rgb(0xff, 0xff, 0xff)))
            .add_modifier(Modifier::BOLD),
    );
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme.ui(picker_colours::BORDER)))
        .title(title.clone())
        .style(Style::default().bg(theme.ui(picker_colours::BODY)));
    let inner = Rect {
        x: rect.x + 1,
        y: rect.y + 1,
        width: rect.width.saturating_sub(2),
        height: rect.height.saturating_sub(2),
    };
    Widget::render(block, rect, buf);
    if theme.framed_overlays() {
        crate::widgets::surface::paint_overlay_frame(buf, rect, theme);
        buf.set_span(rect.x + 1, rect.y, &title, title.width() as u16);
    }
    let sel_bg = if theme.gradient() {
        let (r, g, b) = crate::gradient::POPUP_SEL_BG;
        Color::Rgb(r, g, b)
    } else {
        theme.ui(picker_colours::SELECTION)
    };
    let tones = crate::theme::tones(theme);

    if inner.height == 0 || inner.width == 0 {
        return;
    }

    let query_style = Style::default()
        .fg(theme.ui(picker_colours::TEXT))
        .add_modifier(Modifier::BOLD);
    let caret_style = Style::default()
        .fg(theme.ui(picker_colours::BODY))
        .bg(theme.ui(picker_colours::TEXT))
        .add_modifier(Modifier::SLOW_BLINK);
    let cursor = picker.cursor.min(picker.query.chars().count());
    let before: String = picker.query.chars().take(cursor).collect();
    let at: String = picker.query.chars().skip(cursor).take(1).collect();
    let after: String = picker.query.chars().skip(cursor + 1).collect();
    let caret_glyph = if at.is_empty() { String::from(" ") } else { at };
    let prompt_line = Line::from(vec![
        Span::styled("@ ", Style::default().fg(theme.ui(picker_colours::PROMPT))),
        Span::styled(before, query_style),
        Span::styled(caret_glyph, caret_style),
        Span::styled(after, query_style),
    ]);
    Widget::render(
        Paragraph::new(prompt_line),
        Rect {
            x: inner.x,
            y: inner.y,
            width: inner.width,
            height: 1,
        },
        buf,
    );

    let sep_line = Line::from(Span::styled(
        "─".repeat(inner.width as usize),
        Style::default().fg(theme.ui(Color::Rgb(0x3b, 0x42, 0x52))),
    ));
    Widget::render(
        Paragraph::new(sep_line),
        Rect {
            x: inner.x,
            y: inner.y + 1,
            width: inner.width,
            height: 1,
        },
        buf,
    );

    let list_rect = Rect {
        x: inner.x,
        y: inner.y + 2,
        width: inner.width,
        height: inner.height.saturating_sub(2),
    };
    picker.last_inner_height = list_rect.height;
    if list_rect.height == 0 {
        return;
    }

    // Line mode: the symbol list is moot; show the target so the user sees
    // where Enter lands.
    if picker.is_line_mode() {
        let msg = match picker.line_target() {
            Some(n) => format!("  Go to line {n}"),
            None => String::from("  Type a line number, e.g. :42"),
        };
        Widget::render(
            Paragraph::new(Line::from(Span::styled(
                msg,
                Style::default().fg(theme.ui(picker_colours::DETAIL_BRIGHT)),
            ))),
            list_rect,
            buf,
        );
        return;
    }

    let visible = list_rect.height as usize;
    let total = picker.results.len();
    if picker.selected >= picker.scroll + visible {
        picker.scroll = picker.selected + 1 - visible;
    }
    if picker.selected < picker.scroll {
        picker.scroll = picker.selected;
    }
    let end = (picker.scroll + visible).min(total);

    if total == 0 {
        let empty = Line::from(Span::styled(
            String::from("  No symbols in this file"),
            Style::default().fg(theme.ui(picker_colours::DIM)),
        ));
        Widget::render(Paragraph::new(empty), list_rect, buf);
        return;
    }

    let mut lines: Vec<Line<'static>> = Vec::with_capacity(end - picker.scroll);
    for (offset, &sym_idx) in picker.results[picker.scroll..end].iter().enumerate() {
        let row_idx = picker.scroll + offset;
        let is_selected = row_idx == picker.selected;
        let Some(sym) = picker.symbols.get(sym_idx) else {
            continue;
        };
        let icon = for_outline_kind(sym.kind);
        let (row_style, detail_style, icon_style) = match tones {
            // The selected row's band and bar are painted after the rows,
            // so a `surfaces` row carries only its inks.
            Some(t) => (
                Style::default().fg(if is_selected { t.strong() } else { t.text() }),
                Style::default().fg(t.muted()),
                Style::default().fg(theme.ui(icon.color)),
            ),
            None if is_selected => (
                Style::default().bg(sel_bg).fg(theme.ui(Color::White)),
                Style::default()
                    .bg(sel_bg)
                    .fg(theme.ui(picker_colours::DETAIL_BRIGHT)),
                Style::default().bg(sel_bg).fg(theme.ui(icon.color)),
            ),
            None => (
                Style::default().fg(theme.ui(picker_colours::TEXT)),
                Style::default().fg(theme.ui(picker_colours::DETAIL)),
                Style::default().fg(theme.ui(icon.color)),
            ),
        };
        // Indent nested symbols by depth (capped), like the outline tree.
        let indent = "  ".repeat((sym.depth as usize).min(6));
        let prefix = if is_selected && tones.is_none() {
            "> "
        } else {
            "  "
        };
        // Right-align the line number, like the palette's chord hint.
        let line_label = format!("{} ", sym.line + 1);
        let used = prefix.chars().count()
            + indent.chars().count()
            + 2 // icon + space
            + sym.name.chars().count()
            + line_label.chars().count();
        let pad = (list_rect.width as usize).saturating_sub(used).max(1);
        lines.push(Line::from(vec![
            Span::styled(prefix.to_string(), row_style),
            Span::styled(indent, row_style),
            Span::styled(format!("{} ", icon.glyph), icon_style),
            Span::styled(sym.name.clone(), row_style),
            Span::styled(" ".repeat(pad), row_style),
            Span::styled(line_label, detail_style),
        ]));
    }
    Widget::render(Paragraph::new(lines), list_rect, buf);
    if let Some(t) = tones {
        paint_selected(buf, rect, list_rect, picker.selected, picker.scroll, t);
    }
}

/// The selected row on a `surfaces` card: the band across the card with
/// the accent bar on its left edge, at row `selected` of a list scrolled
/// to `scroll` and drawn in `list` inside `card`. Nothing when it is off
/// screen. Shared by the pickers whose rows carry no fill of their own.
pub(crate) fn paint_selected(
    buf: &mut Buffer,
    card: Rect,
    list: Rect,
    selected: usize,
    scroll: usize,
    t: crate::theme::Tones,
) {
    let Some(row) = selected.checked_sub(scroll) else {
        return;
    };
    if row >= usize::from(list.height) {
        return;
    }
    let band = Rect::new(card.x, list.y + row as u16, card.width.saturating_sub(1), 1);
    crate::widgets::surface::paint_selected_row(buf, band, t, t.raised, true);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lsp::manager::OutlineKind;

    fn sym(name: &str, kind: OutlineKind, depth: u16, line: u32) -> OutlineSymbol {
        OutlineSymbol {
            name: name.to_string(),
            detail: None,
            kind,
            depth,
            line,
            character: 0,
            range_start_line: line,
            range_end_line: line,
            range_start_character: 0,
            range_end_character: u32::MAX,
        }
    }

    fn picker() -> SymbolPicker {
        SymbolPicker::new(
            PathBuf::from("f.rs"),
            vec![
                sym("alpha", OutlineKind::Function, 0, 1),
                sym("beta", OutlineKind::Method, 1, 5),
                sym("gamma_helper", OutlineKind::Function, 0, 20),
            ],
        )
    }

    #[test]
    fn empty_query_lists_every_symbol_in_order() {
        let p = picker();
        assert_eq!(p.results, vec![0, 1, 2]);
    }

    /// In line mode (`:42`) the list area renders only a "Go to line" hint,
    /// yet `results` still holds every symbol; a click there must map to
    /// nothing rather than jump to an invisible symbol row.
    #[test]
    fn row_index_at_refuses_clicks_in_line_mode() {
        let mut p = picker();
        p.last_rect = Rect {
            x: 10,
            y: 5,
            width: 60,
            height: 10,
        };
        p.last_inner_height = 6;
        assert_eq!(
            p.row_index_at(8),
            Some(0),
            "outside line mode the first list row maps to the first symbol"
        );
        for c in [':', '4', '2'] {
            p.push_char(c);
        }
        assert!(p.is_line_mode());
        assert_eq!(
            p.row_index_at(8),
            None,
            "line mode renders a hint, not rows; clicks must map to nothing"
        );
    }

    #[test]
    fn fuzzy_query_filters_and_ranks() {
        let mut p = picker();
        p.push_char('g');
        p.push_char('h');
        // "gh" subsequence-matches gamma_helper, not alpha/beta.
        assert_eq!(p.results, vec![2]);
        assert_eq!(p.selected_target(), Some((20, 0)));
    }

    #[test]
    fn line_mode_parses_the_target_line() {
        let mut p = picker();
        for c in ":42".chars() {
            p.push_char(c);
        }
        assert!(p.is_line_mode());
        assert_eq!(p.line_target(), Some(42));
    }

    #[test]
    fn line_mode_with_no_digits_has_no_target() {
        let mut p = picker();
        p.push_char(':');
        assert!(p.is_line_mode());
        assert_eq!(p.line_target(), None);
    }

    #[test]
    fn selected_target_follows_navigation() {
        let mut p = picker();
        p.select_next();
        assert_eq!(p.selected_target(), Some((5, 0)));
        p.select_prev();
        assert_eq!(p.selected_target(), Some((1, 0)));
    }

    /// Croft Loch: the selected row is the band with the accent bar on the
    /// card's edge and keeps its own inks; no `> ` marker, no forced white.
    #[test]
    fn croft_loch_selects_a_row_with_the_band_and_bar() {
        use crate::widgets::surface;
        let theme = crate::theme::Theme::from_id("loch");
        let t = crate::theme::tones(theme).unwrap();
        let mut p = picker();
        p.select_next();
        let area = Rect::new(0, 0, 100, 30);
        let mut buf = Buffer::empty(area);
        render_symbol_picker(&mut p, area, &mut buf, theme, true);
        let r = p.last_rect;
        let row = |y: u16| -> String { (r.x..r.right()).map(|x| buf[(x, y)].symbol()).collect() };
        let list_top = r.y + 3;
        let y = list_top + 1;
        assert!(row(y).contains("beta"), "{}", row(y));
        assert!(!row(y).contains("> "), "{}", row(y));
        assert_eq!(buf[(r.x, y)].symbol(), surface::ROW_BAR);
        assert_eq!(buf[(r.x, y)].fg, t.accent());
        assert_eq!(buf[(r.x + 2, y)].bg, t.band());
        let name_x = (r.x..r.right())
            .find(|&x| buf[(x, y)].symbol() == "b")
            .unwrap();
        assert_eq!(buf[(name_x, y)].fg, t.strong());
        assert_ne!(buf[(r.x, list_top)].symbol(), surface::ROW_BAR);
        assert_eq!(buf[(r.x + 2, list_top)].bg, t.raised());
    }
}