envision 0.16.0

A ratatui framework for collaborative TUI development with headless testing support
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
//! A treemap component for hierarchical proportional data visualization.
//!
//! [`Treemap`] displays hierarchical data as nested rectangles where each
//! rectangle's area is proportional to its value. Useful for disk usage,
//! memory allocation by module, request volume by service/endpoint, and
//! similar visualizations. State is stored in [`TreemapState`], updated via
//! [`TreemapMessage`], and produces [`TreemapOutput`].
//!
//!
//! # Example
//!
//! ```rust
//! use envision::component::{
//!     Component, Treemap, TreemapState, TreemapNode,
//! };
//! use ratatui::style::Color;
//!
//! let root = TreemapNode::new("root", 0.0)
//!     .with_child(TreemapNode::new("src", 60.0).with_color(Color::Blue))
//!     .with_child(TreemapNode::new("docs", 30.0).with_color(Color::Green))
//!     .with_child(TreemapNode::new("tests", 10.0).with_color(Color::Yellow));
//!
//! let state = TreemapState::new().with_root(root);
//! assert!(state.root().is_some());
//! assert_eq!(state.root().unwrap().children.len(), 3);
//! ```

use std::marker::PhantomData;

use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders};

use super::{Component, EventContext, RenderContext};
use crate::input::{Event, Key};

/// Layout algorithm module.
pub mod layout;
mod render;

pub use layout::{LayoutRect, squarified_layout};

/// A node in the treemap hierarchy.
///
/// Each node has a label, a value (which determines its proportional area),
/// a color, and optional children. Leaf nodes use their own value; parent
/// nodes compute their total value as the sum of children's total values.
///
/// # Example
///
/// ```rust
/// use envision::component::TreemapNode;
/// use ratatui::style::Color;
///
/// let leaf = TreemapNode::new("file.rs", 42.0).with_color(Color::Cyan);
/// assert!(leaf.is_leaf());
/// assert_eq!(leaf.total_value(), 42.0);
///
/// let parent = TreemapNode::new("src", 0.0)
///     .with_child(TreemapNode::new("main.rs", 30.0))
///     .with_child(TreemapNode::new("lib.rs", 20.0));
/// assert!(!parent.is_leaf());
/// assert_eq!(parent.total_value(), 50.0);
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct TreemapNode {
    /// Display label.
    pub label: String,
    /// Value (determines area proportion for leaf nodes).
    pub value: f64,
    /// Color for this node's rectangle.
    pub color: Color,
    /// Child nodes (if any).
    pub children: Vec<TreemapNode>,
}

impl TreemapNode {
    /// Creates a new leaf node with the given label and value.
    ///
    /// The default color is `Color::Gray`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapNode;
    /// use ratatui::style::Color;
    ///
    /// let node = TreemapNode::new("data", 100.0);
    /// assert_eq!(node.label, "data");
    /// assert_eq!(node.value, 100.0);
    /// assert_eq!(node.color, Color::Gray);
    /// assert!(node.children.is_empty());
    /// ```
    pub fn new(label: impl Into<String>, value: f64) -> Self {
        Self {
            label: label.into(),
            value,
            color: Color::Gray,
            children: Vec::new(),
        }
    }

    /// Sets the color for this node (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapNode;
    /// use ratatui::style::Color;
    ///
    /// let node = TreemapNode::new("data", 100.0).with_color(Color::Red);
    /// assert_eq!(node.color, Color::Red);
    /// ```
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    /// Sets the color for this node.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapNode;
    /// use ratatui::style::Color;
    ///
    /// let mut node = TreemapNode::new("data", 100.0);
    /// node.set_color(Color::Red);
    /// assert_eq!(node.color, Color::Red);
    /// ```
    pub fn set_color(&mut self, color: Color) {
        self.color = color;
    }

    /// Returns the color of this node.
    ///
    /// This is the getter counterpart to [`set_color`](Self::set_color).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapNode;
    /// use ratatui::style::Color;
    ///
    /// let node = TreemapNode::new("data", 100.0);
    /// assert_eq!(node.color(), Color::Gray);
    ///
    /// let node = TreemapNode::new("data", 100.0).with_color(Color::Cyan);
    /// assert_eq!(node.color(), Color::Cyan);
    /// ```
    pub fn color(&self) -> Color {
        self.color
    }

    /// Adds a single child node (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapNode;
    ///
    /// let parent = TreemapNode::new("root", 0.0)
    ///     .with_child(TreemapNode::new("a", 10.0))
    ///     .with_child(TreemapNode::new("b", 20.0));
    /// assert_eq!(parent.children.len(), 2);
    /// ```
    pub fn with_child(mut self, child: TreemapNode) -> Self {
        self.children.push(child);
        self
    }

    /// Sets multiple children at once (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapNode;
    ///
    /// let children = vec![
    ///     TreemapNode::new("a", 10.0),
    ///     TreemapNode::new("b", 20.0),
    /// ];
    /// let parent = TreemapNode::new("root", 0.0).with_children(children);
    /// assert_eq!(parent.children.len(), 2);
    /// ```
    pub fn with_children(mut self, children: Vec<TreemapNode>) -> Self {
        self.children = children;
        self
    }

    /// Returns the total value of this node.
    ///
    /// For leaf nodes, this is the node's own value. For parent nodes,
    /// this is the sum of all children's total values.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapNode;
    ///
    /// let leaf = TreemapNode::new("x", 42.0);
    /// assert_eq!(leaf.total_value(), 42.0);
    ///
    /// let parent = TreemapNode::new("p", 0.0)
    ///     .with_child(TreemapNode::new("a", 10.0))
    ///     .with_child(TreemapNode::new("b", 20.0));
    /// assert_eq!(parent.total_value(), 30.0);
    /// ```
    pub fn total_value(&self) -> f64 {
        if self.children.is_empty() {
            self.value
        } else {
            self.children.iter().map(|c| c.total_value()).sum()
        }
    }

    /// Returns true if this node has no children.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapNode;
    ///
    /// let leaf = TreemapNode::new("leaf", 10.0);
    /// assert!(leaf.is_leaf());
    ///
    /// let parent = TreemapNode::new("parent", 0.0)
    ///     .with_child(TreemapNode::new("child", 5.0));
    /// assert!(!parent.is_leaf());
    /// ```
    pub fn is_leaf(&self) -> bool {
        self.children.is_empty()
    }
}

/// Messages that can be sent to a Treemap.
///
/// # Example
///
/// ```rust
/// use envision::component::{
///     Component, Treemap, TreemapState, TreemapNode, TreemapMessage,
/// };
/// use ratatui::style::Color;
///
/// let root = TreemapNode::new("root", 0.0)
///     .with_child(TreemapNode::new("a", 30.0).with_color(Color::Red))
///     .with_child(TreemapNode::new("b", 20.0).with_color(Color::Blue));
///
/// let mut state = TreemapState::new().with_root(root);
/// state.update(TreemapMessage::SelectNext);
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum TreemapMessage {
    /// Set the root node.
    SetRoot(TreemapNode),
    /// Clear the treemap.
    Clear,
    /// Zoom into the selected node.
    ZoomIn,
    /// Zoom out to the parent.
    ZoomOut,
    /// Reset zoom to the root.
    ResetZoom,
    /// Select the next sibling.
    SelectNext,
    /// Select the previous sibling.
    SelectPrev,
    /// Select the first child of the current selection.
    SelectChild,
    /// Select the parent of the current selection.
    SelectParent,
}

/// Output messages from a Treemap.
///
/// # Example
///
/// ```rust
/// use envision::component::{
///     Component, Treemap, TreemapState, TreemapNode, TreemapMessage, TreemapOutput,
/// };
/// use ratatui::style::Color;
///
/// let root = TreemapNode::new("root", 0.0)
///     .with_child(
///         TreemapNode::new("a", 0.0)
///             .with_color(Color::Red)
///             .with_child(TreemapNode::new("x", 15.0))
///             .with_child(TreemapNode::new("y", 15.0)),
///     );
/// let mut state = TreemapState::new().with_root(root);
///
/// let output = Treemap::update(&mut state, TreemapMessage::ZoomIn);
/// assert_eq!(
///     output,
///     Some(TreemapOutput::ZoomedIn("a".to_string()))
/// );
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum TreemapOutput {
    /// A node was confirmed/selected.
    NodeSelected {
        /// Label of the selected node.
        label: String,
        /// Value of the selected node.
        value: f64,
    },
    /// Zoomed into a node.
    ZoomedIn(String),
    /// Zoomed out.
    ZoomedOut,
}

/// State for a Treemap component.
///
/// Contains the root node, selection path, zoom path, and display options.
///
/// # Example
///
/// ```rust
/// use envision::component::{TreemapState, TreemapNode};
/// use ratatui::style::Color;
///
/// let root = TreemapNode::new("root", 0.0)
///     .with_child(TreemapNode::new("src", 60.0).with_color(Color::Blue))
///     .with_child(TreemapNode::new("docs", 30.0).with_color(Color::Green));
///
/// let state = TreemapState::new()
///     .with_root(root)
///     .with_title("Disk Usage");
/// assert_eq!(state.title(), Some("Disk Usage"));
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct TreemapState {
    /// The root node of the tree.
    root: Option<TreemapNode>,
    /// Path to the currently selected node (indices at each depth).
    selected_path: Vec<usize>,
    /// Path to the zoomed-in node (empty = show root).
    zoom_path: Vec<usize>,
    /// Optional title for the treemap.
    title: Option<String>,
    /// Whether to show labels in rectangles.
    show_labels: bool,
    /// Whether to show values in rectangles.
    show_values: bool,
}

impl TreemapState {
    /// Creates a new empty treemap state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapState;
    ///
    /// let state = TreemapState::new();
    /// assert!(state.root().is_none());
    /// ```
    pub fn new() -> Self {
        Self {
            show_labels: true,
            ..Default::default()
        }
    }

    /// Sets the root node (builder pattern).
    ///
    /// Resets the selection and zoom paths.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{TreemapState, TreemapNode};
    ///
    /// let root = TreemapNode::new("root", 0.0)
    ///     .with_child(TreemapNode::new("a", 10.0));
    /// let state = TreemapState::new().with_root(root);
    /// assert!(state.root().is_some());
    /// ```
    pub fn with_root(mut self, root: TreemapNode) -> Self {
        self.root = Some(root);
        self.selected_path = vec![0];
        self.zoom_path = Vec::new();
        self
    }

    /// Sets the title (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapState;
    ///
    /// let state = TreemapState::new().with_title("Memory Usage");
    /// assert_eq!(state.title(), Some("Memory Usage"));
    /// ```
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Sets whether to show labels (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapState;
    ///
    /// let state = TreemapState::new().with_show_labels(false);
    /// assert!(!state.show_labels());
    /// ```
    pub fn with_show_labels(mut self, show: bool) -> Self {
        self.show_labels = show;
        self
    }

    /// Sets whether to show values (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapState;
    ///
    /// let state = TreemapState::new().with_show_values(true);
    /// assert!(state.show_values());
    /// ```
    pub fn with_show_values(mut self, show: bool) -> Self {
        self.show_values = show;
        self
    }

    // ---- Accessors ----

    /// Returns a reference to the root node, if set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{TreemapState, TreemapNode};
    ///
    /// let state = TreemapState::new().with_root(TreemapNode::new("r", 10.0));
    /// assert_eq!(state.root().unwrap().label, "r");
    /// ```
    pub fn root(&self) -> Option<&TreemapNode> {
        self.root.as_ref()
    }

    /// Sets the root node, resetting selection and zoom.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{TreemapState, TreemapNode};
    ///
    /// let mut state = TreemapState::new();
    /// state.set_root(TreemapNode::new("root", 0.0)
    ///     .with_child(TreemapNode::new("a", 10.0)));
    /// assert!(state.root().is_some());
    /// ```
    pub fn set_root(&mut self, root: TreemapNode) {
        self.root = Some(root);
        self.selected_path = vec![0];
        self.zoom_path = Vec::new();
    }

    /// Clears the treemap.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{TreemapState, TreemapNode};
    ///
    /// let mut state = TreemapState::new().with_root(TreemapNode::new("r", 10.0));
    /// state.clear();
    /// assert!(state.root().is_none());
    /// ```
    pub fn clear(&mut self) {
        self.root = None;
        self.selected_path.clear();
        self.zoom_path.clear();
    }

    /// Returns the node at the current zoom path.
    ///
    /// If the zoom path is empty, returns the root node.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{TreemapState, TreemapNode};
    ///
    /// let root = TreemapNode::new("root", 0.0)
    ///     .with_child(TreemapNode::new("a", 10.0));
    /// let state = TreemapState::new().with_root(root);
    /// let view = state.current_view_node();
    /// assert_eq!(view.unwrap().label, "root");
    /// ```
    pub fn current_view_node(&self) -> Option<&TreemapNode> {
        let root = self.root.as_ref()?;
        navigate_to_node(root, &self.zoom_path)
    }

    /// Returns the currently selected node.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{TreemapState, TreemapNode};
    /// use ratatui::style::Color;
    ///
    /// let root = TreemapNode::new("root", 0.0)
    ///     .with_child(TreemapNode::new("a", 30.0).with_color(Color::Red))
    ///     .with_child(TreemapNode::new("b", 20.0).with_color(Color::Blue));
    /// let state = TreemapState::new().with_root(root);
    /// let selected = state.selected_node();
    /// assert_eq!(selected.unwrap().label, "a");
    /// ```
    pub fn selected_node(&self) -> Option<&TreemapNode> {
        let view_node = self.current_view_node()?;
        if self.selected_path.is_empty() {
            return None;
        }
        let idx = self.selected_path[0];
        view_node.children.get(idx)
    }

    /// Returns the title, if set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapState;
    ///
    /// let state = TreemapState::new().with_title("Disk Usage");
    /// assert_eq!(state.title(), Some("Disk Usage"));
    /// ```
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Sets the title.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapState;
    ///
    /// let mut state = TreemapState::default();
    /// state.set_title("Disk Usage");
    /// assert_eq!(state.title(), Some("Disk Usage"));
    /// ```
    pub fn set_title(&mut self, title: impl Into<String>) {
        self.title = Some(title.into());
    }

    /// Returns whether labels are shown.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapState;
    ///
    /// let state = TreemapState::new();
    /// assert!(state.show_labels());
    /// ```
    pub fn show_labels(&self) -> bool {
        self.show_labels
    }

    /// Sets whether labels are shown.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{TreemapState, TreemapNode};
    ///
    /// let mut state = TreemapState::new();
    /// state.set_show_labels(false);
    /// assert!(!state.show_labels());
    /// ```
    pub fn set_show_labels(&mut self, show: bool) {
        self.show_labels = show;
    }

    /// Returns whether values are shown.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::TreemapState;
    ///
    /// let state = TreemapState::new();
    /// assert!(!state.show_values());
    /// ```
    pub fn show_values(&self) -> bool {
        self.show_values
    }

    /// Sets whether values are shown.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{TreemapState, TreemapNode};
    ///
    /// let mut state = TreemapState::new();
    /// state.set_show_values(true);
    /// assert!(state.show_values());
    /// ```
    pub fn set_show_values(&mut self, show: bool) {
        self.show_values = show;
    }

    /// Returns the selected child index at the current zoom level.
    pub(crate) fn selected_child_index(&self) -> usize {
        self.selected_path.first().copied().unwrap_or(0)
    }

    // ---- Instance methods ----

    /// Updates the state with a message, returning any output.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{TreemapMessage, TreemapNode, TreemapOutput, TreemapState};
    ///
    /// let root = TreemapNode::new("root", 0.0)
    ///     .with_child(
    ///         TreemapNode::new("parent", 0.0)
    ///             .with_child(TreemapNode::new("leaf", 10.0)),
    ///     );
    /// let mut state = TreemapState::new().with_root(root);
    /// let output = state.update(TreemapMessage::ZoomIn);
    /// assert_eq!(output, Some(TreemapOutput::ZoomedIn("parent".to_string())));
    /// ```
    pub fn update(&mut self, msg: TreemapMessage) -> Option<TreemapOutput> {
        Treemap::update(self, msg)
    }

    /// Returns the number of children of the current view node.
    fn current_child_count(&self) -> usize {
        self.current_view_node()
            .map(|n| n.children.len())
            .unwrap_or(0)
    }
}

/// Navigate to a node at the given path from the root.
fn navigate_to_node<'a>(root: &'a TreemapNode, path: &[usize]) -> Option<&'a TreemapNode> {
    let mut current = root;
    for &idx in path {
        current = current.children.get(idx)?;
    }
    Some(current)
}

/// A treemap component for hierarchical proportional data visualization.
///
/// Renders hierarchical data as nested colored rectangles where area is
/// proportional to value. Supports keyboard navigation for selection and
/// zoom in/out.
///
/// # Key Bindings
///
/// - `Left` / `h` -- Select previous sibling
/// - `Right` / `l` -- Select next sibling
/// - `Down` / `j` -- Select first child
/// - `Up` / `k` -- Select parent
/// - `Enter` -- Zoom into selected node
/// - `Escape` / `Backspace` -- Zoom out to parent
/// - `Home` -- Reset zoom to root
pub struct Treemap(PhantomData<()>);

impl Component for Treemap {
    type State = TreemapState;
    type Message = TreemapMessage;
    type Output = TreemapOutput;

    fn init() -> Self::State {
        TreemapState::new()
    }

    fn handle_event(
        _state: &Self::State,
        event: &Event,
        ctx: &EventContext,
    ) -> Option<Self::Message> {
        if !ctx.focused || ctx.disabled {
            return None;
        }

        let key = event.as_key()?;

        match key.code {
            Key::Left | Key::Char('h') => Some(TreemapMessage::SelectPrev),
            Key::Right | Key::Char('l') => Some(TreemapMessage::SelectNext),
            Key::Down | Key::Char('j') => Some(TreemapMessage::SelectChild),
            Key::Up | Key::Char('k') => Some(TreemapMessage::SelectParent),
            Key::Enter => Some(TreemapMessage::ZoomIn),
            Key::Esc | Key::Backspace => Some(TreemapMessage::ZoomOut),
            Key::Home => Some(TreemapMessage::ResetZoom),
            _ => None,
        }
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            TreemapMessage::SetRoot(root) => {
                state.set_root(root);
                None
            }
            TreemapMessage::Clear => {
                state.clear();
                None
            }
            TreemapMessage::ZoomIn => {
                let child_count = state.current_child_count();
                if child_count == 0 {
                    return None;
                }

                let selected_idx = state.selected_child_index();
                if selected_idx >= child_count {
                    return None;
                }

                // Check if the selected node has children to zoom into.
                let has_children = state
                    .current_view_node()
                    .and_then(|n| n.children.get(selected_idx))
                    .map(|n| !n.children.is_empty())
                    .unwrap_or(false);

                let label = state
                    .current_view_node()
                    .and_then(|n| n.children.get(selected_idx))
                    .map(|n| n.label.clone())
                    .unwrap_or_default();

                if has_children {
                    state.zoom_path.push(selected_idx);
                    state.selected_path = vec![0];
                    Some(TreemapOutput::ZoomedIn(label))
                } else {
                    // Leaf node -- emit NodeSelected.
                    let value = state
                        .current_view_node()
                        .and_then(|n| n.children.get(selected_idx))
                        .map(|n| n.total_value())
                        .unwrap_or(0.0);
                    Some(TreemapOutput::NodeSelected { label, value })
                }
            }
            TreemapMessage::ZoomOut => {
                if state.zoom_path.is_empty() {
                    return None;
                }
                let popped = state.zoom_path.pop().unwrap_or(0);
                state.selected_path = vec![popped];
                Some(TreemapOutput::ZoomedOut)
            }
            TreemapMessage::ResetZoom => {
                if state.zoom_path.is_empty() {
                    return None;
                }
                state.zoom_path.clear();
                state.selected_path = vec![0];
                Some(TreemapOutput::ZoomedOut)
            }
            TreemapMessage::SelectNext => {
                let child_count = state.current_child_count();
                if child_count == 0 {
                    return None;
                }
                let current = state.selected_child_index();
                if current + 1 < child_count {
                    state.selected_path = vec![current + 1];
                }
                None
            }
            TreemapMessage::SelectPrev => {
                let child_count = state.current_child_count();
                if child_count == 0 {
                    return None;
                }
                let current = state.selected_child_index();
                if current > 0 {
                    state.selected_path = vec![current - 1];
                }
                None
            }
            TreemapMessage::SelectChild => {
                // Navigate into the children of the selected node.
                let child_count = state.current_child_count();
                if child_count == 0 {
                    return None;
                }
                let selected_idx = state.selected_child_index();
                let has_children = state
                    .current_view_node()
                    .and_then(|n| n.children.get(selected_idx))
                    .map(|n| !n.children.is_empty())
                    .unwrap_or(false);

                if has_children {
                    // Zoom in and select first child.
                    let label = state
                        .current_view_node()
                        .and_then(|n| n.children.get(selected_idx))
                        .map(|n| n.label.clone())
                        .unwrap_or_default();
                    state.zoom_path.push(selected_idx);
                    state.selected_path = vec![0];
                    Some(TreemapOutput::ZoomedIn(label))
                } else {
                    None
                }
            }
            TreemapMessage::SelectParent => {
                if state.zoom_path.is_empty() {
                    return None;
                }
                let popped = state.zoom_path.pop().unwrap_or(0);
                state.selected_path = vec![popped];
                Some(TreemapOutput::ZoomedOut)
            }
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        if ctx.area.height < 3 || ctx.area.width < 3 {
            return;
        }

        crate::annotation::with_registry(|reg| {
            reg.register(
                ctx.area,
                crate::annotation::Annotation::container("treemap")
                    .with_focus(ctx.focused)
                    .with_disabled(ctx.disabled),
            );
        });

        let border_style = if ctx.disabled {
            ctx.theme.disabled_style()
        } else if ctx.focused {
            ctx.theme.focused_border_style()
        } else {
            ctx.theme.border_style()
        };

        let mut block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style);

        if let Some(ref title) = state.title {
            block = block.title(title.as_str());
        }

        let inner = block.inner(ctx.area);
        ctx.frame.render_widget(block, ctx.area);

        if inner.height == 0 || inner.width == 0 || state.root.is_none() {
            return;
        }

        render::render_treemap(
            state,
            ctx.frame,
            inner,
            ctx.theme,
            ctx.focused,
            ctx.disabled,
        );
    }
}

#[cfg(test)]
mod snapshot_tests;
#[cfg(test)]
mod tests;