ratada 0.4.0

A ratatui widget toolkit: driver, modals, forms, pickers, theming
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
//! A collapsible tree view: a hierarchical, keyboard-navigable list.
//!
//! The caller builds an owned tree of [`TreeItem`]s; [`TreeView`] holds the
//! expand/collapse and cursor state and renders the currently visible nodes.

use std::{cell::Cell, collections::HashSet};

use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{Frame, layout::Rect, text::Line};

use super::{chrome, input, list, nav};
use crate::theme::{GlyphVariant, Skin};

/// A node in a tree: a label plus zero or more children.
///
/// A leaf may carry a caller-defined `id`, which [`TreeView::selected_id`]
/// hands back for the node under the cursor. Labels are not unique, so an `id`
/// is the only reliable way to map a selection back to the caller's data.
#[derive(Debug, Clone)]
pub struct TreeItem {
    label: String,
    id: Option<usize>,
    children: Vec<TreeItem>,
}

impl TreeItem {
    /// A leaf node with no children and no id.
    pub fn leaf(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            id: None,
            children: Vec::new(),
        }
    }

    /// A leaf node carrying `id`, so the caller can map a selection back to
    /// whatever the leaf stands for.
    pub fn leaf_with_id(label: impl Into<String>, id: usize) -> Self {
        Self {
            label: label.into(),
            id: Some(id),
            children: Vec::new(),
        }
    }

    /// A node with children.
    pub fn node(label: impl Into<String>, children: Vec<TreeItem>) -> Self {
        Self {
            label: label.into(),
            id: None,
            children,
        }
    }

    fn has_children(&self) -> bool {
        !self.children.is_empty()
    }
}

/// One currently visible node, produced by flattening the tree.
struct Flat {
    index: usize,
    depth: usize,
    label: String,
    id: Option<usize>,
    has_children: bool,
    expanded: bool,
}

/// A tree view over owned [`TreeItem`] roots. Nodes start collapsed.
pub struct TreeView {
    roots: Vec<TreeItem>,
    expanded: HashSet<usize>,
    cursor: usize,
    offset: Cell<usize>,
    viewport: Cell<usize>,
    decor: Option<chrome::BoxDecor>,
}

impl TreeView {
    /// Builds a tree view over `roots`, all collapsed, cursor on the first row.
    pub fn new(roots: Vec<TreeItem>) -> Self {
        Self {
            roots,
            expanded: HashSet::new(),
            cursor: 0,
            offset: Cell::new(0),
            viewport: Cell::new(1),
            decor: None,
        }
    }

    /// Draws the tree inside a rounded box with the given caption/badge (see
    /// [`chrome::BoxDecor`]); the badge defaults to the number of visible rows.
    /// Omit it for a plain tree.
    #[must_use]
    pub fn boxed(mut self, decor: chrome::BoxDecor) -> Self {
        self.decor = Some(decor);
        self
    }

    /// The label of the node under the cursor, if any.
    pub fn selected_label(&self) -> Option<String> {
        self.flatten()
            .get(self.cursor)
            .map(|node| node.label.clone())
    }

    /// The id of the node under the cursor, or `None` when the tree is empty or
    /// the node was built without one (see [`TreeItem::leaf_with_id`]).
    pub fn selected_id(&self) -> Option<usize> {
        self.flatten().get(self.cursor).and_then(|node| node.id)
    }

    /// Whether the node under the cursor is a leaf. An empty tree has no
    /// cursor node and so reports `false`.
    pub fn selected_is_leaf(&self) -> bool {
        self.flatten()
            .get(self.cursor)
            .is_some_and(|node| !node.has_children)
    }

    /// Handles a key: move the cursor (`Up`/`Down`/`k`/`j` cyclically,
    /// `PageUp`/`PageDown` by a page, `Home`/`End`/`g`/`G` to the ends),
    /// expand/collapse (`Left`/`Right`/`h`/`l`) or toggle (`Enter`/`Space`) the
    /// current node.
    ///
    /// These are bare keys only: a Ctrl chord is ignored, so a caller stays
    /// free to bind `Ctrl+<key>` itself.
    pub fn handle_key(&mut self, key: KeyEvent) {
        // The tree binds no chord of its own, and crossterm reports Ctrl+L and
        // Ctrl+H as `Char('l')`/`Char('h')` - without this they would expand
        // and collapse the node, and Ctrl+J would move the cursor.
        if input::is_command(key) {
            return;
        }
        let flat = self.flatten();
        if flat.is_empty() {
            return;
        }
        let page = self.viewport.get().max(1) as isize;
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                self.cursor = nav::cycle(self.cursor, flat.len(), -1);
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.cursor = nav::cycle(self.cursor, flat.len(), 1);
            }
            KeyCode::PageUp => {
                self.cursor = nav::step_clamped(self.cursor, flat.len(), -page);
            }
            KeyCode::PageDown => {
                self.cursor = nav::step_clamped(self.cursor, flat.len(), page);
            }
            KeyCode::Home | KeyCode::Char('g') => self.cursor = 0,
            KeyCode::End | KeyCode::Char('G') => {
                self.cursor = flat.len().saturating_sub(1);
            }
            KeyCode::Right | KeyCode::Char('l') => {
                self.set_expanded(&flat, true);
            }
            KeyCode::Left | KeyCode::Char('h') => {
                self.set_expanded(&flat, false);
            }
            KeyCode::Enter | KeyCode::Char(' ') => self.toggle(&flat),
            _ => {}
        }
        self.clamp_cursor();
    }

    /// Opens (`expand`) or closes the node under the cursor. Leaves do nothing.
    fn set_expanded(&mut self, flat: &[Flat], expand: bool) {
        let Some(node) = flat.get(self.cursor) else {
            return;
        };
        if !node.has_children {
            return;
        }
        if expand {
            self.expanded.insert(node.index);
        } else {
            self.expanded.remove(&node.index);
        }
    }

    fn toggle(&mut self, flat: &[Flat]) {
        if let Some(node) = flat.get(self.cursor)
            && node.has_children
        {
            if node.expanded {
                self.expanded.remove(&node.index);
            } else {
                self.expanded.insert(node.index);
            }
        }
    }

    fn clamp_cursor(&mut self) {
        let len = self.flatten().len();
        if self.cursor >= len {
            self.cursor = len.saturating_sub(1);
        }
    }

    /// The currently visible nodes, in display order, with a stable per-node
    /// index (preorder over the whole tree) used as the expansion key.
    fn flatten(&self) -> Vec<Flat> {
        let mut out = Vec::new();
        let mut counter = 0usize;
        for item in &self.roots {
            self.walk(item, 0, true, &mut counter, &mut out);
        }
        out
    }

    fn walk(
        &self,
        item: &TreeItem,
        depth: usize,
        visible: bool,
        counter: &mut usize,
        out: &mut Vec<Flat>,
    ) {
        let index = *counter;
        *counter += 1;
        let expanded = self.expanded.contains(&index);
        if visible {
            out.push(Flat {
                index,
                depth,
                label: item.label.clone(),
                id: item.id,
                has_children: item.has_children(),
                expanded,
            });
        }
        for child in &item.children {
            self.walk(child, depth + 1, visible && expanded, counter, out);
        }
    }

    /// Renders the visible nodes with indentation and expand markers, the cursor
    /// row highlighted and a scrollbar on overflow.
    pub fn render(&self, frame: &mut Frame, area: Rect, skin: &Skin) {
        let ascii = matches!(skin.glyphs.variant, GlyphVariant::Ascii);
        let lines: Vec<Line<'static>> = self
            .flatten()
            .iter()
            .map(|node| {
                let marker = marker(node.has_children, node.expanded, ascii);
                let indent = "  ".repeat(node.depth);
                Line::from(format!("{indent}{marker} {}", node.label))
            })
            .collect();
        let view = list::ListView {
            rows: lines,
            selected: self.cursor,
            offset: &self.offset,
        };
        let viewport = match &self.decor {
            Some(decor) => {
                list::render_boxed(frame, area, skin, view, decor, true)
            }
            // Without a box there is no border to hang the badge on, so the
            // bottom row carries it.
            None => list::render_counted(frame, area, skin, view),
        };
        self.viewport.set(viewport);
    }
}

/// The expand/collapse marker for a node.
fn marker(has_children: bool, expanded: bool, ascii: bool) -> &'static str {
    match (has_children, expanded, ascii) {
        (false, _, _) => " ",
        (true, true, false) => "\u{25be}", // â–¾
        (true, false, false) => "\u{25b8}", // â–¸
        (true, true, true) => "-",
        (true, false, true) => "+",
    }
}

#[cfg(test)]
mod tests {
    use crossterm::event::KeyModifiers;

    use super::*;

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn ctrl(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::CONTROL)
    }

    fn sample() -> TreeView {
        TreeView::new(vec![
            TreeItem::node(
                "src",
                vec![TreeItem::leaf("main.rs"), TreeItem::leaf("lib.rs")],
            ),
            TreeItem::leaf("Cargo.toml"),
        ])
    }

    #[test]
    fn starts_collapsed_showing_only_roots() {
        let view = sample();
        assert_eq!(view.flatten().len(), 2);
        assert_eq!(view.selected_label().as_deref(), Some("src"));
    }

    #[test]
    fn expanding_reveals_children() {
        let mut view = sample();
        view.handle_key(key(KeyCode::Right));
        assert_eq!(view.flatten().len(), 4);
    }

    #[test]
    fn collapsing_hides_children_again() {
        let mut view = sample();
        view.handle_key(key(KeyCode::Enter)); // expand src
        assert_eq!(view.flatten().len(), 4);
        view.handle_key(key(KeyCode::Enter)); // collapse src
        assert_eq!(view.flatten().len(), 2);
    }

    #[test]
    fn navigation_stays_in_bounds() {
        let mut view = sample();
        view.handle_key(key(KeyCode::Up)); // wrap to last
        assert_eq!(view.selected_label().as_deref(), Some("Cargo.toml"));
    }

    #[test]
    fn home_and_end_jump_to_the_first_and_last_row() {
        let mut view = sample();
        view.handle_key(key(KeyCode::End));
        assert_eq!(view.selected_label().as_deref(), Some("Cargo.toml"));
        view.handle_key(key(KeyCode::Home));
        assert_eq!(view.selected_label().as_deref(), Some("src"));
        // vim g/G mirror Home/End.
        view.handle_key(key(KeyCode::Char('G')));
        assert_eq!(view.selected_label().as_deref(), Some("Cargo.toml"));
        view.handle_key(key(KeyCode::Char('g')));
        assert_eq!(view.selected_label().as_deref(), Some("src"));
    }

    #[test]
    fn page_down_clamps_at_the_last_row() {
        // The default one-row viewport makes a page one row; PageDown from the
        // top still clamps at the last node rather than wrapping.
        let mut view = sample();
        view.handle_key(key(KeyCode::PageDown));
        assert_eq!(view.selected_label().as_deref(), Some("Cargo.toml"));
        view.handle_key(key(KeyCode::PageDown));
        assert_eq!(view.selected_label().as_deref(), Some("Cargo.toml"));
    }

    #[test]
    fn ctrl_chords_do_not_navigate_or_expand() {
        let mut view = sample();
        // crossterm reports Ctrl+L/Ctrl+H as `Char('l')`/`Char('h')`, which
        // would expand and collapse the node under the cursor.
        view.handle_key(ctrl(KeyCode::Char('l')));
        assert_eq!(view.flatten().len(), 2, "Ctrl+L must not expand");
        view.handle_key(key(KeyCode::Right)); // expand src for real
        view.handle_key(ctrl(KeyCode::Char('h')));
        assert_eq!(view.flatten().len(), 4, "Ctrl+H must not collapse");
        // Ctrl+J/Ctrl+G must not move the cursor either.
        view.handle_key(ctrl(KeyCode::Char('j')));
        view.handle_key(ctrl(KeyCode::Char('G')));
        assert_eq!(view.selected_label().as_deref(), Some("src"));
    }

    /// A folder holding two identically labelled leaves, so only the ids can
    /// tell them apart.
    fn sample_with_ids() -> TreeView {
        TreeView::new(vec![
            TreeItem::node(
                "decks",
                vec![
                    TreeItem::leaf_with_id("rust", 7),
                    TreeItem::leaf_with_id("rust", 9),
                ],
            ),
            TreeItem::leaf_with_id("geography", 3),
        ])
    }

    #[test]
    fn selected_id_survives_expanding_and_collapsing() {
        let mut view = sample_with_ids();
        assert_eq!(view.selected_id(), None); // the folder carries no id
        view.handle_key(key(KeyCode::Right)); // expand decks
        view.handle_key(key(KeyCode::Down));
        assert_eq!(view.selected_id(), Some(7));
        view.handle_key(key(KeyCode::Down));
        assert_eq!(view.selected_id(), Some(9));
        view.handle_key(key(KeyCode::Up));
        view.handle_key(key(KeyCode::Up));
        view.handle_key(key(KeyCode::Left)); // collapse decks
        view.handle_key(key(KeyCode::Down));
        assert_eq!(view.selected_id(), Some(3));
    }

    #[test]
    fn selected_is_leaf_separates_folders_from_leaves() {
        let mut view = sample_with_ids();
        assert!(!view.selected_is_leaf()); // on "decks"
        view.handle_key(key(KeyCode::Down));
        assert!(view.selected_is_leaf()); // on "geography"
        assert!(!TreeView::new(Vec::new()).selected_is_leaf());
    }
}