rnk 0.17.3

A React-like declarative terminal UI framework for Rust, inspired by Ink
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
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! Tree component for hierarchical data display
//!
//! A tree view component for displaying hierarchical data with
//! expand/collapse functionality.
//!
//! # Features
//!
//! - Hierarchical data display
//! - Expand/collapse nodes
//! - Keyboard navigation
//! - Customizable icons and indentation
//! - Selection support
//!
//! # Example
//!
//! ```ignore
//! use rnk::components::tree::{Tree, TreeNode, TreeState};
//! use rnk::hooks::{use_signal, use_input};
//!
//! fn app() -> Element {
//!     let root = TreeNode::new("root", "Root")
//!         .child(TreeNode::new("child1", "Child 1")
//!             .child(TreeNode::leaf("leaf1", "Leaf 1")))
//!         .child(TreeNode::leaf("child2", "Child 2"));
//!
//!     let state = use_signal(|| TreeState::new(&root));
//!
//!     Tree::new(&root, &state.get())
//!         .into_element()
//! }
//! ```

use crate::components::{Box as RnkBox, Text};
use crate::core::{Color, Element, FlexDirection};
use std::collections::HashSet;

/// A node in the tree
#[derive(Debug, Clone)]
pub struct TreeNode<T: Clone> {
    /// Unique identifier for this node
    pub id: String,
    /// Display label
    pub label: String,
    /// Associated data
    pub data: Option<T>,
    /// Child nodes
    pub children: Vec<TreeNode<T>>,
}

impl<T: Clone> TreeNode<T> {
    /// Create a new tree node with children capability
    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            data: None,
            children: Vec::new(),
        }
    }

    /// Create a leaf node (no children)
    pub fn leaf(id: impl Into<String>, label: impl Into<String>) -> Self {
        Self::new(id, label)
    }

    /// Create a node with data
    pub fn with_data(id: impl Into<String>, label: impl Into<String>, data: T) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            data: Some(data),
            children: Vec::new(),
        }
    }

    /// Add a child node
    pub fn child(mut self, child: TreeNode<T>) -> Self {
        self.children.push(child);
        self
    }

    /// Add multiple children
    pub fn children(mut self, children: impl IntoIterator<Item = TreeNode<T>>) -> Self {
        self.children.extend(children);
        self
    }

    /// Check if this is a leaf node
    pub fn is_leaf(&self) -> bool {
        self.children.is_empty()
    }

    /// Check if this node has children
    pub fn has_children(&self) -> bool {
        !self.children.is_empty()
    }

    /// Get total node count (including self and all descendants)
    pub fn node_count(&self) -> usize {
        1 + self.children.iter().map(|c| c.node_count()).sum::<usize>()
    }

    /// Find a node by ID
    pub fn find(&self, id: &str) -> Option<&TreeNode<T>> {
        if self.id == id {
            return Some(self);
        }
        for child in &self.children {
            if let Some(found) = child.find(id) {
                return Some(found);
            }
        }
        None
    }

    /// Get all node IDs in depth-first order
    pub fn all_ids(&self) -> Vec<String> {
        let mut ids = vec![self.id.clone()];
        for child in &self.children {
            ids.extend(child.all_ids());
        }
        ids
    }
}

/// Tree state for tracking expanded nodes and selection
#[derive(Debug, Clone)]
pub struct TreeState {
    /// Set of expanded node IDs
    expanded: HashSet<String>,
    /// Currently selected node ID
    selected: Option<String>,
    /// Flattened visible node IDs (for navigation)
    visible_nodes: Vec<String>,
    /// Current cursor position in visible nodes
    cursor: usize,
}

impl TreeState {
    /// Create a new tree state
    pub fn new<T: Clone>(root: &TreeNode<T>) -> Self {
        let mut state = Self {
            expanded: HashSet::new(),
            selected: None,
            visible_nodes: Vec::new(),
            cursor: 0,
        };
        state.rebuild_visible(root);
        state
    }

    /// Create with root expanded
    pub fn with_root_expanded<T: Clone>(root: &TreeNode<T>) -> Self {
        let mut state = Self::new(root);
        state.expanded.insert(root.id.clone());
        state.rebuild_visible(root);
        state
    }

    /// Create with all nodes expanded
    pub fn all_expanded<T: Clone>(root: &TreeNode<T>) -> Self {
        let mut state = Self::new(root);
        state.expand_all(root);
        state.rebuild_visible(root);
        state
    }

    /// Check if a node is expanded
    pub fn is_expanded(&self, id: &str) -> bool {
        self.expanded.contains(id)
    }

    /// Expand a node
    pub fn expand(&mut self, id: &str) {
        self.expanded.insert(id.to_string());
    }

    /// Collapse a node
    pub fn collapse(&mut self, id: &str) {
        self.expanded.remove(id);
    }

    /// Toggle expand/collapse
    pub fn toggle(&mut self, id: &str) {
        if self.expanded.contains(id) {
            self.expanded.remove(id);
        } else {
            self.expanded.insert(id.to_string());
        }
    }

    /// Expand all nodes
    pub fn expand_all<T: Clone>(&mut self, root: &TreeNode<T>) {
        for id in root.all_ids() {
            self.expanded.insert(id);
        }
    }

    /// Collapse all nodes
    pub fn collapse_all(&mut self) {
        self.expanded.clear();
    }

    /// Get selected node ID
    pub fn selected(&self) -> Option<&str> {
        self.selected.as_deref()
    }

    /// Set selected node
    pub fn set_selected(&mut self, id: Option<String>) {
        self.selected = id;
    }

    /// Get cursor position
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// Get currently focused node ID
    pub fn focused(&self) -> Option<&str> {
        self.visible_nodes.get(self.cursor).map(|s| s.as_str())
    }

    /// Move cursor up
    pub fn cursor_up(&mut self) {
        if self.cursor > 0 {
            self.cursor -= 1;
        }
    }

    /// Move cursor down
    pub fn cursor_down(&mut self) {
        if self.cursor < self.visible_nodes.len().saturating_sub(1) {
            self.cursor += 1;
        }
    }

    /// Move cursor to first visible node
    pub fn cursor_first(&mut self) {
        self.cursor = 0;
    }

    /// Move cursor to last visible node
    pub fn cursor_last(&mut self) {
        self.cursor = self.visible_nodes.len().saturating_sub(1);
    }

    /// Toggle expand/collapse of focused node
    pub fn toggle_focused(&mut self) {
        if let Some(id) = self.focused().map(|s| s.to_string()) {
            self.toggle(&id);
        }
    }

    /// Select focused node
    pub fn select_focused(&mut self) {
        self.selected = self.focused().map(|s| s.to_string());
    }

    /// Rebuild visible nodes list based on expanded state
    pub fn rebuild_visible<T: Clone>(&mut self, root: &TreeNode<T>) {
        self.visible_nodes.clear();
        self.collect_visible(root);
        // Clamp cursor
        if self.cursor >= self.visible_nodes.len() {
            self.cursor = self.visible_nodes.len().saturating_sub(1);
        }
    }

    fn collect_visible<T: Clone>(&mut self, node: &TreeNode<T>) {
        self.visible_nodes.push(node.id.clone());
        if self.is_expanded(&node.id) {
            for child in &node.children {
                self.collect_visible(child);
            }
        }
    }

    /// Get visible node count
    pub fn visible_count(&self) -> usize {
        self.visible_nodes.len()
    }
}

/// Style configuration for the tree
#[derive(Debug, Clone)]
pub struct TreeStyle {
    /// Indentation per level (in spaces)
    pub indent: usize,
    /// Icon for expanded nodes
    pub expanded_icon: String,
    /// Icon for collapsed nodes
    pub collapsed_icon: String,
    /// Icon for leaf nodes
    pub leaf_icon: String,
    /// Connector for tree lines
    pub connector: String,
    /// Last item connector
    pub last_connector: String,
    /// Vertical line for tree structure
    pub vertical_line: String,
    /// Color for icons
    pub icon_color: Option<Color>,
    /// Color for selected item
    pub selected_color: Option<Color>,
    /// Color for focused item
    pub focused_color: Option<Color>,
    /// Background for focused item
    pub focused_bg: Option<Color>,
    /// Show tree lines
    pub show_lines: bool,
}

impl Default for TreeStyle {
    fn default() -> Self {
        Self {
            indent: 2,
            expanded_icon: "".to_string(),
            collapsed_icon: "".to_string(),
            leaf_icon: "".to_string(),
            connector: "├─".to_string(),
            last_connector: "└─".to_string(),
            vertical_line: "".to_string(),
            icon_color: Some(Color::Cyan),
            selected_color: Some(Color::Green),
            focused_color: Some(Color::Cyan),
            focused_bg: None,
            show_lines: true,
        }
    }
}

impl TreeStyle {
    /// Create a new style with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Set indentation
    pub fn indent(mut self, indent: usize) -> Self {
        self.indent = indent;
        self
    }

    /// Set expanded icon
    pub fn expanded_icon(mut self, icon: impl Into<String>) -> Self {
        self.expanded_icon = icon.into();
        self
    }

    /// Set collapsed icon
    pub fn collapsed_icon(mut self, icon: impl Into<String>) -> Self {
        self.collapsed_icon = icon.into();
        self
    }

    /// Set leaf icon
    pub fn leaf_icon(mut self, icon: impl Into<String>) -> Self {
        self.leaf_icon = icon.into();
        self
    }

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

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

    /// Enable/disable tree lines
    pub fn show_lines(mut self, show: bool) -> Self {
        self.show_lines = show;
        self
    }

    /// Use folder-style icons
    pub fn folder_icons() -> Self {
        Self {
            expanded_icon: "📂".to_string(),
            collapsed_icon: "📁".to_string(),
            leaf_icon: "📄".to_string(),
            ..Default::default()
        }
    }

    /// Use arrow-style icons
    pub fn arrow_icons() -> Self {
        Self {
            expanded_icon: "".to_string(),
            collapsed_icon: "".to_string(),
            leaf_icon: " ".to_string(),
            ..Default::default()
        }
    }

    /// Use plus/minus icons
    pub fn plus_minus_icons() -> Self {
        Self {
            expanded_icon: "[-]".to_string(),
            collapsed_icon: "[+]".to_string(),
            leaf_icon: " - ".to_string(),
            ..Default::default()
        }
    }

    /// Minimal style (no lines)
    pub fn minimal() -> Self {
        Self {
            show_lines: false,
            expanded_icon: "".to_string(),
            collapsed_icon: "".to_string(),
            leaf_icon: " ".to_string(),
            ..Default::default()
        }
    }
}

/// Tree component
#[derive(Debug, Clone)]
pub struct Tree<'a, T: Clone> {
    /// Root node
    root: &'a TreeNode<T>,
    /// Tree state
    state: &'a TreeState,
    /// Style configuration
    style: TreeStyle,
    /// Whether the tree is focused
    focused: bool,
}

impl<'a, T: Clone> Tree<'a, T> {
    /// Create a new tree
    pub fn new(root: &'a TreeNode<T>, state: &'a TreeState) -> Self {
        Self {
            root,
            state,
            style: TreeStyle::default(),
            focused: true,
        }
    }

    /// Set the style
    pub fn style(mut self, style: TreeStyle) -> Self {
        self.style = style;
        self
    }

    /// Set whether the tree is focused
    pub fn focused(mut self, focused: bool) -> Self {
        self.focused = focused;
        self
    }

    /// Convert to Element
    pub fn into_element(self) -> Element {
        let mut container = RnkBox::new().flex_direction(FlexDirection::Column);

        // Render tree recursively
        let elements = self.render_node(self.root, 0, vec![]);
        for elem in elements {
            container = container.child(elem);
        }

        container.into_element()
    }

    /// Render a node and its children
    fn render_node(
        &self,
        node: &TreeNode<T>,
        depth: usize,
        parent_is_last: Vec<bool>,
    ) -> Vec<Element> {
        let mut elements = Vec::new();

        let is_focused = self.focused && self.state.focused() == Some(&node.id);
        let is_selected = self.state.selected() == Some(&node.id);
        let is_expanded = self.state.is_expanded(&node.id);

        // Build prefix (tree lines)
        let mut prefix = String::new();
        if self.style.show_lines && depth > 0 {
            for &is_last in &parent_is_last[..parent_is_last.len().saturating_sub(1)] {
                if is_last {
                    prefix.push_str("  ");
                } else {
                    prefix.push_str(&self.style.vertical_line);
                }
            }
            if let Some(&is_last) = parent_is_last.last() {
                if is_last {
                    prefix.push_str(&self.style.last_connector);
                } else {
                    prefix.push_str(&self.style.connector);
                }
            }
        } else {
            prefix = " ".repeat(depth * self.style.indent);
        }

        // Build icon
        let icon = if node.is_leaf() {
            &self.style.leaf_icon
        } else if is_expanded {
            &self.style.expanded_icon
        } else {
            &self.style.collapsed_icon
        };

        // Build the line
        let line = format!("{}{} {}", prefix, icon, node.label);

        let mut text = Text::new(&line);

        // Apply styling
        if is_focused {
            if let Some(color) = self.style.focused_color {
                text = text.color(color);
            }
            if let Some(bg) = self.style.focused_bg {
                text = text.background(bg);
            }
            text = text.bold();
        } else if is_selected {
            if let Some(color) = self.style.selected_color {
                text = text.color(color);
            }
        }

        elements.push(text.into_element());

        // Render children if expanded
        if is_expanded {
            let child_count = node.children.len();
            for (i, child) in node.children.iter().enumerate() {
                let is_last = i == child_count - 1;
                let mut child_is_last = parent_is_last.clone();
                child_is_last.push(is_last);
                elements.extend(self.render_node(child, depth + 1, child_is_last));
            }
        }

        elements
    }
}

/// Handle tree input
pub fn handle_tree_input<T: Clone>(
    state: &mut TreeState,
    root: &TreeNode<T>,
    _input: &str,
    key: &crate::hooks::Key,
) -> bool {
    let mut handled = false;

    if key.up_arrow {
        state.cursor_up();
        handled = true;
    } else if key.down_arrow {
        state.cursor_down();
        handled = true;
    } else if key.left_arrow {
        // Collapse current node or move to parent
        if let Some(id) = state.focused().map(|s| s.to_string()) {
            if state.is_expanded(&id) {
                state.collapse(&id);
                state.rebuild_visible(root);
            }
        }
        handled = true;
    } else if key.right_arrow {
        // Expand current node
        if let Some(id) = state.focused().map(|s| s.to_string()) {
            if !state.is_expanded(&id) {
                state.expand(&id);
                state.rebuild_visible(root);
            }
        }
        handled = true;
    } else if key.return_key || key.space {
        // Toggle expand/collapse
        if let Some(id) = state.focused().map(|s| s.to_string()) {
            state.toggle(&id);
            state.rebuild_visible(root);
        }
        handled = true;
    } else if key.home {
        state.cursor_first();
        handled = true;
    } else if key.end {
        state.cursor_last();
        handled = true;
    }

    handled
}

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

    fn sample_tree() -> TreeNode<()> {
        TreeNode::new("root", "Root")
            .child(
                TreeNode::new("a", "Node A")
                    .child(TreeNode::leaf("a1", "Leaf A1"))
                    .child(TreeNode::leaf("a2", "Leaf A2")),
            )
            .child(TreeNode::leaf("b", "Node B"))
            .child(TreeNode::new("c", "Node C").child(TreeNode::leaf("c1", "Leaf C1")))
    }

    #[test]
    fn test_tree_node_creation() {
        let node = TreeNode::<()>::new("test", "Test Node");
        assert_eq!(node.id, "test");
        assert_eq!(node.label, "Test Node");
        assert!(node.is_leaf());
    }

    #[test]
    fn test_tree_node_with_children() {
        let node = TreeNode::<()>::new("parent", "Parent")
            .child(TreeNode::leaf("child1", "Child 1"))
            .child(TreeNode::leaf("child2", "Child 2"));

        assert!(!node.is_leaf());
        assert!(node.has_children());
        assert_eq!(node.children.len(), 2);
    }

    #[test]
    fn test_tree_node_count() {
        let tree = sample_tree();
        assert_eq!(tree.node_count(), 7); // root + a + a1 + a2 + b + c + c1
    }

    #[test]
    fn test_tree_find() {
        let tree = sample_tree();
        assert!(tree.find("a1").is_some());
        assert!(tree.find("nonexistent").is_none());
    }

    #[test]
    fn test_tree_state_new() {
        let tree = sample_tree();
        let state = TreeState::new(&tree);

        assert_eq!(state.visible_count(), 1); // Only root visible
        assert_eq!(state.cursor(), 0);
        assert!(!state.is_expanded("root"));
    }

    #[test]
    fn test_tree_state_expand() {
        let tree = sample_tree();
        let mut state = TreeState::new(&tree);

        state.expand("root");
        state.rebuild_visible(&tree);

        assert!(state.is_expanded("root"));
        assert_eq!(state.visible_count(), 4); // root + a + b + c
    }

    #[test]
    fn test_tree_state_expand_all() {
        let tree = sample_tree();
        let mut state = TreeState::new(&tree);

        state.expand_all(&tree);
        state.rebuild_visible(&tree);

        assert_eq!(state.visible_count(), 7); // All nodes visible
    }

    #[test]
    fn test_tree_state_navigation() {
        let tree = sample_tree();
        let mut state = TreeState::all_expanded(&tree);

        assert_eq!(state.cursor(), 0);
        assert_eq!(state.focused(), Some("root"));

        state.cursor_down();
        assert_eq!(state.focused(), Some("a"));

        state.cursor_down();
        assert_eq!(state.focused(), Some("a1"));

        state.cursor_up();
        assert_eq!(state.focused(), Some("a"));

        state.cursor_last();
        assert_eq!(state.focused(), Some("c1"));

        state.cursor_first();
        assert_eq!(state.focused(), Some("root"));
    }

    #[test]
    fn test_tree_state_toggle() {
        let tree = sample_tree();
        let mut state = TreeState::new(&tree);

        state.expand("root");
        state.rebuild_visible(&tree);
        assert_eq!(state.visible_count(), 4);

        state.toggle("root");
        state.rebuild_visible(&tree);
        assert_eq!(state.visible_count(), 1);
    }

    #[test]
    fn test_tree_style_presets() {
        let _default = TreeStyle::default();
        let _folder = TreeStyle::folder_icons();
        let _arrow = TreeStyle::arrow_icons();
        let _plus_minus = TreeStyle::plus_minus_icons();
        let _minimal = TreeStyle::minimal();
    }
}