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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! The Explorer's OPEN EDITORS section: a collapsible list of the editor tabs
//! currently open, mirroring VS Code's "Open Editors" view. Unlike OUTLINE /
//! TIMELINE / RUST DEPENDENCIES this needs no background fetch — the rows are a
//! pure projection of the in-memory [`crate::widgets::editor::EditorTabs`],
//! refreshed each frame by the app. A click activates that tab; the active tab
//! is highlighted and dirty tabs carry a filled dot, exactly as in the tab bar.

use std::path::PathBuf;

use crate::widgets::editor::{Editor, TabTitle, TabTitleInputs};

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

use crate::widgets::scrollbar;
use crate::widgets::view_cx::ViewCx;

const COLOR_DIM: Color = Color::Rgb(0x60, 0x68, 0x78);
const COLOR_NAME: Color = Color::Rgb(0xCC, 0xCC, 0xCC);
const COLOR_DIRTY: Color = Color::Rgb(0xE2, 0xC0, 0x8D);

/// Left indent matching the tree's `Borders::ALL` inset (this panel draws only
/// a bottom separator) so rows line up under the file rows above.
const CONTENT_INDENT: u16 = 1;

/// One open editor, as projected from the active tab set.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OpenEditorItem {
    /// The tab's file path (used for the click-to-activate target).
    pub path: PathBuf,
    /// The basename shown in the row.
    pub name: String,
    /// Dirty (unsaved) tab — drawn with a filled dot, like the tab bar.
    pub dirty: bool,
    /// The currently focused tab — highlighted.
    pub active: bool,
}

pub struct OpenEditorsPanel {
    pub collapsed: bool,
    items: Vec<OpenEditorItem>,
    scroll: usize,

    pub last_area: Rect,
    pub last_scrollbar: Rect,
    /// Hit-test rect of the header's Save All action (#852), VS Code's
    /// Open Editors toolbar button. `Rect::default()` while the section is
    /// collapsed (VS Code hides a collapsed view's actions) or too narrow.
    pub save_all_btn: Rect,
    last_header_row: u16,
    last_header_x: u16,
    last_header_w: u16,
    first_row_y: u16,
    visible_rows: u16,
    /// The scroll those rows were drawn with (#2751). A click is matched
    /// against it: the screen shows it until the next frame, while a key or
    /// wheel step read in the same burst has already moved `scroll`.
    last_scroll: usize,
    viewport_rows: u16,
    /// The active tab and each tab's title inputs the rows were built from
    /// (#2062): the rows are a function of them, so a pass that finds them
    /// unchanged has nothing to rebuild.
    built_from: Option<(usize, Vec<TabTitleInputs>)>,
}

impl OpenEditorsPanel {
    pub fn new() -> Self {
        Self {
            // Start collapsed (a 1-row chevron strip), like OUTLINE, so a fresh
            // Explorer is compact; the user expands what they want.
            collapsed: true,
            items: Vec::new(),
            scroll: 0,
            last_area: Rect::default(),
            last_scrollbar: Rect::default(),
            save_all_btn: Rect::default(),
            last_header_row: 0,
            last_header_x: 0,
            last_header_w: 0,
            first_row_y: 0,
            visible_rows: 0,
            last_scroll: 0,
            viewport_rows: 0,
            built_from: None,
        }
    }

    /// Whether the rows were built from these tabs with `active` focused,
    /// compared in place so a pass that finds nothing changed allocates
    /// nothing (#2062).
    pub fn built_from(&self, active: usize, tabs: &[Editor]) -> bool {
        self.built_from
            .as_ref()
            .is_some_and(|(was_active, inputs)| {
                *was_active == active
                    && inputs.len() == tabs.len()
                    && inputs.iter().zip(tabs).all(|(i, t)| *i == TabTitle::of(t))
            })
    }

    /// Replace the rows with `items`, built from `tabs` with `active`
    /// focused, returning whether anything changed (see [`Self::set_items`]).
    pub fn set_items_from(
        &mut self,
        items: Vec<OpenEditorItem>,
        active: usize,
        tabs: &[Editor],
    ) -> bool {
        self.built_from = Some((
            active,
            tabs.iter()
                .map(|t| TabTitleInputs::from(TabTitle::of(t)))
                .collect(),
        ));
        self.set_items(items)
    }

    /// Replace the row set with the current tabs, returning whether anything
    /// actually changed (so the caller only forces a redraw when it did, never
    /// once per tick). Keeps scroll where it is so a redraw never jumps.
    pub fn set_items(&mut self, items: Vec<OpenEditorItem>) -> bool {
        if self.items == items {
            return false;
        }
        self.items = items;
        self.scroll = self.scroll.min(self.max_scroll());
        true
    }

    pub fn toggle_collapse(&mut self) {
        self.collapsed = !self.collapsed;
    }

    pub fn scroll_down(&mut self, n: usize) {
        self.scroll = (self.scroll + n).min(self.max_scroll());
    }

    pub fn scroll_up(&mut self, n: usize) {
        self.scroll = self.scroll.saturating_sub(n);
    }

    fn max_scroll(&self) -> usize {
        self.items.len().saturating_sub(self.viewport_rows as usize)
    }

    pub fn scroll_to_bar_y(&mut self, y: u16) -> bool {
        let Some(metrics) = scrollbar::vertical_metrics(
            self.last_scrollbar,
            self.items.len(),
            self.viewport_rows as usize,
            self.scroll,
        ) else {
            return false;
        };
        let target = scrollbar::scroll_for_y(metrics, y);
        let moved = target != self.scroll;
        self.scroll = target;
        moved
    }

    /// Same collapsible sizing contract as [`OutlinePanel::desired_height`]:
    /// collapsed is the header plus the bottom separator; expanded adds one row
    /// per editor (or a single empty-state row), capped at half the region.
    pub fn desired_height(&self, available: u16) -> u16 {
        const BORDER: u16 = 1;
        if available == 0 {
            return 0;
        }
        let header = 1u16;
        let floor = header + BORDER;
        if self.collapsed {
            return floor.min(available);
        }
        let content = if self.items.is_empty() {
            1
        } else {
            self.items.len() as u16
        };
        let half = (available / 2).max(floor);
        (header + content + BORDER).min(half)
    }

    pub fn hit_header(&self, x: u16, y: u16) -> bool {
        y == self.last_header_row
            && x >= self.last_header_x
            && x < self.last_header_x.saturating_add(self.last_header_w)
    }

    /// Whether `(x, y)` is on the header's Save All action (#852).
    pub fn hit_save_all(&self, x: u16, y: u16) -> bool {
        let b = self.save_all_btn;
        b.width > 0 && y == b.y && x >= b.x && x < b.x.saturating_add(b.width)
    }

    pub fn row_at(&self, y: u16) -> Option<usize> {
        if self.collapsed || self.visible_rows == 0 || y < self.first_row_y {
            return None;
        }
        let offset = (y - self.first_row_y) as usize;
        if offset >= self.visible_rows as usize {
            return None;
        }
        let idx = self.last_scroll + offset;
        (idx < self.items.len()).then_some(idx)
    }

    /// The path of the editor at `idx`, for activating its tab on click.
    pub fn path_at(&self, idx: usize) -> Option<PathBuf> {
        self.items.get(idx).map(|i| i.path.clone())
    }
}

impl Default for OpenEditorsPanel {
    fn default() -> Self {
        Self::new()
    }
}

impl OpenEditorsPanel {
    /// Draw the section into `area` with this frame's [`ViewCx`].
    pub fn draw(&mut self, cx: &ViewCx, area: Rect, buf: &mut Buffer) {
        let block = crate::widgets::surface::section_block(
            cx.theme,
            Borders::BOTTOM,
            Style::default().fg(cx.theme.ui(COLOR_DIM)),
        );
        let inner = block.inner(area);
        block.render(area, buf);
        self.last_area = area;
        self.last_scrollbar = Rect::default();
        self.save_all_btn = Rect::default();
        self.visible_rows = 0;
        if inner.height == 0 || inner.width == 0 {
            return;
        }
        let inner = Rect {
            x: inner.x + CONTENT_INDENT.min(inner.width),
            width: inner.width.saturating_sub(CONTENT_INDENT),
            ..inner
        };

        let header_y = inner.y;
        let chevron = format!(
            "{} ",
            crate::widgets::surface::chevron(cx.theme, !self.collapsed)
        );
        const TITLE: &str = "OPEN EDITORS";
        // The header's own text, measured in cells, so the Save All action
        // below clears it whatever the chevron glyph or title become.
        let title_w = {
            use unicode_width::UnicodeWidthStr;
            u16::try_from(chevron.width() + TITLE.width()).unwrap_or(u16::MAX)
        };
        let header_row = Rect {
            x: inner.x,
            y: header_y,
            width: inner.width,
            height: 1,
        };
        crate::widgets::surface::paint_section_header(
            buf,
            header_row,
            cx.theme,
            !self.collapsed,
            TITLE,
            Vec::new(),
            crate::widgets::hover::contains(header_row, cx.pointer),
        );
        self.last_header_row = header_y;
        self.last_header_x = inner.x;
        self.last_header_w = inner.width;

        // VS Code's Save All action (#852), right-aligned on the header with
        // a one-cell pad, as the Explorer's root-row toolbar sits. Only while
        // expanded (VS Code hides a collapsed view's actions) and only where
        // it clears the title.
        const PAD: u16 = 1;
        // Title, a two-cell gap, then the glyph and its pad.
        if !self.collapsed && inner.width > title_w.saturating_add(2 + PAD) {
            let x = inner.x + inner.width - PAD - 1;
            let rect = Rect {
                x,
                y: header_y,
                width: 1 + PAD,
                height: 1,
            };
            let hovered = crate::widgets::hover::contains(rect, cx.pointer);
            crate::widgets::header_pill::render(
                buf,
                x,
                header_y,
                crate::widgets::header_pill::SAVE_ALL_GLYPH,
                cx.theme,
                hovered,
            );
            self.save_all_btn = rect;
        }

        if self.collapsed || inner.height < 2 {
            return;
        }

        let body_y = header_y + 1;
        let body_h = inner.height - 1;
        self.first_row_y = body_y;
        self.viewport_rows = body_h;

        if self.items.is_empty() {
            Paragraph::new(Line::from(Span::styled(
                "No open editors",
                Style::default().fg(cx.theme.ui(COLOR_DIM)),
            )))
            .render(
                Rect {
                    x: inner.x,
                    y: body_y,
                    width: inner.width,
                    height: 1,
                },
                buf,
            );
            return;
        }

        self.scroll = self
            .scroll
            .min(self.items.len().saturating_sub(body_h as usize));
        let bar = scrollbar::vertical_metrics(
            Rect {
                x: inner.x + inner.width.saturating_sub(1),
                y: body_y,
                width: 1,
                height: body_h,
            },
            self.items.len(),
            body_h as usize,
            self.scroll,
        );
        let content_w = inner.width.saturating_sub(u16::from(bar.is_some()));

        let visible = (body_h as usize).min(self.items.len().saturating_sub(self.scroll));
        self.visible_rows = visible as u16;
        self.last_scroll = self.scroll;
        let brand = cx.theme.gradient();
        let sel_bg = if brand {
            crate::gradient::rgb_color(crate::gradient::POPUP_SEL_BG)
        } else {
            cx.theme.ui(Color::Rgb(0x09, 0x4d, 0x77))
        };

        for row in 0..visible {
            let idx = self.scroll + row;
            let item = &self.items[idx];
            let y = body_y + row as u16;
            let row_rect = Rect {
                x: inner.x,
                y,
                width: content_w,
                height: 1,
            };

            // Dirty tabs lead with a filled dot in the dirty colour; clean tabs
            // pad the same column so the names stay aligned.
            let (marker, marker_color) = if item.dirty {
                ("● ", cx.theme.ui(COLOR_DIRTY))
            } else {
                ("  ", cx.theme.ui(COLOR_DIM))
            };
            let name_style = if item.active {
                Style::default()
                    .fg(cx.theme.ui(Color::White))
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(cx.theme.ui(COLOR_NAME))
            };
            let spans = vec![
                Span::styled(marker, Style::default().fg(marker_color)),
                Span::styled(item.name.clone(), name_style),
            ];

            let style = if item.active {
                Style::default().bg(sel_bg)
            } else if let Some(bg) =
                crate::widgets::hover::row_hover_bg(row_rect, cx.pointer, cx.theme)
            {
                Style::default().bg(bg)
            } else {
                Style::default()
            };
            buf.set_style(row_rect, style);
            Paragraph::new(Line::from(spans)).render(row_rect, buf);
        }

        if let Some(metrics) = bar {
            self.last_scrollbar = metrics.area;
            scrollbar::render_vertical_on_chrome(buf, metrics, cx.focused, cx.theme);
        }
    }
}

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

    fn item(name: &str, dirty: bool, active: bool) -> OpenEditorItem {
        OpenEditorItem {
            path: PathBuf::from(format!("/repo/{name}")),
            name: name.to_string(),
            dirty,
            active,
        }
    }

    /// #2062: the rows are kept while what they are made of stays, and a
    /// change to any of it (the file, the dirty dot, the focused tab, a
    /// tab more) says they must be built again, so keeping them never
    /// hides a change.
    #[test]
    fn rows_are_rebuilt_only_when_what_they_are_made_of_changes() {
        let mut a = Editor::new();
        a.path = Some(PathBuf::from("/repo/a.rs"));
        let mut b = Editor::new();
        b.path = Some(PathBuf::from("/repo/b.rs"));
        let mut tabs = vec![a, b];
        let mut p = OpenEditorsPanel::new();
        assert!(!p.built_from(0, &tabs), "nothing is built at first");
        p.set_items_from(vec![item("a.rs", false, true)], 0, &tabs);
        assert!(p.built_from(0, &tabs), "the same tabs need no rebuild");
        assert!(!p.built_from(1, &tabs), "another focused tab does");
        tabs[1].dirty = true;
        assert!(!p.built_from(0, &tabs), "a dirty dot does");
        tabs[1].dirty = false;
        assert!(p.built_from(0, &tabs));
        tabs[0].path = Some(PathBuf::from("/repo/c.rs"));
        assert!(!p.built_from(0, &tabs), "another file does");
        tabs[0].path = Some(PathBuf::from("/repo/a.rs"));
        tabs[1].write_protected = true;
        assert!(!p.built_from(0, &tabs), "a read-only mark does");
        tabs[1].write_protected = false;
        tabs.push(Editor::new());
        assert!(!p.built_from(0, &tabs), "a tab more does");
    }

    #[test]
    fn collapsed_is_header_plus_separator_expanded_grows() {
        let mut p = OpenEditorsPanel::new();
        p.set_items(vec![item("a.rs", false, true)]);
        p.collapsed = true;
        assert_eq!(p.desired_height(40), 2, "collapsed: header + separator");
        p.toggle_collapse();
        assert_eq!(p.desired_height(40), 3, "header + one editor + separator");
    }

    #[test]
    fn empty_expanded_shows_one_message_row() {
        let mut p = OpenEditorsPanel::new();
        p.collapsed = false;
        assert_eq!(
            p.desired_height(40),
            3,
            "header + 'No open editors' + separator"
        );
    }

    /// #2751: a wheel step and a click read in the same burst: the click
    /// meets the rows the last frame drew, not the ones the wheel has moved
    /// there before the next frame.
    #[test]
    fn a_click_after_a_wheel_step_meets_the_drawn_rows() {
        let mut p = OpenEditorsPanel::new();
        p.collapsed = false;
        p.set_items(
            (0..20)
                .map(|i| item(&format!("f{i:02}.rs"), false, i == 0))
                .collect(),
        );
        let area = Rect {
            x: 0,
            y: 0,
            width: 30,
            height: 6,
        };
        let mut buf = Buffer::empty(area);
        p.draw(&ViewCx::default(), area, &mut buf);
        let drawn = p.row_at(2);
        assert!(drawn.is_some(), "a row is drawn there");
        let before = p.scroll;
        p.scroll_down(3);
        assert!(p.scroll > before, "the wheel scrolled the rows");
        assert_eq!(p.row_at(2), drawn, "the row drawn there");
    }

    #[test]
    fn row_at_maps_clicks_to_items() {
        let mut p = OpenEditorsPanel::new();
        p.collapsed = false;
        p.set_items(vec![item("a.rs", false, true), item("b.rs", true, false)]);
        let area = Rect {
            x: 0,
            y: 0,
            width: 30,
            height: 6,
        };
        let mut buf = Buffer::empty(area);
        p.draw(&ViewCx::default(), area, &mut buf);
        assert_eq!(p.row_at(0), None, "header row is not an item");
        assert_eq!(p.row_at(1), Some(0));
        assert_eq!(p.row_at(2), Some(1));
        assert_eq!(p.row_at(3), None, "below the last item");
        assert_eq!(p.path_at(1), Some(PathBuf::from("/repo/b.rs")));
    }

    fn rendered_text(p: &mut OpenEditorsPanel, width: u16, height: u16) -> String {
        let area = Rect {
            x: 0,
            y: 0,
            width,
            height,
        };
        let mut buf = Buffer::empty(area);
        p.draw(&ViewCx::default(), area, &mut buf);
        let mut out = String::new();
        for y in 0..height {
            for x in 0..width {
                out.push_str(buf[(x, y)].symbol());
            }
            out.push('\n');
        }
        out
    }

    /// #852 negative: the header's Save All sits right-aligned while
    /// expanded, and a header too narrow to clear the title paints none
    /// rather than overprinting "OPEN EDITORS".
    #[test]
    fn save_all_action_needs_room_beside_the_title() {
        let mut p = OpenEditorsPanel::new();
        p.collapsed = false;
        p.set_items(vec![item("a.rs", true, true)]);
        let text = rendered_text(&mut p, 18, 4);
        assert!(!text.contains('\u{eb49}'), "{text:?}");
        assert!(text.contains("OPEN EDITORS"));
        assert_eq!(p.save_all_btn, Rect::default());
        let text = rendered_text(&mut p, 30, 4);
        assert!(
            text.lines().next().unwrap().contains('\u{eb49}'),
            "{text:?}"
        );
        assert!(p.hit_save_all(28, 0));
        assert!(!p.hit_save_all(5, 0), "the title is not the button");
        assert!(!p.hit_save_all(28, 1), "nor is the row below it");
    }

    /// #852 review guard: at every header width the Save All glyph either
    /// stays off or sits at least two cells clear of the title's last cell,
    /// and it shows from the first width with room for both.
    #[test]
    fn save_all_clears_the_title_at_every_width() {
        let mut p = OpenEditorsPanel::new();
        p.collapsed = false;
        p.set_items(vec![item("a.rs", true, true)]);
        let title: Vec<char> = "OPEN EDITORS".chars().collect();
        let mut first_shown = None;
        for width in 4..48 {
            let text = rendered_text(&mut p, width, 3);
            let header: Vec<char> = text.lines().next().unwrap().chars().collect();
            let title_end = header
                .windows(title.len())
                .position(|w| w == title.as_slice())
                .map(|at| at + title.len());
            match (title_end, header.iter().position(|&c| c == '\u{eb49}')) {
                (Some(end), Some(at)) => {
                    assert!(
                        at >= end + 2,
                        "width {width}: glyph at {at}, title ends at {end}"
                    );
                    first_shown.get_or_insert(width);
                }
                (_, None) => assert_eq!(p.save_all_btn, Rect::default(), "width {width}"),
                (None, Some(_)) => panic!("width {width}: a glyph with no full title: {text:?}"),
            }
        }
        let shown = first_shown.expect("Save All shows once there is room");
        assert!(
            rendered_text(&mut p, shown - 1, 3)
                .find('\u{eb49}')
                .is_none()
        );
        assert!(shown >= 18, "never squeezed in beside the title: {shown}");
    }

    #[test]
    fn dirty_tab_draws_a_dot() {
        let mut p = OpenEditorsPanel::new();
        p.collapsed = false;
        p.set_items(vec![item("dirty.rs", true, false)]);
        let text = rendered_text(&mut p, 24, 4);
        assert!(text.contains('●'), "dirty editor must show a dot: {text:?}");
        assert!(text.contains("dirty.rs"));
    }
}