envision 0.10.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
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
//! Component Showcase - Demonstrating 18+ Envision components in a single application.
//!
//! This example shows how to compose multiple components together into a cohesive
//! application using The Elm Architecture (TEA) pattern. It demonstrates:
//!
//! - **Event dispatch**: Using `dispatch_event` to route events to the focused component
//! - **Instance methods**: Using `state.set_focused()` instead of `Component::set_focused()`
//! - **Simplified messages**: Global hotkeys only; component events dispatched directly
//! - **Focus management**: Using `FocusManager` to coordinate keyboard focus
//! - **Output handling**: Reacting to component outputs (selections, confirmations)
//! - **Theming**: Consistent styling across all components via `Theme`
//!
//! # Components Used
//!
//! - Menu (horizontal navigation bar)
//! - Tabs (panel switching)
//! - InputField (text entry)
//! - Checkbox (boolean toggle)
//! - RadioGroup (single selection from options)
//! - Button (form submission)
//! - SelectableList (item selection with scrolling)
//! - Table (data display with columns)
//! - ProgressBar (progress indicator)
//! - Spinner (loading animation)
//! - Toast (notification popups)
//! - Dialog (modal confirmation)
//! - Sparkline (compact data trend)
//! - Gauge (visual measurement)
//! - Heatmap (2D color grid)
//! - Timeline (event/span visualization)
//! - CommandPalette (fuzzy finder)
//! - CodeBlock (syntax highlighting)
//!
//! Run with: `cargo run --example component_showcase --features full`

use envision::component::code_block::highlight::Language;
use envision::component::{
    ButtonState, CheckboxState, CodeBlock, CodeBlockState, Column, CommandPalette,
    CommandPaletteState, Component, Dialog, DialogMessage, DialogOutput, DialogState, FocusManager,
    Gauge, GaugeState, GaugeVariant, Heatmap, HeatmapState, InputFieldState, MenuItem, MenuOutput,
    MenuState, PaletteItem, ProgressBarState, RadioGroupState, SelectableListState, Sparkline,
    SparklineState, Spinner, SpinnerMessage, SpinnerState, Table, TableOutput, TableRow,
    TableState, Tabs, TabsState, Timeline, TimelineEvent, TimelineSpan, TimelineState, Toast,
    ToastMessage, ToastState,
};
use envision::prelude::*;
use ratatui::layout::{Alignment, Constraint, Layout};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};

// ---------------------------------------------------------------------------
// Focus IDs for FocusManager
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, PartialEq, Eq)]
enum FocusId {
    Menu,
    Tabs,
    Input,
    Checkbox,
    Radio,
    SubmitButton,
    List,
    Table,
    Progress,
    Heatmap,
    Timeline,
    CommandPalette,
    CodeBlock,
}

// ---------------------------------------------------------------------------
// Table row type
// ---------------------------------------------------------------------------

#[derive(Clone, Debug)]
struct UserRow {
    name: String,
    role: String,
    status: String,
}

impl TableRow for UserRow {
    fn cells(&self) -> Vec<String> {
        vec![self.name.clone(), self.role.clone(), self.status.clone()]
    }
}

// ---------------------------------------------------------------------------
// Application State
// ---------------------------------------------------------------------------

struct ShowcaseApp;

#[derive(Clone, Debug, PartialEq, Eq)]
enum Panel {
    Form,
    Data,
    Status,
    Viz,
}

impl std::fmt::Display for Panel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Panel::Form => write!(f, "Form"),
            Panel::Data => write!(f, "Data"),
            Panel::Status => write!(f, "Status"),
            Panel::Viz => write!(f, "Viz"),
        }
    }
}

#[derive(Clone)]
struct State {
    // Layout
    focus: FocusManager<FocusId>,
    tabs: TabsState<Panel>,
    menu: MenuState,

    // Form panel
    input: InputFieldState,
    checkbox: CheckboxState,
    radio: RadioGroupState<String>,
    submit_button: ButtonState,

    // Data panel
    list: SelectableListState<String>,
    table: TableState<UserRow>,

    // Status panel
    progress: ProgressBarState,
    spinner: SpinnerState,
    toast: ToastState,

    // Viz panel
    sparkline: SparklineState,
    gauge: GaugeState,
    heatmap: HeatmapState,
    timeline: TimelineState,
    command_palette: CommandPaletteState,
    code_block: CodeBlockState,

    // Dialog overlay
    dialog: DialogState,

    // Tracking
    submission_count: u32,
}

impl Default for State {
    fn default() -> Self {
        let mut focus = FocusManager::with_initial_focus(vec![
            FocusId::Menu,
            FocusId::Tabs,
            FocusId::Input,
            FocusId::Checkbox,
            FocusId::Radio,
            FocusId::SubmitButton,
            FocusId::List,
            FocusId::Table,
            FocusId::Progress,
            FocusId::Heatmap,
            FocusId::Timeline,
            FocusId::CommandPalette,
            FocusId::CodeBlock,
        ]);
        focus.focus(&FocusId::Tabs);

        let tabs = TabsState::new(vec![Panel::Form, Panel::Data, Panel::Status, Panel::Viz]);

        let menu = MenuState::new(vec![
            MenuItem::new("File"),
            MenuItem::new("Edit"),
            MenuItem::new("Help"),
        ]);

        let mut input = InputFieldState::new();
        input.set_placeholder("Enter your name...");

        let checkbox = CheckboxState::new("Subscribe to newsletter");

        let radio = RadioGroupState::new(vec![
            "Standard".to_string(),
            "Premium".to_string(),
            "Enterprise".to_string(),
        ]);

        let submit_button = ButtonState::new("Submit");

        let list = SelectableListState::with_items(vec![
            "Alice Johnson".to_string(),
            "Bob Smith".to_string(),
            "Carol Williams".to_string(),
            "David Brown".to_string(),
            "Eve Davis".to_string(),
        ]);

        let rows = vec![
            UserRow {
                name: "Alice".to_string(),
                role: "Admin".to_string(),
                status: "Active".to_string(),
            },
            UserRow {
                name: "Bob".to_string(),
                role: "Editor".to_string(),
                status: "Active".to_string(),
            },
            UserRow {
                name: "Carol".to_string(),
                role: "Viewer".to_string(),
                status: "Inactive".to_string(),
            },
            UserRow {
                name: "David".to_string(),
                role: "Admin".to_string(),
                status: "Active".to_string(),
            },
        ];
        let columns = vec![
            Column::new("Name", Constraint::Length(15)),
            Column::new("Role", Constraint::Length(12)),
            Column::new("Status", Constraint::Length(10)),
        ];
        let table = TableState::new(rows, columns);

        let progress = ProgressBarState::with_progress(0.35);

        let mut spinner = SpinnerState::new();
        spinner.set_label(Some("Loading data...".to_string()));

        let toast = ToastState::with_max_visible(3);

        // Viz panel components
        let sparkline =
            SparklineState::with_data(vec![2, 5, 8, 12, 7, 4, 9, 15, 11, 6, 3, 8, 10, 14, 9, 5])
                .with_title("Request Rate");

        let gauge = GaugeState::new(73.0, 100.0)
            .with_label("CPU Usage")
            .with_units("%")
            .with_variant(GaugeVariant::Full);

        let heatmap = HeatmapState::with_data(vec![
            vec![1.0, 3.0, 5.0, 2.0, 7.0],
            vec![4.0, 6.0, 2.0, 8.0, 3.0],
            vec![2.0, 1.0, 9.0, 4.0, 6.0],
        ])
        .with_row_labels(vec!["Mon".into(), "Tue".into(), "Wed".into()])
        .with_col_labels(vec![
            "00:00".into(),
            "06:00".into(),
            "12:00".into(),
            "18:00".into(),
            "24:00".into(),
        ])
        .with_title("Error Rate by Day/Hour");

        let timeline = TimelineState::new()
            .with_events(vec![
                TimelineEvent::new("e1", 100.0, "Deploy v2.1"),
                TimelineEvent::new("e2", 450.0, "Alert fired"),
                TimelineEvent::new("e3", 800.0, "Resolved"),
            ])
            .with_spans(vec![
                TimelineSpan::new("s1", 100.0, 300.0, "Build"),
                TimelineSpan::new("s2", 300.0, 700.0, "Test"),
                TimelineSpan::new("s3", 700.0, 900.0, "Deploy"),
            ])
            .with_view_range(0.0, 1000.0)
            .with_title("CI/CD Pipeline");

        let command_palette = CommandPaletteState::new(vec![
            PaletteItem::new("open", "Open File"),
            PaletteItem::new("save", "Save File"),
            PaletteItem::new("quit", "Quit Application"),
            PaletteItem::new("find", "Find in Files"),
            PaletteItem::new("replace", "Find and Replace"),
            PaletteItem::new("settings", "Open Settings"),
        ])
        .with_title("Command Palette")
        .with_visible(true);

        let code_block = CodeBlockState::new()
            .with_code(
                "fn main() {\n    let data = vec![1, 2, 3];\n    for item in &data {\n        println!(\"{item}\");\n    }\n}",
            )
            .with_language(Language::Rust)
            .with_line_numbers(true)
            .with_title("Example Code");

        let dialog = DialogState::confirm("Confirm Submission", "Submit the form?");

        Self {
            focus,
            tabs,
            menu,
            input,
            checkbox,
            radio,
            submit_button,
            list,
            table,
            progress,
            spinner,
            toast,
            sparkline,
            gauge,
            heatmap,
            timeline,
            command_palette,
            code_block,
            dialog,
            submission_count: 0,
        }
    }
}

// ---------------------------------------------------------------------------
// Messages — simplified with ComponentEvent routing
// ---------------------------------------------------------------------------

#[derive(Clone, Debug)]
enum Msg {
    // Global navigation
    FocusNext,
    FocusPrev,

    // Component events — routed to the focused component via dispatch_event
    ComponentEvent(Event),

    // Timer-driven (not from keyboard)
    SpinnerTick,
    ToastTick,

    // App control
    Quit,
}

// ---------------------------------------------------------------------------
// App Implementation
// ---------------------------------------------------------------------------

impl App for ShowcaseApp {
    type State = State;
    type Message = Msg;

    fn init() -> (State, Command<Msg>) {
        (State::default(), Command::none())
    }

    fn update(state: &mut State, msg: Msg) -> Command<Msg> {
        match msg {
            Msg::Quit => return Command::quit(),

            Msg::FocusNext => {
                state.focus.focus_next();
                sync_focus(state);
            }
            Msg::FocusPrev => {
                state.focus.focus_prev();
                sync_focus(state);
            }

            Msg::ComponentEvent(event) => {
                // If dialog is visible, route events to it
                if state.dialog.is_visible() {
                    if let Some(output) = state.dialog.dispatch_event(&event) {
                        handle_dialog_output(state, output);
                    }
                    return Command::none();
                }

                // Route to focused component
                let focused = state.focus.focused().cloned();
                match focused {
                    Some(FocusId::Menu) => {
                        if let Some(MenuOutput::Selected(idx)) = state.menu.dispatch_event(&event) {
                            let label = state.menu.items()[idx].label();
                            push_toast(
                                &mut state.toast,
                                format!("Menu: {label} clicked"),
                                envision::component::ToastLevel::Info,
                            );
                        }
                    }
                    Some(FocusId::Tabs) => {
                        state.tabs.dispatch_event(&event);
                    }
                    Some(FocusId::Input) => {
                        state.input.dispatch_event(&event);
                    }
                    Some(FocusId::Checkbox) => {
                        state.checkbox.dispatch_event(&event);
                    }
                    Some(FocusId::Radio) => {
                        state.radio.dispatch_event(&event);
                    }
                    Some(FocusId::SubmitButton) => {
                        if state.submit_button.dispatch_event(&event).is_some() {
                            Dialog::update(&mut state.dialog, DialogMessage::Open);
                        }
                    }
                    Some(FocusId::List) => {
                        state.list.dispatch_event(&event);
                    }
                    Some(FocusId::Table) => {
                        if let Some(TableOutput::Selected(row)) = state.table.dispatch_event(&event)
                        {
                            push_toast(
                                &mut state.toast,
                                format!("Selected user: {}", row.name),
                                envision::component::ToastLevel::Info,
                            );
                        }
                    }
                    Some(FocusId::Progress) => {
                        // Progress bar isn't interactive via keyboard;
                        // could extend to handle +/- keys here.
                    }
                    Some(FocusId::Heatmap) => {
                        state.heatmap.dispatch_event(&event);
                    }
                    Some(FocusId::Timeline) => {
                        state.timeline.dispatch_event(&event);
                    }
                    Some(FocusId::CommandPalette) => {
                        state.command_palette.dispatch_event(&event);
                    }
                    Some(FocusId::CodeBlock) => {
                        state.code_block.dispatch_event(&event);
                    }
                    None => {}
                }
            }

            Msg::SpinnerTick => {
                Spinner::update(&mut state.spinner, SpinnerMessage::Tick);
            }
            Msg::ToastTick => {
                Toast::update(&mut state.toast, ToastMessage::Tick(100));
            }
        }
        Command::none()
    }

    fn view(state: &State, frame: &mut Frame) {
        let theme = Theme::default();
        let area = frame.area();

        // Main layout: menu bar, tabs, content, status line
        let main_chunks = Layout::vertical([
            Constraint::Length(1), // Menu bar
            Constraint::Length(3), // Tabs
            Constraint::Min(10),   // Content
            Constraint::Length(3), // Status / controls
        ])
        .split(area);

        // Menu bar
        envision::component::Menu::view(
            &state.menu,
            frame,
            main_chunks[0],
            &theme,
            &ViewContext::default(),
        );

        // Tabs
        Tabs::view(
            &state.tabs,
            frame,
            main_chunks[1],
            &theme,
            &ViewContext::default(),
        );

        // Content panel based on selected tab
        let content_area = main_chunks[2];
        match state.tabs.selected_item() {
            Some(Panel::Form) => render_form_panel(state, frame, content_area, &theme),
            Some(Panel::Data) => render_data_panel(state, frame, content_area, &theme),
            Some(Panel::Status) => render_status_panel(state, frame, content_area, &theme),
            Some(Panel::Viz) => render_viz_panel(state, frame, content_area, &theme),
            None => {}
        }

        // Controls
        let controls = Paragraph::new(Line::from(vec![
            Span::styled("[Tab]", theme.info_style()),
            Span::raw(" Focus  "),
            Span::styled("[←→]", theme.info_style()),
            Span::raw(" Navigate  "),
            Span::styled("[Enter]", theme.info_style()),
            Span::raw(" Confirm  "),
            Span::styled("[Q]", theme.error_style()),
            Span::raw(" Quit"),
        ]))
        .alignment(Alignment::Center)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(theme.border_style())
                .title("Controls"),
        );
        frame.render_widget(controls, main_chunks[3]);

        // Dialog overlay (rendered last, on top)
        if state.dialog.is_visible() {
            let dialog_area = centered_rect(40, 8, area);
            Dialog::view(
                &state.dialog,
                frame,
                dialog_area,
                &theme,
                &ViewContext::default(),
            );
        }
    }

    fn handle_event(event: &Event) -> Option<Msg> {
        use crossterm::event::KeyCode;

        if let Some(key) = event.as_key() {
            match key.code {
                KeyCode::Char('q') | KeyCode::Char('Q') | KeyCode::Esc => Some(Msg::Quit),
                KeyCode::Tab => Some(Msg::FocusNext),
                KeyCode::BackTab => Some(Msg::FocusPrev),
                // All other keys are forwarded as ComponentEvent
                _ => Some(Msg::ComponentEvent(event.clone())),
            }
        } else {
            None
        }
    }
}

// ---------------------------------------------------------------------------
// Event Output Handlers
// ---------------------------------------------------------------------------

fn handle_dialog_output(state: &mut State, output: DialogOutput) {
    match output {
        DialogOutput::ButtonPressed(id) if id == "ok" => {
            state.submission_count += 1;
            let count = state.submission_count;
            push_toast(
                &mut state.toast,
                format!("Form submitted! (#{count})"),
                envision::component::ToastLevel::Success,
            );
        }
        DialogOutput::Closed => {}
        _ => {}
    }
}

fn push_toast(toast: &mut ToastState, message: String, level: envision::component::ToastLevel) {
    Toast::update(
        toast,
        ToastMessage::Push {
            message,
            level,
            duration_ms: Some(3000),
        },
    );
}

// ---------------------------------------------------------------------------
// Panel Rendering
// ---------------------------------------------------------------------------

fn render_form_panel(state: &State, frame: &mut Frame, area: Rect, theme: &Theme) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme.border_style())
        .title("Form Panel");
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let chunks = Layout::vertical([
        Constraint::Length(3), // Input
        Constraint::Length(1), // Checkbox
        Constraint::Length(5), // RadioGroup
        Constraint::Length(3), // Button
    ])
    .split(inner);

    envision::component::InputField::view(
        &state.input,
        frame,
        chunks[0],
        theme,
        &ViewContext::default(),
    );
    envision::component::Checkbox::view(
        &state.checkbox,
        frame,
        chunks[1],
        theme,
        &ViewContext::default(),
    );
    envision::component::RadioGroup::view(
        &state.radio,
        frame,
        chunks[2],
        theme,
        &ViewContext::default(),
    );
    envision::component::Button::view(
        &state.submit_button,
        frame,
        chunks[3],
        theme,
        &ViewContext::default(),
    );
}

fn render_data_panel(state: &State, frame: &mut Frame, area: Rect, theme: &Theme) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme.border_style())
        .title("Data Panel");
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let chunks =
        Layout::horizontal([Constraint::Percentage(40), Constraint::Percentage(60)]).split(inner);

    // List with its own border
    let list_block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme.border_style())
        .title("Users");
    let list_inner = list_block.inner(chunks[0]);
    frame.render_widget(list_block, chunks[0]);
    envision::component::SelectableList::view(
        &state.list,
        frame,
        list_inner,
        theme,
        &ViewContext::default(),
    );

    // Table
    Table::view(
        &state.table,
        frame,
        chunks[1],
        theme,
        &ViewContext::default(),
    );
}

fn render_status_panel(state: &State, frame: &mut Frame, area: Rect, theme: &Theme) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme.border_style())
        .title("Status Panel");
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let chunks = Layout::vertical([
        Constraint::Length(3), // Progress
        Constraint::Length(1), // Spinner
        Constraint::Min(3),    // Toast area
    ])
    .split(inner);

    envision::component::ProgressBar::view(
        &state.progress,
        frame,
        chunks[0],
        theme,
        &ViewContext::default(),
    );
    Spinner::view(
        &state.spinner,
        frame,
        chunks[1],
        theme,
        &ViewContext::default(),
    );
    Toast::view(
        &state.toast,
        frame,
        chunks[2],
        theme,
        &ViewContext::default(),
    );
}

fn render_viz_panel(state: &State, frame: &mut Frame, area: Rect, theme: &Theme) {
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(theme.border_style())
        .title("Visualization Panel");
    let inner = block.inner(area);
    frame.render_widget(block, area);

    // Top row: Sparkline + Gauge | Bottom row: Heatmap + Timeline + CodeBlock
    let rows = Layout::vertical([
        Constraint::Length(5), // Sparkline + Gauge
        Constraint::Length(7), // Heatmap
        Constraint::Length(8), // Timeline
        Constraint::Min(6),    // CommandPalette + CodeBlock
    ])
    .split(inner);

    // Row 1: Sparkline (left) + Gauge (right)
    let top_cols =
        Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)]).split(rows[0]);
    Sparkline::view(
        &state.sparkline,
        frame,
        top_cols[0],
        theme,
        &ViewContext::default(),
    );
    Gauge::view(
        &state.gauge,
        frame,
        top_cols[1],
        theme,
        &ViewContext::default(),
    );

    // Row 2: Heatmap (full width)
    Heatmap::view(
        &state.heatmap,
        frame,
        rows[1],
        theme,
        &ViewContext::default(),
    );

    // Row 3: Timeline (full width)
    Timeline::view(
        &state.timeline,
        frame,
        rows[2],
        theme,
        &ViewContext::default(),
    );

    // Row 4: CommandPalette (left) + CodeBlock (right)
    let bottom_cols =
        Layout::horizontal([Constraint::Percentage(40), Constraint::Percentage(60)]).split(rows[3]);
    CommandPalette::view(
        &state.command_palette,
        frame,
        bottom_cols[0],
        theme,
        &ViewContext::default(),
    );
    CodeBlock::view(
        &state.code_block,
        frame,
        bottom_cols[1],
        theme,
        &ViewContext::default(),
    );
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Synchronizes focus state across all components using instance methods.
/// No turbofish needed — the type is inferred from the receiver.
fn sync_focus(state: &mut State) {
    let focused = state.focus.focused().cloned();

    state.menu.set_focused(focused == Some(FocusId::Menu));
    state.tabs.set_focused(focused == Some(FocusId::Tabs));
    state.input.set_focused(focused == Some(FocusId::Input));
    state
        .checkbox
        .set_focused(focused == Some(FocusId::Checkbox));
    state.radio.set_focused(focused == Some(FocusId::Radio));
    state
        .submit_button
        .set_focused(focused == Some(FocusId::SubmitButton));
    state.list.set_focused(focused == Some(FocusId::List));
    state.table.set_focused(focused == Some(FocusId::Table));
    state.heatmap.set_focused(focused == Some(FocusId::Heatmap));
    state
        .timeline
        .set_focused(focused == Some(FocusId::Timeline));
    state
        .command_palette
        .set_focused(focused == Some(FocusId::CommandPalette));
    state
        .code_block
        .set_focused(focused == Some(FocusId::CodeBlock));
}

/// Creates a centered rectangle for dialog overlays.
fn centered_rect(width: u16, height: u16, area: Rect) -> Rect {
    let x = area.x + area.width.saturating_sub(width) / 2;
    let y = area.y + area.height.saturating_sub(height) / 2;
    Rect::new(x, y, width.min(area.width), height.min(area.height))
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut vt = Runtime::<ShowcaseApp, _>::virtual_terminal(80, 40)?;

    println!("=== Component Showcase ===\n");
    println!("Demonstrating 18 Envision components with simplified event routing.\n");

    // Initial render (Form panel)
    vt.tick()?;
    println!("--- Initial State (Form Panel) ---");
    println!("{}\n", vt.display_ansi());

    // Navigate menu via ComponentEvent
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Right,
    )));
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Enter,
    )));

    // Switch focus to Tabs, then navigate
    vt.dispatch(Msg::FocusNext);
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Right,
    )));
    vt.tick()?;
    println!("--- Data Panel ---");
    println!("{}\n", vt.display_ansi());

    // Focus the list, navigate it
    vt.dispatch(Msg::FocusNext); // -> Input
    vt.dispatch(Msg::FocusNext); // -> Checkbox
    vt.dispatch(Msg::FocusNext); // -> Radio
    vt.dispatch(Msg::FocusNext); // -> SubmitButton
    vt.dispatch(Msg::FocusNext); // -> List
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Down,
    )));
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Down,
    )));

    // Focus the table, select a row
    vt.dispatch(Msg::FocusNext); // -> Table
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Down,
    )));
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Enter,
    )));
    vt.tick()?;
    println!("--- Data Panel (after navigation) ---");
    println!("{}\n", vt.display_ansi());

    // Switch to Status panel
    vt.dispatch(Msg::FocusNext); // -> Progress
    vt.dispatch(Msg::FocusNext); // -> Menu (wraps)
    vt.dispatch(Msg::FocusNext); // -> Tabs
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Right,
    )));
    vt.dispatch(Msg::SpinnerTick);
    vt.dispatch(Msg::ToastTick);
    vt.tick()?;
    println!("--- Status Panel ---");
    println!("{}\n", vt.display_ansi());

    // Go back to Form and submit
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Left,
    )));
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Left,
    )));

    // Focus the submit button and press it
    vt.dispatch(Msg::FocusNext); // -> Input
    vt.dispatch(Msg::FocusNext); // -> Checkbox
    vt.dispatch(Msg::FocusNext); // -> Radio
    vt.dispatch(Msg::FocusNext); // -> SubmitButton
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Enter,
    )));
    vt.tick()?;
    println!("--- Form Panel with Dialog Overlay ---");
    println!("{}\n", vt.display_ansi());

    // Confirm dialog via dispatch_event (Tab to OK, Enter to confirm)
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Tab,
    )));
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Enter,
    )));
    vt.tick()?;
    println!("--- After Submission (toast notification) ---");
    println!("{}\n", vt.display_ansi());

    // Switch to Viz panel to show new components
    vt.dispatch(Msg::FocusNext); // -> List
    vt.dispatch(Msg::FocusNext); // -> Table
    vt.dispatch(Msg::FocusNext); // -> Progress
    vt.dispatch(Msg::FocusNext); // -> Heatmap
    vt.dispatch(Msg::FocusNext); // -> Timeline
    vt.dispatch(Msg::FocusNext); // -> CommandPalette
    vt.dispatch(Msg::FocusNext); // -> CodeBlock
    vt.dispatch(Msg::FocusNext); // -> Menu (wraps)
    vt.dispatch(Msg::FocusNext); // -> Tabs
                                 // Navigate right three times to reach Viz tab
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Right,
    )));
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Right,
    )));
    vt.dispatch(Msg::ComponentEvent(Event::key(
        crossterm::event::KeyCode::Right,
    )));
    vt.tick()?;
    println!("--- Viz Panel (Sparkline, Gauge, Heatmap, Timeline, CommandPalette, CodeBlock) ---");
    println!("{}\n", vt.display_ansi());

    println!("=== Showcase Complete ===");
    println!("This example demonstrated Menu, Tabs, InputField, Checkbox,");
    println!("RadioGroup, Button, SelectableList, Table, ProgressBar,");
    println!("Spinner, Toast, Dialog, Sparkline, Gauge, Heatmap,");
    println!("Timeline, CommandPalette, and CodeBlock components working together.");
    println!("\nKey patterns shown:");
    println!("  - Msg enum: 6 variants (was 30+)");
    println!("  - sync_focus: no turbofish needed");
    println!("  - dispatch_event: routes events to focused component directly");

    Ok(())
}