mecomp_tui/ui/components/
queuebar.rs

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
//! Implementation of the Queue Bar component, a scrollable list of the songs in the queue.

use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
use mecomp_core::state::RepeatMode;
use mecomp_storage::db::schemas::song::Song;
use ratatui::{
    layout::{Constraint, Direction, Layout, Position, Rect},
    style::{Modifier, Style},
    text::{Line, Text},
    widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
};

use tokio::sync::mpsc::UnboundedSender;

use crate::{
    state::{
        action::{Action, AudioAction, ComponentAction, QueueAction},
        component::ActiveComponent,
    },
    ui::colors::{
        BORDER_FOCUSED, BORDER_UNFOCUSED, TEXT_HIGHLIGHT, TEXT_HIGHLIGHT_ALT, TEXT_NORMAL,
    },
};

use super::{AppState, Component, ComponentRender, RenderProps};

pub struct QueueBar {
    /// Action Sender
    pub action_tx: UnboundedSender<Action>,
    /// Mapped Props from state
    pub(crate) props: Props,
    /// list state
    list_state: ListState,
}

pub struct Props {
    pub(crate) queue: Box<[Song]>,
    pub(crate) current_position: Option<usize>,
    pub(crate) repeat_mode: RepeatMode,
}

impl From<&AppState> for Props {
    fn from(value: &AppState) -> Self {
        Self {
            current_position: value.audio.queue_position,
            repeat_mode: value.audio.repeat_mode,
            queue: value.audio.queue.clone(),
        }
    }
}

impl Component for QueueBar {
    fn new(state: &AppState, action_tx: UnboundedSender<Action>) -> Self
    where
        Self: Sized,
    {
        let props = Props::from(state);
        Self {
            action_tx,
            list_state: ListState::default().with_selected(props.current_position),
            props,
        }
    }

    fn move_with_state(self, state: &AppState) -> Self
    where
        Self: Sized,
    {
        let old_current_index = self.props.current_position;
        let new_current_index = state.audio.queue_position;

        let list_state = if old_current_index == new_current_index {
            self.list_state
        } else {
            self.list_state.with_selected(new_current_index)
        };

        Self {
            list_state,
            props: Props::from(state),
            ..self
        }
    }

    fn name(&self) -> &str {
        "Queue"
    }

    fn handle_key_event(&mut self, key: KeyEvent) {
        match key.code {
            // Move the selected index up
            KeyCode::Up => {
                if let Some(index) = self.list_state.selected() {
                    let new_index = if index == 0 {
                        self.props.queue.len() - 1
                    } else {
                        index - 1
                    };
                    self.list_state.select(Some(new_index));
                }
            }
            // Move the selected index down
            KeyCode::Down => {
                if let Some(index) = self.list_state.selected() {
                    let new_index = if index == self.props.queue.len() - 1 {
                        0
                    } else {
                        index + 1
                    };
                    self.list_state.select(Some(new_index));
                }
            }
            // Set the current song to the selected index
            KeyCode::Enter => {
                if let Some(index) = self.list_state.selected() {
                    self.action_tx
                        .send(Action::Audio(AudioAction::Queue(QueueAction::SetPosition(
                            index,
                        ))))
                        .unwrap();
                }
            }
            // Clear the queue
            KeyCode::Char('c') => {
                self.action_tx
                    .send(Action::Audio(AudioAction::Queue(QueueAction::Clear)))
                    .unwrap();
            }
            // Remove the selected index from the queue
            KeyCode::Char('d') => {
                if let Some(index) = self.list_state.selected() {
                    self.action_tx
                        .send(Action::Audio(AudioAction::Queue(QueueAction::Remove(
                            index,
                        ))))
                        .unwrap();
                }
            }
            // shuffle the queue
            KeyCode::Char('s') => {
                self.action_tx
                    .send(Action::Audio(AudioAction::Queue(QueueAction::Shuffle)))
                    .unwrap();
            }
            // set the repeat mode
            KeyCode::Char('r') => match self.props.repeat_mode {
                RepeatMode::None => {
                    self.action_tx
                        .send(Action::Audio(AudioAction::Queue(
                            QueueAction::SetRepeatMode(RepeatMode::Once),
                        )))
                        .unwrap();
                }
                RepeatMode::Once => {
                    self.action_tx
                        .send(Action::Audio(AudioAction::Queue(
                            QueueAction::SetRepeatMode(RepeatMode::Continuous),
                        )))
                        .unwrap();
                }
                RepeatMode::Continuous => {
                    self.action_tx
                        .send(Action::Audio(AudioAction::Queue(
                            QueueAction::SetRepeatMode(RepeatMode::None),
                        )))
                        .unwrap();
                }
            },
            _ => {}
        }
    }

    // TODO: refactor QueueBar to use a CheckTree for better mouse handling
    fn handle_mouse_event(&mut self, mouse: MouseEvent, area: Rect) {
        let MouseEvent {
            kind, column, row, ..
        } = mouse;
        let mouse_position = Position::new(column, row);

        match kind {
            // TODO: refactor Sidebar to use a CheckTree for better mouse handling
            MouseEventKind::Down(MouseButton::Left) if area.contains(mouse_position) => {
                // make this the active component
                self.action_tx
                    .send(Action::ActiveComponent(ComponentAction::Set(
                        ActiveComponent::QueueBar,
                    )))
                    .unwrap();

                // TODO: when we have better mouse handling, we can use this to select an item
            }
            MouseEventKind::ScrollDown => self.handle_key_event(KeyEvent::from(KeyCode::Down)),
            MouseEventKind::ScrollUp => self.handle_key_event(KeyEvent::from(KeyCode::Up)),
            _ => {}
        }
    }
}

impl ComponentRender<RenderProps> for QueueBar {
    fn render_border(&self, frame: &mut ratatui::Frame, props: RenderProps) -> RenderProps {
        let border_style = if props.is_focused {
            Style::default().fg(BORDER_FOCUSED.into())
        } else {
            Style::default().fg(BORDER_UNFOCUSED.into())
        };

        let border = Block::bordered().title("Queue").border_style(border_style);
        frame.render_widget(&border, props.area);
        let area = border.inner(props.area);

        // split up area
        let [info_area, content_area, instructions_area] = *Layout::default()
            .direction(Direction::Vertical)
            .constraints(
                [
                    Constraint::Length(2),
                    Constraint::Min(0),
                    Constraint::Length(3),
                ]
                .as_ref(),
            )
            .split(area)
        else {
            panic!("Failed to split queue bar area");
        };

        // border the content area
        let border = Block::default()
            .borders(Borders::TOP | Borders::BOTTOM)
            .title(format!("Songs ({})", self.props.queue.len()))
            .border_style(border_style);
        frame.render_widget(&border, content_area);
        let content_area = border.inner(content_area);

        // render queue info chunk
        let queue_info = format!(
            "repeat: {}",
            match self.props.repeat_mode {
                RepeatMode::None => "none",
                RepeatMode::Once => "once",
                RepeatMode::Continuous => "continuous",
            }
        );
        frame.render_widget(
            Paragraph::new(queue_info)
                .style(Style::default().fg(TEXT_NORMAL.into()))
                .alignment(ratatui::layout::Alignment::Center),
            info_area,
        );

        // render instructions
        frame.render_widget(
            Paragraph::new(Text::from(vec![
                Line::from("↑/↓: Move | c: Clear"),
                Line::from("\u{23CE} : Select | d: Delete"),
                Line::from("s: Shuffle | r: Repeat"),
            ]))
            .style(Style::default().fg(TEXT_NORMAL.into()))
            .alignment(ratatui::layout::Alignment::Center),
            instructions_area,
        );

        // return the new props
        RenderProps {
            area: content_area,
            is_focused: props.is_focused,
        }
    }

    fn render_content(&self, frame: &mut ratatui::Frame, props: RenderProps) {
        let items = self
            .props
            .queue
            .iter()
            .enumerate()
            .map(|(index, song)| {
                let style = if Some(index) == self.props.current_position {
                    Style::default().fg(TEXT_HIGHLIGHT_ALT.into())
                } else {
                    Style::default().fg(TEXT_NORMAL.into())
                };

                ListItem::new(song.title.as_ref()).style(style)
            })
            .collect::<Vec<_>>();

        frame.render_stateful_widget(
            List::new(items)
                .highlight_style(
                    Style::default()
                        .fg(TEXT_HIGHLIGHT.into())
                        .add_modifier(Modifier::BOLD),
                )
                .scroll_padding(1)
                .direction(ratatui::widgets::ListDirection::TopToBottom),
            props.area,
            &mut self.list_state.clone(),
        );
    }
}