mecomp_tui/ui/widgets/popups/
playlist.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
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
//! A popup that prompts the user to select a playlist, or create a new one.
//!
//! The popup will consist of an input box for the playlist name, a list of playlists to select from, and a button to create a new playlist.
//!
//! The user can navigate the list of playlists using the arrow keys, and select a playlist by pressing the enter key.
//!
//! The user can create a new playlist by typing a name in the input box and pressing the enter key.
//!
//! The user can cancel the popup by pressing the escape key.

use std::sync::Mutex;

use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
use mecomp_storage::db::schemas::Thing;
use ratatui::{
    layout::{Constraint, Direction, Layout, Margin, Position, Rect},
    style::{Style, Stylize},
    text::Line,
    widgets::{Block, Borders, Scrollbar, ScrollbarOrientation},
    Frame,
};
use tokio::sync::mpsc::UnboundedSender;

use crate::{
    state::action::{Action, LibraryAction, PopupAction},
    ui::{
        colors::{BORDER_FOCUSED, TEXT_HIGHLIGHT, TEXT_HIGHLIGHT_ALT},
        components::{
            content_view::views::{
                checktree_utils::{create_playlist_tree_leaf, get_selected_things_from_tree_state},
                playlist::Props,
            },
            Component, ComponentRender,
        },
        widgets::{
            input_box::{InputBox, RenderProps},
            tree::{state::CheckTreeState, CheckTree},
        },
        AppState,
    },
};

use super::Popup;

/// A popup that prompts the user to select a playlist, or create a new one.
///
/// The popup will consist of a list of playlists to select from,
/// and if the user wants to create a new playlist, they can press the "n" key,
/// which will make an input box appear for the user to type the name of the new playlist.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct PlaylistSelector {
    /// Action Sender
    action_tx: UnboundedSender<Action>,
    /// Mapped Props from state
    props: Props,
    /// tree state
    tree_state: Mutex<CheckTreeState<String>>,
    /// Playlist Name Input Box
    input_box: InputBox,
    /// Is the input box visible
    input_box_visible: bool,
    /// The items to add to the playlist
    items: Vec<Thing>,
}

impl PlaylistSelector {
    #[must_use]
    pub fn new(state: &AppState, action_tx: UnboundedSender<Action>, items: Vec<Thing>) -> Self {
        Self {
            input_box: InputBox::new(state, action_tx.clone()),
            input_box_visible: false,
            action_tx,
            props: Props::from(state),
            tree_state: Mutex::new(CheckTreeState::default()),
            items,
        }
    }
}

impl Popup for PlaylistSelector {
    fn title(&self) -> ratatui::prelude::Line {
        Line::from("Select a Playlist")
    }

    fn instructions(&self) -> ratatui::prelude::Line {
        Line::from(if self.input_box_visible {
            ""
        } else {
            "  \u{23CE} : Select | ↑/↓: Up/Down"
        })
    }

    fn update_with_state(&mut self, state: &AppState) {
        self.props = Props::from(state);
    }

    fn area(&self, terminal_area: Rect) -> Rect {
        let [_, horizontal_area, _] = *Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(50),
                Constraint::Min(31),
                Constraint::Percentage(19),
            ])
            .split(terminal_area)
        else {
            panic!("Failed to split horizontal area");
        };

        let [_, area, _] = *Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Max(10),
                Constraint::Min(10),
                Constraint::Max(10),
            ])
            .split(horizontal_area)
        else {
            panic!("Failed to split vertical area");
        };
        area
    }

    fn inner_handle_key_event(&mut self, key: KeyEvent) {
        // this component has 2 distinct states:
        // 1. the user is selecting a playlist
        // 2. the user is creating a new playlist
        // when the user is creating a new playlist, the input box is visible
        // and the user can type the name of the new playlist
        // when the user is selecting a playlist, the input box is not visible
        // and the user can navigate the list of playlists
        if self.input_box_visible {
            match key.code {
                // if the user presses Enter, we try to create a new playlist with the given name
                // and add the items to that playlist
                KeyCode::Enter => {
                    let name = self.input_box.text();
                    if !name.is_empty() {
                        // create the playlist and add the items,
                        self.action_tx
                            .send(Action::Library(LibraryAction::CreatePlaylistAndAddThings(
                                name.to_string(),
                                self.items.clone(),
                            )))
                            .unwrap();
                        // close the popup
                        self.action_tx
                            .send(Action::Popup(PopupAction::Close))
                            .unwrap();
                    }
                    self.input_box_visible = false;
                }
                // defer to the input box
                _ => self.input_box.handle_key_event(key),
            }
        } else {
            match key.code {
                // if the user presses the "n" key, we show the input box
                KeyCode::Char('n') => {
                    self.input_box_visible = true;
                }
                // arrow keys
                KeyCode::PageUp => {
                    self.tree_state.lock().unwrap().select_relative(|current| {
                        current.map_or(self.props.playlists.len() - 1, |c| c.saturating_sub(10))
                    });
                }
                KeyCode::Up => {
                    self.tree_state.lock().unwrap().key_up();
                }
                KeyCode::PageDown => {
                    self.tree_state
                        .lock()
                        .unwrap()
                        .select_relative(|current| current.map_or(0, |c| c.saturating_add(10)));
                }
                KeyCode::Down => {
                    self.tree_state.lock().unwrap().key_down();
                }
                KeyCode::Left => {
                    self.tree_state.lock().unwrap().key_left();
                }
                KeyCode::Right => {
                    self.tree_state.lock().unwrap().key_right();
                }
                // Enter key adds the items to the selected playlist
                // and closes the popup
                KeyCode::Enter => {
                    if self.tree_state.lock().unwrap().toggle_selected() {
                        let things =
                            get_selected_things_from_tree_state(&self.tree_state.lock().unwrap());

                        if let Some(thing) = things {
                            // add the items to the selected playlist
                            self.action_tx
                                .send(Action::Library(LibraryAction::AddThingsToPlaylist(
                                    thing,
                                    self.items.clone(),
                                )))
                                .unwrap();
                            // close the popup
                            self.action_tx
                                .send(Action::Popup(PopupAction::Close))
                                .unwrap();
                        }
                    }
                }
                _ => {}
            }
        }
    }

    /// Mouse Event Handler for the inner component of the popup,
    /// when an item in the list is clicked, it will be selected.
    fn inner_handle_mouse_event(&mut self, mouse: MouseEvent, area: Rect) {
        let MouseEvent {
            kind, column, row, ..
        } = mouse;
        let mouse_position = Position::new(column, row);

        // adjust the area to account for the border
        let area = area.inner(Margin::new(1, 1));

        // defer to input box if it's visible
        if self.input_box_visible {
            let [input_box_area, content_area] = split_area(area);
            if input_box_area.contains(mouse_position) {
                self.input_box.handle_mouse_event(mouse, input_box_area);
            } else if content_area.contains(mouse_position)
                && kind == MouseEventKind::Down(MouseButton::Left)
            {
                self.input_box_visible = false;
            }
        } else {
            match kind {
                MouseEventKind::Down(MouseButton::Left) if area.contains(mouse_position) => {
                    self.tree_state.lock().unwrap().mouse_click(mouse_position);
                }
                MouseEventKind::ScrollDown if area.contains(mouse_position) => {
                    self.tree_state.lock().unwrap().key_down();
                }
                MouseEventKind::ScrollUp if area.contains(mouse_position) => {
                    self.tree_state.lock().unwrap().key_up();
                }
                _ => {}
            }
        }
    }
}

fn split_area(area: Rect) -> [Rect; 2] {
    let [input_box_area, content_area] = *Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(4)])
        .split(area)
    else {
        panic!("Failed to split playlist selector area");
    };
    [input_box_area, content_area]
}

impl ComponentRender<Rect> for PlaylistSelector {
    fn render_border(&self, frame: &mut ratatui::Frame, area: Rect) -> Rect {
        let area = self.render_popup_border(frame, area);

        let content_area = if self.input_box_visible {
            // split content area to make room for the input box
            let [input_box_area, content_area] = split_area(area);

            // render input box
            self.input_box.render(
                frame,
                RenderProps {
                    area: input_box_area,
                    text_color: TEXT_HIGHLIGHT_ALT.into(),
                    border: Block::bordered()
                        .title("Enter Name:")
                        .border_style(Style::default().fg(BORDER_FOCUSED.into())),
                    show_cursor: self.input_box_visible,
                },
            );

            content_area
        } else {
            area
        };

        // draw additional border around content area to display additional instructions
        let border = Block::new()
            .borders(Borders::TOP)
            .title_top(if self.input_box_visible {
                " \u{23CE} : Create (cancel if empty)"
            } else {
                "n: new playlist"
            })
            .border_style(Style::default().fg(self.border_color()));
        frame.render_widget(&border, content_area);
        border.inner(content_area)
    }

    fn render_content(&self, frame: &mut Frame, area: Rect) {
        // create a tree for the playlists
        let playlists = self
            .props
            .playlists
            .iter()
            .map(create_playlist_tree_leaf)
            .collect::<Vec<_>>();

        // render the playlists
        frame.render_stateful_widget(
            CheckTree::new(&playlists)
                .unwrap()
                .highlight_style(Style::default().fg(TEXT_HIGHLIGHT.into()).bold())
                // we want this to be rendered like a normal tree, not a check tree, so we don't show the checkboxes
                .node_unchecked_symbol("▪ ")
                .node_checked_symbol("▪ ")
                .experimental_scrollbar(Some(Scrollbar::new(ScrollbarOrientation::VerticalRight))),
            area,
            &mut self.tree_state.lock().unwrap(),
        );
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;
    use crate::{
        state::component::ActiveComponent,
        test_utils::setup_test_terminal,
        ui::components::content_view::{views::ViewData, ActiveView},
    };
    use anyhow::Result;
    use mecomp_core::{
        rpc::SearchResult,
        state::{library::LibraryFull, StateAudio},
    };
    use mecomp_storage::db::schemas::playlist::Playlist;
    use pretty_assertions::assert_eq;
    use ratatui::{
        buffer::Buffer,
        style::{Color, Style},
        text::Span,
    };
    use rstest::{fixture, rstest};

    #[fixture]
    fn state() -> AppState {
        AppState {
            active_component: ActiveComponent::default(),
            audio: StateAudio::default(),
            search: SearchResult::default(),
            library: LibraryFull {
                playlists: vec![Playlist {
                    id: Playlist::generate_id(),
                    name: "playlist 1".into(),
                    runtime: Duration::default(),
                    song_count: 0,
                }]
                .into_boxed_slice(),
                ..Default::default()
            },
            active_view: ActiveView::default(),
            additional_view_data: ViewData::default(),
        }
    }

    #[fixture]
    fn border_style() -> Style {
        Style::reset().fg(Color::Rgb(3, 169, 244))
    }

    #[fixture]
    fn input_box_style() -> Style {
        Style::reset().fg(Color::Rgb(239, 154, 154))
    }

    #[rstest]
    #[case::large((100, 100), Rect::new(50, 10, 31, 80))]
    #[case::small((31, 10), Rect::new(0, 0, 31, 10))]
    #[case::too_small((20, 5), Rect::new(0, 0, 20, 5))]
    fn test_playlist_selector_area(
        #[case] terminal_size: (u16, u16),
        #[case] expected_area: Rect,
        state: AppState,
    ) -> Result<()> {
        let (_, area) = setup_test_terminal(terminal_size.0, terminal_size.1);
        let action_tx = tokio::sync::mpsc::unbounded_channel().0;
        let items = vec![];
        let area = PlaylistSelector::new(&state, action_tx, items).area(area);
        assert_eq!(area, expected_area);

        Ok(())
    }

    #[rstest]
    fn test_playlist_selector_render(
        state: AppState,
        #[from(border_style)] style: Style,
    ) -> Result<()> {
        let (mut terminal, _) = setup_test_terminal(31, 10);
        let action_tx = tokio::sync::mpsc::unbounded_channel().0;
        let items = vec![];
        let popup = PlaylistSelector::new(&state, action_tx, items);
        let buffer = terminal
            .draw(|frame| popup.render_popup(frame))?
            .buffer
            .clone();
        let expected = Buffer::with_lines([
            Line::styled("┌Select a Playlist────────────┐", style),
            Line::styled("│n: new playlist──────────────│", style),
            Line::from(vec![
                Span::styled("│", style),
                Span::raw("▪ "),
                Span::raw("playlist 1").bold(),
                Span::raw("                 "),
                Span::styled("│", style),
            ]),
            Line::from(vec![
                Span::styled("│", style),
                Span::raw("                             "),
                Span::styled("│", style),
            ]),
            Line::from(vec![
                Span::styled("│", style),
                Span::raw("                             "),
                Span::styled("│", style),
            ]),
            Line::from(vec![
                Span::styled("│", style),
                Span::raw("                             "),
                Span::styled("│", style),
            ]),
            Line::from(vec![
                Span::styled("│", style),
                Span::raw("                             "),
                Span::styled("│", style),
            ]),
            Line::from(vec![
                Span::styled("│", style),
                Span::raw("                             "),
                Span::styled("│", style),
            ]),
            Line::from(vec![
                Span::styled("│", style),
                Span::raw("                             "),
                Span::styled("│", style),
            ]),
            Line::styled("└  ⏎ : Select | ↑/↓: Up/Down──┘", style),
        ]);

        assert_eq!(buffer, expected);

        Ok(())
    }

    #[rstest]
    fn test_playlist_selector_render_input_box(
        state: AppState,
        border_style: Style,
        input_box_style: Style,
    ) -> Result<()> {
        let (mut terminal, _) = setup_test_terminal(31, 10);
        let action_tx = tokio::sync::mpsc::unbounded_channel().0;
        let items = vec![];
        let mut popup = PlaylistSelector::new(&state, action_tx, items);
        popup.inner_handle_key_event(KeyEvent::from(KeyCode::Char('n')));
        let buffer = terminal
            .draw(|frame| popup.render_popup(frame))?
            .buffer
            .clone();
        let expected = Buffer::with_lines([
            Line::styled("┌Select a Playlist────────────┐", border_style),
            Line::from(vec![
                Span::styled("│", border_style),
                Span::styled("┌Enter Name:────────────────┐", input_box_style),
                Span::styled("│", border_style),
            ]),
            Line::from(vec![
                Span::styled("│", border_style),
                Span::styled("│                           │", input_box_style),
                Span::styled("│", border_style),
            ]),
            Line::from(vec![
                Span::styled("│", border_style),
                Span::styled("└───────────────────────────┘", input_box_style),
                Span::styled("│", border_style),
            ]),
            Line::styled("│ ⏎ : Create (cancel if empty)│", border_style),
            Line::from(vec![
                Span::styled("│", border_style),
                Span::raw("▪ "),
                Span::raw("playlist 1").bold(),
                Span::raw("                 "),
                Span::styled("│", border_style),
            ]),
            Line::from(vec![
                Span::styled("│", border_style),
                Span::raw("                             "),
                Span::styled("│", border_style),
            ]),
            Line::from(vec![
                Span::styled("│", border_style),
                Span::raw("                             "),
                Span::styled("│", border_style),
            ]),
            Line::from(vec![
                Span::styled("│", border_style),
                Span::raw("                             "),
                Span::styled("│", border_style),
            ]),
            Line::styled("└─────────────────────────────┘", border_style),
        ]);

        assert_eq!(buffer, expected);

        Ok(())
    }
}