summaryrefslogtreecommitdiffstats
path: root/src/app/widgets/bottom_widgets/carousel.rs
blob: 3788cf97851f65852414a4414de27f4dd5bd5229 (plain)
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
use std::borrow::Cow;

use crossterm::event::MouseEvent;
use indextree::NodeId;
use tui::{
    backend::Backend,
    layout::{Constraint, Layout, Rect},
    text::{Span, Spans},
    widgets::Paragraph,
    Frame,
};

use crate::{
    app::{
        does_bound_intersect_coordinate,
        event::{ComponentEventResult, SelectionAction},
        Component, Widget,
    },
    canvas::Painter,
    options::layout_options::LayoutRule,
};

/// A container that "holds" multiple [`BottomWidget`]s through their [`NodeId`]s.
#[derive(PartialEq, Eq)]
pub struct Carousel {
    index: usize,
    children: Vec<(NodeId, Cow<'static, str>)>,
    bounds: Rect,
    width: LayoutRule,
    height: LayoutRule,
    left_button_bounds: Rect,
    right_button_bounds: Rect,
}

impl Carousel {
    /// Creates a new [`Carousel`] with the specified children.
    pub fn new(children: Vec<(NodeId, Cow<'static, str>)>) -> Self {
        Self {
            index: 0,
            children,
            bounds: Default::default(),
            width: Default::default(),
            height: Default::default(),
            left_button_bounds: Default::default(),
            right_button_bounds: Default::default(),
        }
    }

    /// Sets the width.
    pub fn width(mut self, width: LayoutRule) -> Self {
        self.width = width;
        self
    }

    /// Sets the height.
    pub fn height(mut self, height: LayoutRule) -> Self {
        self.height = height;
        self
    }

    /// Adds a new child to a [`Carousel`].
    pub fn add_child(&mut self, child: NodeId, name: Cow<'static, str>) {
        self.children.push((child, name));
    }

    /// Returns the currently selected [`NodeId`] if possible.
    pub fn get_currently_selected(&self) -> Option<NodeId> {
        self.children.get(self.index).map(|i| i.0)
    }

    fn get_next(&self) -> Option<&(NodeId, Cow<'static, str>)> {
        self.children.get(if self.index + 1 == self.children.len() {
            0
        } else {
            self.index + 1
        })
    }

    fn get_prev(&self) -> Option<&(NodeId, Cow<'static, str>)> {
        self.children.get(if self.index > 0 {
            self.index - 1
        } else {
            self.children.len().saturating_sub(1)
        })
    }

    fn increment_index(&mut self) {
        if self.index + 1 == self.children.len() {
            self.index = 0;
        } else {
            self.index += 1;
        }
    }

    fn decrement_index(&mut self) {
        if self.index > 0 {
            self.index -= 1;
        } else {
            self.index = self.children.len().saturating_sub(1);
        }
    }

    /// Draws the [`Carousel`] arrows, and returns back the remaining [`Rect`] to draw the child with.
    pub fn draw_carousel<B: Backend>(
        &mut self, painter: &Painter, f: &mut Frame<'_, B>, area: Rect,
    ) -> Rect {
        const CONSTRAINTS: [Constraint; 2] = [Constraint::Length(1), Constraint::Min(0)];
        let split_area = Layout::default()
            .constraints(CONSTRAINTS)
            .direction(tui::layout::Direction::Vertical)
            .split(area);

        self.set_bounds(area);

        if let Some((_prev_id, prev_element_name)) = self.get_prev() {
            let prev_arrow_text = Spans::from(Span::styled(
                format!("◄ {}", prev_element_name),
                painter.colours.text_style,
            ));

            self.left_button_bounds = Rect::new(
                split_area[0].x,
                split_area[0].y,
                prev_arrow_text.width() as u16,
                split_area[0].height,
            );

            f.render_widget(
                Paragraph::new(vec![prev_arrow_text]).alignment(tui::layout::Alignment::Left),
                split_area[0],
            );
        }

        if let Some((_next_id, next_element_name)) = self.get_next() {
            let next_arrow_text = Spans::from(Span::styled(
                format!("{} ►", next_element_name),
                painter.colours.text_style,
            ));

            let width = next_arrow_text.width() as u16;

            self.right_button_bounds = Rect::new(
                split_area[0].right().saturating_sub(width + 1),
                split_area[0].y,
                width,
                split_area[0].height,
            );

            f.render_widget(
                Paragraph::new(vec![next_arrow_text]).alignment(tui::layout::Alignment::Right),
                split_area[0],
            );
        }

        split_area[1]
    }
}

impl Component for Carousel {
    fn bounds(&self) -> Rect {
        self.bounds
    }

    fn set_bounds(&mut self, new_bounds: Rect) {
        self.bounds = new_bounds;
    }

    fn handle_mouse_event(&mut self, event: MouseEvent) -> ComponentEventResult {
        match event.kind {
            crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left) => {
                let x = event.column;
                let y = event.row;

                if does_bound_intersect_coordinate(x, y, self.left_button_bounds) {
                    self.decrement_index();
                    ComponentEventResult::Redraw
                } else if does_bound_intersect_coordinate(x, y, self.right_button_bounds) {
                    self.increment_index();
                    ComponentEventResult::Redraw
                } else {
                    ComponentEventResult::Unhandled
                }
            }
            _ => ComponentEventResult::Unhandled,
        }
    }
}

impl Widget for Carousel {
    fn get_pretty_name(&self) -> &'static str {
        "Carousel"
    }

    fn width(&self) -> LayoutRule {
        self.width
    }

    fn height(&self) -> LayoutRule {
        self.height
    }

    fn handle_widget_selection_left(&mut self) -> SelectionAction {
        // Override to move to the left widget
        self.decrement_index();
        SelectionAction::Handled
    }

    fn handle_widget_selection_right(&mut self) -> SelectionAction {
        // Override to move to the right widget
        self.increment_index();
        SelectionAction::Handled
    }
}