ratatui-interact 0.5.1

Interactive TUI components for ratatui with focus management and mouse 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
//! Button component - Various button views
//!
//! Supports single-line, multi-line (block), icon+text, and toggle button styles.
//!
//! # Example
//!
//! ```rust
//! use ratatui_interact::components::{Button, ButtonState, ButtonVariant};
//!
//! let state = ButtonState::enabled();
//!
//! // Single line button
//! let button = Button::new("Submit", &state)
//!     .variant(ButtonVariant::SingleLine);
//!
//! // Icon button
//! let save_btn = Button::new("Save", &state)
//!     .icon("💾");
//!
//! // Toggle button
//! let mut toggle_state = ButtonState::enabled();
//! toggle_state.toggled = true;
//! let toggle = Button::new("Dark Mode", &toggle_state)
//!     .variant(ButtonVariant::Toggle);
//! ```

use ratatui::{
    buffer::Buffer,
    layout::{Alignment, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Widget},
};

use crate::traits::{ClickRegion, ClickRegionRegistry, FocusId};

/// Actions a button can emit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ButtonAction {
    /// Button was clicked/activated.
    Click,
}

/// State for a button.
#[derive(Debug, Clone)]
pub struct ButtonState {
    /// Whether the button has focus.
    pub focused: bool,
    /// Whether the button is currently pressed.
    pub pressed: bool,
    /// Whether the button is enabled.
    pub enabled: bool,
    /// For toggle buttons: whether the button is toggled on.
    pub toggled: bool,
}

impl Default for ButtonState {
    fn default() -> Self {
        Self {
            focused: false,
            pressed: false,
            enabled: true,
            toggled: false,
        }
    }
}

impl ButtonState {
    /// Create an enabled button state.
    pub fn enabled() -> Self {
        Self {
            enabled: true,
            ..Default::default()
        }
    }

    /// Create a disabled button state.
    pub fn disabled() -> Self {
        Self {
            enabled: false,
            ..Default::default()
        }
    }

    /// Create a toggled-on button state.
    pub fn toggled(toggled: bool) -> Self {
        Self {
            toggled,
            enabled: true,
            ..Default::default()
        }
    }

    /// Set the focus state.
    pub fn set_focused(&mut self, focused: bool) {
        self.focused = focused;
    }

    /// Set the pressed state.
    pub fn set_pressed(&mut self, pressed: bool) {
        self.pressed = pressed;
    }

    /// Set the enabled state.
    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    /// Toggle the toggled state.
    pub fn toggle(&mut self) {
        if self.enabled {
            self.toggled = !self.toggled;
        }
    }
}

/// Button style variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ButtonVariant {
    /// Single line button: `[ Text ]`
    #[default]
    SingleLine,
    /// Multi-line block button with border.
    Block,
    /// Icon with text: `🔍 Search`
    IconText,
    /// Toggle button (highlighted when toggled).
    Toggle,
    /// Minimal style - just text, changes color on focus.
    Minimal,
}

/// Button styling.
#[derive(Debug, Clone)]
pub struct ButtonStyle {
    /// The button variant.
    pub variant: ButtonVariant,
    /// Foreground color when focused.
    pub focused_fg: Color,
    /// Background color when focused.
    pub focused_bg: Color,
    /// Foreground color when unfocused.
    pub unfocused_fg: Color,
    /// Background color when unfocused.
    pub unfocused_bg: Color,
    /// Foreground color when disabled.
    pub disabled_fg: Color,
    /// Foreground color when pressed.
    pub pressed_fg: Color,
    /// Background color when pressed.
    pub pressed_bg: Color,
    /// Foreground color when toggled.
    pub toggled_fg: Color,
    /// Background color when toggled.
    pub toggled_bg: Color,
}

impl Default for ButtonStyle {
    fn default() -> Self {
        Self {
            variant: ButtonVariant::SingleLine,
            focused_fg: Color::Black,
            focused_bg: Color::Yellow,
            unfocused_fg: Color::White,
            unfocused_bg: Color::DarkGray,
            disabled_fg: Color::DarkGray,
            pressed_fg: Color::Black,
            pressed_bg: Color::White,
            toggled_fg: Color::Black,
            toggled_bg: Color::Green,
        }
    }
}

impl ButtonStyle {
    /// Create a style for a specific variant.
    pub fn new(variant: ButtonVariant) -> Self {
        Self {
            variant,
            ..Default::default()
        }
    }

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

    /// Set focused colors.
    pub fn focused(mut self, fg: Color, bg: Color) -> Self {
        self.focused_fg = fg;
        self.focused_bg = bg;
        self
    }

    /// Set unfocused colors.
    pub fn unfocused(mut self, fg: Color, bg: Color) -> Self {
        self.unfocused_fg = fg;
        self.unfocused_bg = bg;
        self
    }

    /// Set toggled colors.
    pub fn toggled(mut self, fg: Color, bg: Color) -> Self {
        self.toggled_fg = fg;
        self.toggled_bg = bg;
        self
    }

    /// Primary button style (prominent).
    pub fn primary() -> Self {
        Self {
            focused_fg: Color::White,
            focused_bg: Color::Blue,
            unfocused_fg: Color::White,
            unfocused_bg: Color::Rgb(50, 100, 200),
            ..Default::default()
        }
    }

    /// Danger/destructive button style.
    pub fn danger() -> Self {
        Self {
            focused_fg: Color::White,
            focused_bg: Color::Red,
            unfocused_fg: Color::White,
            unfocused_bg: Color::Rgb(150, 50, 50),
            ..Default::default()
        }
    }

    /// Success button style.
    pub fn success() -> Self {
        Self {
            focused_fg: Color::White,
            focused_bg: Color::Green,
            unfocused_fg: Color::White,
            unfocused_bg: Color::Rgb(50, 150, 50),
            ..Default::default()
        }
    }
}

impl From<&crate::theme::Theme> for ButtonStyle {
    fn from(theme: &crate::theme::Theme) -> Self {
        let p = &theme.palette;
        Self {
            variant: ButtonVariant::SingleLine,
            focused_fg: p.highlight_fg,
            focused_bg: p.highlight_bg,
            unfocused_fg: p.text,
            unfocused_bg: Color::DarkGray,
            disabled_fg: p.text_disabled,
            pressed_fg: p.pressed_fg,
            pressed_bg: p.pressed_bg,
            toggled_fg: p.highlight_fg,
            toggled_bg: p.success,
        }
    }
}

/// Button widget.
///
/// A clickable button with various display styles.
pub struct Button<'a> {
    label: &'a str,
    icon: Option<&'a str>,
    state: &'a ButtonState,
    style: ButtonStyle,
    focus_id: FocusId,
    alignment: Alignment,
}

impl<'a> Button<'a> {
    /// Create a new button.
    ///
    /// # Arguments
    ///
    /// * `label` - The button text
    /// * `state` - Reference to the button state
    pub fn new(label: &'a str, state: &'a ButtonState) -> Self {
        Self {
            label,
            icon: None,
            state,
            style: ButtonStyle::default(),
            focus_id: FocusId::default(),
            alignment: Alignment::Center,
        }
    }

    /// Set an icon to display before the label.
    pub fn icon(mut self, icon: &'a str) -> Self {
        self.icon = Some(icon);
        self
    }

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

    /// Apply a theme to this button.
    pub fn theme(self, theme: &crate::theme::Theme) -> Self {
        self.style(ButtonStyle::from(theme))
    }

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

    /// Set the focus ID.
    pub fn focus_id(mut self, id: FocusId) -> Self {
        self.focus_id = id;
        self
    }

    /// Set the text alignment.
    pub fn alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }

    /// Get the current style based on state.
    fn current_style(&self) -> Style {
        if !self.state.enabled {
            Style::default().fg(self.style.disabled_fg)
        } else if self.state.pressed {
            Style::default()
                .fg(self.style.pressed_fg)
                .bg(self.style.pressed_bg)
        } else if self.style.variant == ButtonVariant::Toggle && self.state.toggled {
            Style::default()
                .fg(self.style.toggled_fg)
                .bg(self.style.toggled_bg)
                .add_modifier(Modifier::BOLD)
        } else if self.state.focused {
            Style::default()
                .fg(self.style.focused_fg)
                .bg(self.style.focused_bg)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
                .fg(self.style.unfocused_fg)
                .bg(self.style.unfocused_bg)
        }
    }

    /// Build the button text.
    fn build_text(&self) -> String {
        match self.style.variant {
            ButtonVariant::SingleLine | ButtonVariant::Toggle => {
                if let Some(icon) = self.icon {
                    format!(" {} {} ", icon, self.label)
                } else {
                    format!(" {} ", self.label)
                }
            }
            ButtonVariant::Block | ButtonVariant::IconText | ButtonVariant::Minimal => {
                if let Some(icon) = self.icon {
                    format!("{} {}", icon, self.label)
                } else {
                    self.label.to_string()
                }
            }
        }
    }

    /// Calculate minimum width for this button.
    pub fn min_width(&self) -> u16 {
        let text = self.build_text();
        let text_len = text.chars().count() as u16;

        match self.style.variant {
            ButtonVariant::Block => text_len + 4, // Border + padding
            _ => text_len,
        }
    }

    /// Calculate minimum height for this button.
    pub fn min_height(&self) -> u16 {
        match self.style.variant {
            ButtonVariant::Block => 3, // Border top + content + border bottom
            _ => 1,
        }
    }

    /// Render the button and return the click region.
    ///
    /// This method renders the button and returns a `ClickRegion` that you must
    /// register with a `ClickRegionRegistry` to enable mouse click support.
    ///
    /// For a more convenient API, consider using `render_with_registry()` which
    /// handles both rendering and registration in one call.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ratatui_interact::components::{Button, ButtonState};
    /// use ratatui_interact::traits::ClickRegionRegistry;
    /// use ratatui::layout::Rect;
    /// use ratatui::buffer::Buffer;
    ///
    /// let state = ButtonState::enabled();
    /// let button = Button::new("OK", &state);
    /// let area = Rect::new(0, 0, 10, 1);
    /// let mut buf = Buffer::empty(Rect::new(0, 0, 20, 5));
    /// let mut registry: ClickRegionRegistry<usize> = ClickRegionRegistry::new();
    ///
    /// let region = button.render_stateful(area, &mut buf);
    /// registry.register(region.area, 0);
    /// ```
    pub fn render_stateful(self, area: Rect, buf: &mut Buffer) -> ClickRegion<ButtonAction> {
        let click_area = match self.style.variant {
            ButtonVariant::Block => area,
            _ => Rect::new(area.x, area.y, self.min_width().min(area.width), 1),
        };

        self.render(area, buf);

        ClickRegion::new(click_area, ButtonAction::Click)
    }

    /// Render the button and automatically register its click region.
    ///
    /// This is a convenience method that combines `render_stateful()` with
    /// registry registration. Use this when you have a `ClickRegionRegistry`
    /// and want to avoid the two-step render + register pattern.
    ///
    /// # Arguments
    ///
    /// * `area` - The area to render the button in
    /// * `buf` - The buffer to render to
    /// * `registry` - The click region registry to register with
    /// * `data` - The data to associate with this button's click region
    ///
    /// # Example
    ///
    /// ```rust
    /// use ratatui_interact::components::{Button, ButtonState};
    /// use ratatui_interact::traits::ClickRegionRegistry;
    /// use ratatui::layout::Rect;
    /// use ratatui::buffer::Buffer;
    ///
    /// let state = ButtonState::enabled();
    /// let mut registry: ClickRegionRegistry<usize> = ClickRegionRegistry::new();
    ///
    /// // Clear before each render cycle
    /// registry.clear();
    ///
    /// let button = Button::new("OK", &state);
    /// let area = Rect::new(0, 0, 10, 1);
    /// let mut buf = Buffer::empty(Rect::new(0, 0, 20, 5));
    ///
    /// // Render and register in one call
    /// button.render_with_registry(area, &mut buf, &mut registry, 0);
    ///
    /// // Later, check for clicks
    /// if let Some(&idx) = registry.handle_click(5, 0) {
    ///     println!("Button {} clicked!", idx);
    /// }
    /// ```
    pub fn render_with_registry<D: Clone>(
        self,
        area: Rect,
        buf: &mut Buffer,
        registry: &mut ClickRegionRegistry<D>,
        data: D,
    ) {
        let region = self.render_stateful(area, buf);
        registry.register(region.area, data);
    }
}

impl Widget for Button<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let style = self.current_style();
        let text = self.build_text();

        match self.style.variant {
            ButtonVariant::SingleLine | ButtonVariant::Toggle | ButtonVariant::Minimal => {
                let line = Line::from(Span::styled(text, style));
                let paragraph = Paragraph::new(line).alignment(self.alignment);
                paragraph.render(area, buf);
            }

            ButtonVariant::Block => {
                let block = Block::default().borders(Borders::ALL).border_style(style);

                let inner = block.inner(area);
                block.render(area, buf);

                let paragraph = Paragraph::new(text).style(style).alignment(self.alignment);
                paragraph.render(inner, buf);
            }

            ButtonVariant::IconText => {
                let line = Line::from(Span::styled(text, style));
                let paragraph = Paragraph::new(line);
                paragraph.render(area, buf);
            }
        }
    }
}

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

    #[test]
    fn test_state_default() {
        let state = ButtonState::default();
        assert!(!state.focused);
        assert!(!state.pressed);
        assert!(state.enabled);
        assert!(!state.toggled);
    }

    #[test]
    fn test_state_enabled() {
        let state = ButtonState::enabled();
        assert!(state.enabled);
        assert!(!state.focused);
    }

    #[test]
    fn test_state_disabled() {
        let state = ButtonState::disabled();
        assert!(!state.enabled);
    }

    #[test]
    fn test_state_toggled() {
        let state = ButtonState::toggled(true);
        assert!(state.toggled);
        assert!(state.enabled);
    }

    #[test]
    fn test_toggle() {
        let mut state = ButtonState::enabled();
        assert!(!state.toggled);

        state.toggle();
        assert!(state.toggled);

        state.toggle();
        assert!(!state.toggled);
    }

    #[test]
    fn test_toggle_disabled() {
        let mut state = ButtonState::disabled();
        state.toggled = false;

        state.toggle();
        assert!(!state.toggled); // Should not change when disabled
    }

    #[test]
    fn test_button_text_single_line() {
        let state = ButtonState::enabled();
        let button = Button::new("Click", &state).variant(ButtonVariant::SingleLine);

        assert_eq!(button.build_text(), " Click ");
    }

    #[test]
    fn test_button_text_with_icon() {
        let state = ButtonState::enabled();
        let button = Button::new("Save", &state).icon("💾");

        assert_eq!(button.build_text(), " 💾 Save ");
    }

    #[test]
    fn test_button_min_width() {
        let state = ButtonState::enabled();

        let button = Button::new("OK", &state).variant(ButtonVariant::SingleLine);
        assert_eq!(button.min_width(), 4); // " OK "

        let button = Button::new("OK", &state).variant(ButtonVariant::Block);
        assert_eq!(button.min_width(), 6); // "OK" + 4 for border
    }

    #[test]
    fn test_button_min_height() {
        let state = ButtonState::enabled();

        let button = Button::new("OK", &state).variant(ButtonVariant::SingleLine);
        assert_eq!(button.min_height(), 1);

        let button = Button::new("OK", &state).variant(ButtonVariant::Block);
        assert_eq!(button.min_height(), 3);
    }

    #[test]
    fn test_render_stateful() {
        let state = ButtonState::enabled();
        let button = Button::new("Test", &state);

        let area = Rect::new(5, 3, 20, 1);
        let mut buffer = Buffer::empty(Rect::new(0, 0, 30, 10));

        let click_region = button.render_stateful(area, &mut buffer);

        assert_eq!(click_region.area.x, 5);
        assert_eq!(click_region.area.y, 3);
        assert_eq!(click_region.data, ButtonAction::Click);
    }

    #[test]
    fn test_render_with_registry() {
        use crate::traits::ClickRegionRegistry;

        let state = ButtonState::enabled();
        let button = Button::new("Click", &state);
        let area = Rect::new(5, 3, 20, 1);
        let mut buffer = Buffer::empty(Rect::new(0, 0, 30, 10));
        let mut registry: ClickRegionRegistry<&str> = ClickRegionRegistry::new();

        button.render_with_registry(area, &mut buffer, &mut registry, "test_button");

        // Verify registry has the region
        assert_eq!(registry.len(), 1);

        // Verify click detection works - click inside the button area
        assert_eq!(registry.handle_click(5, 3), Some(&"test_button"));

        // Verify click outside returns None
        assert_eq!(registry.handle_click(100, 100), None);
    }

    #[test]
    fn test_render_with_registry_multiple_buttons() {
        use crate::traits::ClickRegionRegistry;

        let mut registry: ClickRegionRegistry<usize> = ClickRegionRegistry::new();
        let mut buffer = Buffer::empty(Rect::new(0, 0, 50, 10));

        // Render three buttons
        let state = ButtonState::enabled();

        let button1 = Button::new("OK", &state);
        button1.render_with_registry(Rect::new(0, 0, 10, 1), &mut buffer, &mut registry, 0);

        let button2 = Button::new("Cancel", &state);
        button2.render_with_registry(Rect::new(15, 0, 12, 1), &mut buffer, &mut registry, 1);

        let button3 = Button::new("Help", &state);
        button3.render_with_registry(Rect::new(30, 0, 10, 1), &mut buffer, &mut registry, 2);

        // Verify all buttons are registered
        assert_eq!(registry.len(), 3);

        // Verify clicking each button returns the correct index
        assert_eq!(registry.handle_click(2, 0), Some(&0)); // OK
        assert_eq!(registry.handle_click(18, 0), Some(&1)); // Cancel
        assert_eq!(registry.handle_click(32, 0), Some(&2)); // Help

        // Verify clicking in gaps returns None
        assert_eq!(registry.handle_click(12, 0), None);
    }

    #[test]
    fn test_style_presets() {
        let primary = ButtonStyle::primary();
        assert_eq!(primary.focused_bg, Color::Blue);

        let danger = ButtonStyle::danger();
        assert_eq!(danger.focused_bg, Color::Red);

        let success = ButtonStyle::success();
        assert_eq!(success.focused_bg, Color::Green);
    }

    #[test]
    fn test_style_builder() {
        let style = ButtonStyle::default()
            .variant(ButtonVariant::Toggle)
            .focused(Color::White, Color::Cyan)
            .toggled(Color::Black, Color::Magenta);

        assert_eq!(style.variant, ButtonVariant::Toggle);
        assert_eq!(style.focused_fg, Color::White);
        assert_eq!(style.focused_bg, Color::Cyan);
        assert_eq!(style.toggled_fg, Color::Black);
        assert_eq!(style.toggled_bg, Color::Magenta);
    }

    #[test]
    fn test_current_style_states() {
        // Disabled state
        let state = ButtonState::disabled();
        let button = Button::new("Test", &state);
        let style = button.current_style();
        assert_eq!(style.fg, Some(button.style.disabled_fg));

        // Focused state
        let mut state = ButtonState::enabled();
        state.focused = true;
        let button = Button::new("Test", &state);
        let style = button.current_style();
        assert_eq!(style.fg, Some(button.style.focused_fg));
        assert_eq!(style.bg, Some(button.style.focused_bg));

        // Toggled state
        let mut state = ButtonState::enabled();
        state.toggled = true;
        let button = Button::new("Test", &state).variant(ButtonVariant::Toggle);
        let style = button.current_style();
        assert_eq!(style.fg, Some(button.style.toggled_fg));
        assert_eq!(style.bg, Some(button.style.toggled_bg));
    }
}