envision 0.15.1

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
//! Composable UI components for TUI applications.
//!
//! This module provides traits for building reusable UI components that
//! follow the TEA (The Elm Architecture) pattern at a granular level.
//!
//! While the [`App`](crate::app::App) trait defines the top-level application,
//! components are smaller, composable pieces that can be combined to build
//! complex interfaces.
//!
//! # Core Traits
//!
//! - [`Component`]: The base trait for all components
//! - [`Toggleable`]: Components that can be shown or hidden
//! - [`RenderContext`]: Render-time context (frame, area, theme, focus) passed to `view`
//! - [`EventContext`]: Focus and disabled state passed to `handle_event`
//!
//! # Built-in Components
//!
//! - [`SelectableList`]: A scrollable list with keyboard navigation
//! - [`InputField`]: A text input field with cursor navigation
//! - [`Button`]: A clickable button with keyboard activation
//! - [`Checkbox`]: A toggleable checkbox with keyboard activation
//! - [`FocusManager`]: Focus coordination between components
//!
//! # Component vs App
//!
//! | Aspect | App | Component |
//! |--------|-----|-----------|
//! | Scope | Entire application | Part of the UI |
//! | State | Owns all state | Owns its own state |
//! | Messages | All app messages | Component-specific messages |
//! | Output | Commands (side effects) | Messages to parent |
//! | Rendering | Full frame | Specific area |
//!
//! # Example
//!
//! ```rust
//! use envision::component::{Component, RenderContext};
//!
//! struct Counter;
//!
//! #[derive(Clone, Default)]
//! struct CounterState {
//!     value: i32,
//! }
//!
//! #[derive(Clone)]
//! enum CounterMsg {
//!     Increment,
//!     Decrement,
//! }
//!
//! #[derive(Clone)]
//! enum CounterOutput {
//!     ValueChanged(i32),
//! }
//!
//! impl Component for Counter {
//!     type State = CounterState;
//!     type Message = CounterMsg;
//!     type Output = CounterOutput;
//!
//!     fn init() -> Self::State {
//!         CounterState::default()
//!     }
//!
//!     fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
//!         match msg {
//!             CounterMsg::Increment => state.value += 1,
//!             CounterMsg::Decrement => state.value -= 1,
//!         }
//!         Some(CounterOutput::ValueChanged(state.value))
//!     }
//!
//!     fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
//!         let style = if ctx.focused {
//!             ctx.theme.focused_style()
//!         } else {
//!             ctx.theme.normal_style()
//!         };
//!         let text = format!("Count: {}", state.value);
//!         ctx.render_widget(
//!             ratatui::widgets::Paragraph::new(text).style(style),
//!         );
//!     }
//! }
//! ```

use crate::input::Event;

// Input components
#[cfg(feature = "input-components")]
mod button;
#[cfg(feature = "input-components")]
mod checkbox;
#[cfg(feature = "input-components")]
mod dropdown;
#[cfg(feature = "input-components")]
mod input_field;
#[cfg(feature = "input-components")]
pub mod line_input;
#[cfg(feature = "input-components")]
mod number_input;
#[cfg(feature = "input-components")]
mod radio_group;
#[cfg(feature = "input-components")]
mod select;
#[cfg(feature = "input-components")]
mod slider;
#[cfg(feature = "input-components")]
mod switch;
#[cfg(feature = "input-components")]
mod text_area;

// Compound components
#[cfg(feature = "compound-components")]
mod alert_panel;
#[cfg(feature = "compound-components")]
mod box_plot;
#[cfg(feature = "compound-components")]
mod chart;
#[cfg(feature = "compound-components")]
mod conversation_view;
#[cfg(feature = "compound-components")]
mod data_grid;
#[cfg(feature = "compound-components")]
pub mod dependency_graph;

#[cfg(feature = "compound-components")]
pub mod diff_viewer;
#[cfg(feature = "compound-components")]
mod event_stream;
#[cfg(feature = "compound-components")]
pub mod file_browser;
#[cfg(feature = "compound-components")]
mod flame_graph;
#[cfg(feature = "compound-components")]
mod form;
#[cfg(feature = "compound-components")]
mod heatmap;
#[cfg(feature = "compound-components")]
mod histogram;
#[cfg(feature = "compound-components")]
mod log_correlation;
#[cfg(feature = "compound-components")]
mod log_viewer;
#[cfg(feature = "compound-components")]
mod metrics_dashboard;
#[cfg(feature = "compound-components")]
pub mod pane_layout;
#[cfg(feature = "compound-components")]
mod searchable_list;
#[cfg(feature = "compound-components")]
mod span_tree;
#[cfg(feature = "compound-components")]
mod split_panel;
#[cfg(feature = "compound-components")]
mod timeline;
#[cfg(feature = "compound-components")]
pub mod treemap;

// Data components
#[cfg(feature = "data-components")]
mod loading_list;
#[cfg(feature = "data-components")]
mod selectable_list;
#[cfg(feature = "data-components")]
mod table;
#[cfg(feature = "data-components")]
mod tree;

// Display components
#[cfg(feature = "display-components")]
mod big_text;
#[cfg(feature = "display-components")]
mod calendar;
#[cfg(feature = "display-components")]
mod canvas;
#[cfg(feature = "display-components")]
pub mod code_block;
#[cfg(feature = "display-components")]
mod collapsible;
#[cfg(feature = "display-components")]
mod divider;
#[cfg(feature = "display-components")]
mod gauge;
#[cfg(feature = "display-components")]
mod help_panel;
#[cfg(feature = "display-components")]
mod key_hints;
#[cfg(feature = "display-components")]
mod multi_progress;
#[cfg(feature = "display-components")]
mod paginator;
#[cfg(feature = "display-components")]
pub mod progress_bar;
#[cfg(feature = "display-components")]
mod scroll_view;
#[cfg(feature = "display-components")]
mod scrollable_text;
#[cfg(feature = "display-components")]
mod sparkline;
#[cfg(feature = "display-components")]
mod spinner;
#[cfg(feature = "display-components")]
mod status_bar;
#[cfg(feature = "display-components")]
mod status_log;
#[cfg(feature = "display-components")]
pub mod styled_text;
#[cfg(feature = "display-components")]
pub mod terminal_output;
#[cfg(feature = "display-components")]
mod title_card;
#[cfg(feature = "display-components")]
mod toast;
#[cfg(feature = "display-components")]
mod usage_display;

// Navigation components
#[cfg(feature = "navigation-components")]
mod accordion;
#[cfg(feature = "navigation-components")]
mod breadcrumb;
#[cfg(feature = "navigation-components")]
pub mod command_palette;
#[cfg(feature = "navigation-components")]
mod menu;
#[cfg(feature = "navigation-components")]
mod router;
#[cfg(feature = "navigation-components")]
pub mod step_indicator;
#[cfg(feature = "navigation-components")]
mod tab_bar;
#[cfg(feature = "navigation-components")]
mod tabs;

// Overlay components
#[cfg(feature = "overlay-components")]
pub mod confirm_dialog;
#[cfg(feature = "overlay-components")]
mod dialog;
#[cfg(feature = "overlay-components")]
mod tooltip;

// Markdown components
#[cfg(feature = "markdown")]
pub mod markdown_renderer;

// Always available
mod context;
mod focus_manager;

// Input components
#[cfg(feature = "input-components")]
pub use button::{Button, ButtonMessage, ButtonOutput, ButtonState};
#[cfg(feature = "input-components")]
pub use checkbox::{Checkbox, CheckboxMessage, CheckboxOutput, CheckboxState};
#[cfg(feature = "input-components")]
pub use dropdown::{Dropdown, DropdownMessage, DropdownOutput, DropdownState};
#[cfg(feature = "input-components")]
pub use input_field::{InputField, InputFieldMessage, InputFieldOutput, InputFieldState};
#[cfg(feature = "input-components")]
pub use line_input::{LineInput, LineInputMessage, LineInputOutput, LineInputState};
#[cfg(feature = "input-components")]
pub use number_input::{NumberInput, NumberInputMessage, NumberInputOutput, NumberInputState};
#[cfg(feature = "input-components")]
pub use radio_group::{RadioGroup, RadioGroupMessage, RadioGroupOutput, RadioGroupState};
#[cfg(feature = "input-components")]
pub use select::{Select, SelectMessage, SelectOutput, SelectState};
#[cfg(feature = "input-components")]
pub use slider::{Slider, SliderMessage, SliderOrientation, SliderOutput, SliderState};
#[cfg(feature = "input-components")]
pub use switch::{Switch, SwitchMessage, SwitchOutput, SwitchState};
#[cfg(feature = "input-components")]
pub use text_area::{TextArea, TextAreaMessage, TextAreaOutput, TextAreaState};

// Data components
#[cfg(feature = "data-components")]
pub use loading_list::{
    ItemState, LoadingList, LoadingListItem, LoadingListMessage, LoadingListOutput,
    LoadingListState,
};
#[cfg(feature = "data-components")]
pub use selectable_list::{
    SelectableList, SelectableListMessage, SelectableListOutput, SelectableListState,
};
#[cfg(feature = "data-components")]
pub use table::{
    Column, SortComparator, SortDirection, Table, TableMessage, TableOutput, TableRow, TableState,
    date_comparator, numeric_comparator,
};
#[cfg(feature = "data-components")]
pub use tree::{Tree, TreeMessage, TreeNode, TreeOutput, TreeState};

// Display components
#[cfg(feature = "display-components")]
pub use big_text::{BigText, BigTextMessage, BigTextState, big_char, big_char_width};
#[cfg(feature = "display-components")]
pub use calendar::{Calendar, CalendarMessage, CalendarOutput, CalendarState};
#[cfg(feature = "display-components")]
pub use canvas::{Canvas, CanvasMarker, CanvasMessage, CanvasShape, CanvasState};
#[cfg(feature = "display-components")]
pub use code_block::{CodeBlock, CodeBlockMessage, CodeBlockState, Language};
#[cfg(feature = "display-components")]
pub use collapsible::{Collapsible, CollapsibleMessage, CollapsibleOutput, CollapsibleState};
#[cfg(feature = "display-components")]
pub use divider::{Divider, DividerMessage, DividerOrientation, DividerState};
#[cfg(feature = "display-components")]
pub use gauge::{Gauge, GaugeMessage, GaugeOutput, GaugeState, GaugeVariant, ThresholdZone};
#[cfg(feature = "display-components")]
pub use help_panel::{HelpPanel, HelpPanelMessage, HelpPanelState, KeyBinding, KeyBindingGroup};
#[cfg(feature = "display-components")]
pub use key_hints::{KeyHint, KeyHints, KeyHintsLayout, KeyHintsMessage, KeyHintsState};
#[cfg(feature = "display-components")]
pub use multi_progress::{
    MultiProgress, MultiProgressMessage, MultiProgressOutput, MultiProgressState, ProgressItem,
    ProgressItemStatus,
};
#[cfg(feature = "display-components")]
pub use paginator::{Paginator, PaginatorMessage, PaginatorOutput, PaginatorState, PaginatorStyle};
#[cfg(feature = "display-components")]
pub use progress_bar::{
    ProgressBar, ProgressBarMessage, ProgressBarOutput, ProgressBarState, format_eta,
};
#[cfg(feature = "display-components")]
pub use sparkline::{
    Sparkline, SparklineDirection, SparklineMessage, SparklineOutput, SparklineState,
};
#[cfg(feature = "display-components")]
pub use spinner::{Spinner, SpinnerMessage, SpinnerState, SpinnerStyle};

// Compound components
#[cfg(feature = "compound-components")]
pub use alert_panel::{
    AlertMetric, AlertPanel, AlertPanelMessage, AlertPanelOutput, AlertPanelState, AlertState,
    AlertThreshold,
};
#[cfg(feature = "compound-components")]
pub use box_plot::{BoxPlot, BoxPlotData, BoxPlotMessage, BoxPlotOrientation, BoxPlotState};
#[cfg(feature = "compound-components")]
pub use chart::{
    BarMode, Chart, ChartAnnotation, ChartGrid, ChartKind, ChartMessage, ChartOutput, ChartState,
    DEFAULT_PALETTE, DataSeries, Scale, ThresholdLine, VerticalLine, chart_palette_color,
};
#[cfg(feature = "compound-components")]
pub use conversation_view::{
    ConversationMessage, ConversationRole, ConversationView, ConversationViewMessage,
    ConversationViewOutput, ConversationViewState, MessageBlock, MessageHandle,
};
#[cfg(feature = "compound-components")]
pub use data_grid::{DataGrid, DataGridMessage, DataGridOutput, DataGridState};
#[cfg(feature = "compound-components")]
pub use dependency_graph::{
    DependencyGraph, DependencyGraphMessage, DependencyGraphOutput, DependencyGraphState,
    GraphEdge, GraphNode, GraphOrientation, NodeStatus,
    layout::LayoutEdge as DependencyGraphLayoutEdge,
    layout::LayoutNode as DependencyGraphLayoutNode,
};
#[cfg(feature = "compound-components")]
pub use diff_viewer::{
    DiffHunk, DiffLine, DiffLineType, DiffMode, DiffViewer, DiffViewerMessage, DiffViewerOutput,
    DiffViewerState,
};
#[cfg(feature = "compound-components")]
pub use event_stream::{
    EventLevel, EventStream, EventStreamMessage, EventStreamOutput, EventStreamState, StreamEvent,
};
#[cfg(feature = "compound-components")]
pub use file_browser::{
    FileBrowser, FileBrowserMessage, FileBrowserOutput, FileBrowserState, FileEntry,
    FileSortDirection, FileSortField, SelectionMode,
};
#[cfg(feature = "compound-components")]
pub use flame_graph::{
    FlameGraph, FlameGraphMessage, FlameGraphOutput, FlameGraphState, FlameNode,
};
#[cfg(feature = "compound-components")]
pub use form::{Form, FormField, FormFieldKind, FormMessage, FormOutput, FormState, FormValue};
#[cfg(feature = "compound-components")]
pub use heatmap::{
    DistributionMap, Heatmap, HeatmapColorScale, HeatmapMessage, HeatmapOutput, HeatmapState,
    value_to_color,
};
#[cfg(feature = "compound-components")]
pub use histogram::{BinMethod, Histogram, HistogramMessage, HistogramState};
#[cfg(feature = "compound-components")]
pub use log_correlation::{
    CorrelationEntry, CorrelationLevel, LogCorrelation, LogCorrelationMessage,
    LogCorrelationOutput, LogCorrelationState, LogStream,
};
#[cfg(feature = "compound-components")]
pub use log_viewer::{LogViewer, LogViewerMessage, LogViewerOutput, LogViewerState};
#[cfg(feature = "compound-components")]
pub use metrics_dashboard::{
    MetricKind, MetricWidget, MetricsDashboard, MetricsDashboardMessage, MetricsDashboardOutput,
    MetricsDashboardState,
};
#[cfg(feature = "compound-components")]
pub use pane_layout::{PaneLayout, PaneLayoutMessage, PaneLayoutOutput, PaneLayoutState};
#[cfg(feature = "compound-components")]
pub use searchable_list::{
    SearchableList, SearchableListMessage, SearchableListOutput, SearchableListState,
};
#[cfg(feature = "compound-components")]
pub use span_tree::{FlatSpan, SpanNode, SpanTree, SpanTreeMessage, SpanTreeOutput, SpanTreeState};
#[cfg(feature = "compound-components")]
pub use split_panel::{
    SplitOrientation, SplitPanel, SplitPanelMessage, SplitPanelOutput, SplitPanelState,
};
#[cfg(feature = "compound-components")]
pub use timeline::{
    SelectedType, Timeline, TimelineEvent, TimelineMessage, TimelineOutput, TimelineSpan,
    TimelineState,
};
#[cfg(feature = "compound-components")]
pub use treemap::{Treemap, TreemapMessage, TreemapNode, TreemapOutput, TreemapState};

#[cfg(feature = "display-components")]
pub use scroll_view::{ScrollView, ScrollViewMessage, ScrollViewState};
#[cfg(feature = "display-components")]
pub use scrollable_text::{
    ScrollableText, ScrollableTextMessage, ScrollableTextOutput, ScrollableTextState,
};
#[cfg(feature = "display-components")]
pub use status_bar::{
    Section, StatusBar, StatusBarItem, StatusBarItemContent, StatusBarMessage, StatusBarState,
    StatusBarStyle,
};
#[cfg(feature = "display-components")]
pub use status_log::{
    StatusLog, StatusLogEntry, StatusLogLevel, StatusLogMessage, StatusLogOutput, StatusLogState,
};
#[cfg(feature = "display-components")]
pub use styled_text::{StyledText, StyledTextMessage, StyledTextOutput, StyledTextState};
#[cfg(feature = "display-components")]
pub use terminal_output::{
    AnsiSegment, TerminalOutput, TerminalOutputMessage, TerminalOutputOutput, TerminalOutputState,
    parse_ansi,
};
#[cfg(feature = "display-components")]
pub use title_card::{TitleCard, TitleCardMessage, TitleCardState};
#[cfg(feature = "display-components")]
pub use toast::{Toast, ToastItem, ToastLevel, ToastMessage, ToastOutput, ToastState};
#[cfg(feature = "display-components")]
pub use usage_display::{
    UsageDisplay, UsageDisplayMessage, UsageDisplayState, UsageLayout, UsageMetric,
};

// Navigation components
#[cfg(feature = "navigation-components")]
pub use accordion::{Accordion, AccordionMessage, AccordionOutput, AccordionPanel, AccordionState};
#[cfg(feature = "navigation-components")]
pub use breadcrumb::{
    Breadcrumb, BreadcrumbMessage, BreadcrumbOutput, BreadcrumbSegment, BreadcrumbState,
};
#[cfg(feature = "navigation-components")]
pub use command_palette::{
    CommandPalette, CommandPaletteMessage, CommandPaletteOutput, CommandPaletteState, PaletteItem,
};
#[cfg(feature = "navigation-components")]
pub use menu::{Menu, MenuItem, MenuMessage, MenuOutput, MenuState};
#[cfg(feature = "navigation-components")]
pub use router::{NavigationMode, Router, RouterMessage, RouterOutput, RouterState};
#[cfg(feature = "navigation-components")]
pub use step_indicator::{
    StepIndicator, StepIndicatorMessage, StepIndicatorOutput, StepIndicatorState,
};
#[cfg(feature = "navigation-components")]
pub use tab_bar::{Tab, TabBar, TabBarMessage, TabBarOutput, TabBarState};
#[cfg(feature = "navigation-components")]
pub use tabs::{Tabs, TabsMessage, TabsOutput, TabsState};

// Overlay components
#[cfg(feature = "overlay-components")]
pub use confirm_dialog::{
    ConfirmDialog, ConfirmDialogMessage, ConfirmDialogOutput, ConfirmDialogResult,
    ConfirmDialogState,
};
#[cfg(feature = "overlay-components")]
pub use dialog::{Dialog, DialogButton, DialogMessage, DialogOutput, DialogState};
#[cfg(feature = "overlay-components")]
pub use tooltip::{Tooltip, TooltipMessage, TooltipOutput, TooltipPosition, TooltipState};

// Markdown components
#[cfg(feature = "markdown")]
pub use markdown_renderer::{MarkdownRenderer, MarkdownRendererMessage, MarkdownRendererState};

// Always available
pub use context::{EventContext, RenderContext};
pub use focus_manager::FocusManager;

/// A composable UI component with its own state and message handling.
///
/// Components are the building blocks of complex TUI applications. Each
/// component manages its own state, handles its own messages, and renders
/// to a specific area of the screen.
///
/// # Associated Types
///
/// - `State`: The component's internal state. Derive `Clone` if you need snapshots.
/// - `Message`: Messages the component can receive from its parent or from
///   user interaction.
/// - `Output`: Messages the component emits to communicate with its parent.
///   Use `()` if the component doesn't need to communicate outward.
///
/// # Design Pattern
///
/// Components follow the same TEA pattern as [`App`](crate::app::App), but
/// at a smaller scale:
///
/// 1. Parent sends `Message` to component
/// 2. Component updates its `State`
/// 3. Component optionally emits `Output` to parent
/// 4. Component renders itself to its designated area
pub trait Component: Sized {
    /// The component's internal state type.
    ///
    /// This should contain all data needed to render the component.
    /// Deriving `Clone` is recommended but not required.
    type State;

    /// Messages this component can receive.
    ///
    /// These typically come from user input or parent components.
    type Message;

    /// Messages this component can emit to its parent.
    ///
    /// Use `()` if the component doesn't need to communicate upward.
    /// This enables child-to-parent communication without tight coupling.
    type Output;

    /// Initialize the component state.
    ///
    /// Returns the initial state for this component.
    fn init() -> Self::State;

    /// Update component state based on a message.
    ///
    /// Returns an optional output message for the parent to handle.
    /// Return `None` if no parent notification is needed.
    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output>;

    /// Render the component to the given area.
    ///
    /// Unlike [`App::view`](crate::app::App::view) which renders to the full
    /// frame, components render to a specific area carried by the
    /// [`RenderContext`]. The context bundles the frame, render area, theme,
    /// and focus/disabled state.
    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>);

    /// Renders the component with optional tracing instrumentation.
    ///
    /// When the `tracing` feature is enabled, this emits a trace-level span
    /// around the [`view`](Component::view) call with the component type name
    /// and render area dimensions. When the feature is disabled, this is
    /// identical to calling `view` directly.
    fn traced_view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        #[cfg(feature = "tracing")]
        let _span = tracing::trace_span!(
            "component_view",
            component = std::any::type_name::<Self>(),
            area.x = ctx.area.x,
            area.y = ctx.area.y,
            area.width = ctx.area.width,
            area.height = ctx.area.height,
        )
        .entered();
        Self::view(state, ctx);
    }

    /// Maps an input event to a component message.
    ///
    /// This is the read-only half of event handling. It inspects the
    /// component's state, the incoming event, and the [`EventContext`]
    /// (which carries focused/disabled state from the parent), and
    /// returns an appropriate message if the event is relevant.
    ///
    /// Components should check `ctx.focused` and `ctx.disabled` to
    /// decide whether to process the event. The same focus/disabled
    /// state should be passed to both `handle_event` and
    /// [`view`](Component::view) (via the [`RenderContext`]) so that
    /// visual state and event routing are always consistent.
    ///
    /// The default implementation returns `None` (ignores all events).
    fn handle_event(
        state: &Self::State,
        event: &Event,
        ctx: &EventContext,
    ) -> Option<Self::Message> {
        let _ = (state, event, ctx);
        None
    }

    /// Dispatches an event by mapping it to a message and updating state.
    ///
    /// This combines [`handle_event`](Component::handle_event) and
    /// [`update`](Component::update) into a single call. If the event
    /// produces a message, the message is passed to `update` and the
    /// output is returned.
    ///
    /// This is the primary method users should call for event routing.
    fn dispatch_event(
        state: &mut Self::State,
        event: &Event,
        ctx: &EventContext,
    ) -> Option<Self::Output> {
        #[cfg(feature = "tracing")]
        let _span = tracing::debug_span!(
            "component_dispatch",
            component = std::any::type_name::<Self>(),
            event_kind = event.kind_name(),
        )
        .entered();

        let msg = Self::handle_event(state, event, ctx);

        #[cfg(feature = "tracing")]
        tracing::trace!(produced_message = msg.is_some(), "handle_event complete");

        if let Some(msg) = msg {
            let output = Self::update(state, msg);
            #[cfg(feature = "tracing")]
            tracing::trace!(has_output = output.is_some(), "update complete");
            output
        } else {
            None
        }
    }
}

/// A component that can be shown or hidden.
///
/// This is useful for panels, dialogs, and other UI elements that
/// can be toggled on and off. When hidden, the component should not
/// be rendered or receive input.
///
/// # Example
///
/// ```rust
/// use envision::component::{Component, RenderContext, Toggleable};
///
/// struct HelpPanel;
///
/// #[derive(Clone)]
/// struct HelpPanelState {
///     visible: bool,
///     content: String,
/// }
///
/// # #[derive(Clone)]
/// # enum HelpPanelMsg {}
/// # #[derive(Clone)]
/// # enum HelpPanelOutput {}
/// #
/// # impl Component for HelpPanel {
/// #     type State = HelpPanelState;
/// #     type Message = HelpPanelMsg;
/// #     type Output = HelpPanelOutput;
/// #     fn init() -> Self::State { HelpPanelState { visible: false, content: String::new() } }
/// #     fn update(_: &mut Self::State, _: Self::Message) -> Option<Self::Output> { None }
/// #     fn view(_: &Self::State, _: &mut RenderContext<'_, '_>) {}
/// # }
/// #
/// impl Toggleable for HelpPanel {
///     fn is_visible(state: &Self::State) -> bool {
///         state.visible
///     }
///
///     fn set_visible(state: &mut Self::State, visible: bool) {
///         state.visible = visible;
///     }
/// }
///
/// // Usage:
/// let mut state = HelpPanel::init();
/// assert!(!HelpPanel::is_visible(&state));
///
/// HelpPanel::toggle(&mut state);
/// assert!(HelpPanel::is_visible(&state));
///
/// HelpPanel::hide(&mut state);
/// assert!(!HelpPanel::is_visible(&state));
/// ```
pub trait Toggleable: Component {
    /// Returns true if this component is currently visible.
    fn is_visible(state: &Self::State) -> bool;

    /// Sets the visibility of this component.
    fn set_visible(state: &mut Self::State, visible: bool);

    /// Toggles the visibility of this component.
    fn toggle(state: &mut Self::State) {
        let visible = Self::is_visible(state);
        Self::set_visible(state, !visible);
    }

    /// Shows this component.
    ///
    /// Convenience method equivalent to `set_visible(state, true)`.
    fn show(state: &mut Self::State) {
        Self::set_visible(state, true);
    }

    /// Hides this component.
    ///
    /// Convenience method equivalent to `set_visible(state, false)`.
    fn hide(state: &mut Self::State) {
        Self::set_visible(state, false);
    }
}

#[cfg(any(test, feature = "test-utils"))]
pub mod test_utils;
#[cfg(test)]
mod tests;