ratatui_toolkit/primitives/toast/methods/
toast_manager_handle_click.rs

1use crate::primitives::toast::ToastManager;
2use ratatui::layout::Rect;
3
4impl ToastManager {
5    /// Handle a mouse click and dismiss any toast that was clicked.
6    ///
7    /// Returns `true` if a toast was dismissed, `false` otherwise.
8    ///
9    /// # Arguments
10    ///
11    /// * `x` - The x coordinate of the click
12    /// * `y` - The y coordinate of the click
13    /// * `frame_area` - The total frame area (used to calculate toast positions)
14    pub fn handle_click(&mut self, x: u16, y: u16, frame_area: Rect) -> bool {
15        // Use same constants as render_toasts
16        const TOAST_WIDTH: u16 = 40;
17        const TOAST_HEIGHT: u16 = 3;
18        const TOAST_MARGIN: u16 = 2;
19        const TOAST_SPACING: u16 = 1;
20
21        let active_count = self.toasts.iter().filter(|t| !t.is_expired()).count();
22        if active_count == 0 {
23            return false;
24        }
25
26        let mut y_offset = frame_area.height.saturating_sub(TOAST_MARGIN);
27
28        // Iterate through toasts in reverse order (same as render_toasts)
29        // to find which one (if any) was clicked
30        for i in (0..self.toasts.len()).rev() {
31            if self.toasts[i].is_expired() {
32                continue;
33            }
34
35            let toast_y = y_offset.saturating_sub(TOAST_HEIGHT);
36            let toast_x = frame_area.width.saturating_sub(TOAST_WIDTH + TOAST_MARGIN);
37
38            // Check if click is within this toast's bounds
39            if x >= toast_x
40                && x < toast_x + TOAST_WIDTH
41                && y >= toast_y
42                && y < toast_y + TOAST_HEIGHT
43            {
44                self.toasts.remove(i);
45                return true;
46            }
47
48            y_offset = toast_y.saturating_sub(TOAST_SPACING);
49
50            if toast_y == 0 || toast_x == 0 {
51                break;
52            }
53        }
54
55        false
56    }
57}