mecomp_tui/ui/components/content_view/views/
search.rs

1//! implementation the search view
2
3use std::sync::Mutex;
4
5use crossterm::event::{KeyCode, MouseButton, MouseEvent, MouseEventKind};
6use mecomp_core::rpc::SearchResult;
7use ratatui::{
8    layout::{Alignment, Constraint, Direction, Layout, Margin, Position, Rect},
9    style::{Style, Stylize},
10    text::Line,
11    widgets::{Block, Borders, Scrollbar, ScrollbarOrientation},
12};
13use tokio::sync::mpsc::UnboundedSender;
14
15use crate::{
16    state::action::{Action, AudioAction, PopupAction, QueueAction, ViewAction},
17    ui::{
18        AppState,
19        colors::{TEXT_HIGHLIGHT, TEXT_HIGHLIGHT_ALT, TEXT_NORMAL, border_color},
20        components::{Component, ComponentRender, RenderProps, content_view::ActiveView},
21        widgets::{
22            input_box::{self, InputBox},
23            popups::PopupType,
24            tree::{CheckTree, state::CheckTreeState},
25        },
26    },
27};
28
29use super::checktree_utils::{
30    create_album_tree_item, create_artist_tree_item, create_song_tree_item,
31};
32
33#[allow(clippy::module_name_repetitions)]
34pub struct SearchView {
35    /// Action Sender
36    pub action_tx: UnboundedSender<Action>,
37    /// Mapped Props from state
38    pub props: Props,
39    /// tree state
40    tree_state: Mutex<CheckTreeState<String>>,
41    /// Search Bar
42    search_bar: InputBox,
43    /// Is the search bar focused
44    search_bar_focused: bool,
45}
46
47pub struct Props {
48    pub(crate) search_results: SearchResult,
49}
50
51impl From<&AppState> for Props {
52    fn from(value: &AppState) -> Self {
53        Self {
54            search_results: value.search.clone(),
55        }
56    }
57}
58
59impl Component for SearchView {
60    fn new(
61        state: &AppState,
62        action_tx: tokio::sync::mpsc::UnboundedSender<crate::state::action::Action>,
63    ) -> Self
64    where
65        Self: Sized,
66    {
67        let props = Props::from(state);
68        Self {
69            search_bar: InputBox::new(state, action_tx.clone()),
70            search_bar_focused: true,
71            tree_state: Mutex::new(CheckTreeState::default()),
72            action_tx,
73            props,
74        }
75    }
76
77    fn move_with_state(self, state: &AppState) -> Self
78    where
79        Self: Sized,
80    {
81        Self {
82            search_bar: self.search_bar.move_with_state(state),
83            props: Props::from(state),
84            tree_state: Mutex::new(CheckTreeState::default()),
85            ..self
86        }
87    }
88
89    fn name(&self) -> &'static str {
90        "Search"
91    }
92
93    fn handle_key_event(&mut self, key: crossterm::event::KeyEvent) {
94        match key.code {
95            // arrow keys
96            KeyCode::PageUp => {
97                self.tree_state.lock().unwrap().select_relative(|current| {
98                    current.map_or(self.props.search_results.len().saturating_sub(1), |c| {
99                        c.saturating_sub(10)
100                    })
101                });
102            }
103            KeyCode::Up => {
104                self.tree_state.lock().unwrap().key_up();
105            }
106            KeyCode::PageDown => {
107                self.tree_state
108                    .lock()
109                    .unwrap()
110                    .select_relative(|current| current.map_or(0, |c| c.saturating_add(10)));
111            }
112            KeyCode::Down => {
113                self.tree_state.lock().unwrap().key_down();
114            }
115            KeyCode::Left => {
116                self.tree_state.lock().unwrap().key_left();
117            }
118            KeyCode::Right => {
119                self.tree_state.lock().unwrap().key_right();
120            }
121            KeyCode::Char(' ') if !self.search_bar_focused => {
122                self.tree_state.lock().unwrap().key_space();
123            }
124            // when searchbar focused, enter key will search
125            KeyCode::Enter if self.search_bar_focused => {
126                self.search_bar_focused = false;
127                self.tree_state.lock().unwrap().reset();
128                if !self.search_bar.is_empty() {
129                    self.action_tx
130                        .send(Action::Search(self.search_bar.text().to_string()))
131                        .unwrap();
132                    self.search_bar.reset();
133                }
134            }
135            KeyCode::Char('/') if !self.search_bar_focused => {
136                self.search_bar_focused = true;
137            }
138            // when searchbar unfocused, enter key will open the selected node
139            KeyCode::Enter if !self.search_bar_focused => {
140                if self.tree_state.lock().unwrap().toggle_selected() {
141                    let things = self.tree_state.lock().unwrap().get_selected_thing();
142
143                    if let Some(thing) = things {
144                        self.action_tx
145                            .send(Action::ActiveView(ViewAction::Set(thing.into())))
146                            .unwrap();
147                    }
148                }
149            }
150            // when search bar unfocused, and there are checked items, "q" will send the checked items to the queue
151            KeyCode::Char('q') if !self.search_bar_focused => {
152                let things = self.tree_state.lock().unwrap().get_checked_things();
153                if !things.is_empty() {
154                    self.action_tx
155                        .send(Action::Audio(AudioAction::Queue(QueueAction::Add(things))))
156                        .unwrap();
157                }
158            }
159            // when search bar unfocused, and there are checked items, "r" will start a radio with the checked items
160            KeyCode::Char('r') if !self.search_bar_focused => {
161                let things = self.tree_state.lock().unwrap().get_checked_things();
162                if !things.is_empty() {
163                    self.action_tx
164                        .send(Action::ActiveView(ViewAction::Set(ActiveView::Radio(
165                            things,
166                        ))))
167                        .unwrap();
168                }
169            }
170            // when search bar unfocused, and there are checked items, "p" will send the checked items to the playlist
171            KeyCode::Char('p') if !self.search_bar_focused => {
172                let things = self.tree_state.lock().unwrap().get_checked_things();
173                if !things.is_empty() {
174                    self.action_tx
175                        .send(Action::Popup(PopupAction::Open(PopupType::Playlist(
176                            things,
177                        ))))
178                        .unwrap();
179                }
180            }
181
182            // defer to the search bar, if it is focused
183            _ if self.search_bar_focused => {
184                self.search_bar.handle_key_event(key);
185            }
186            _ => {}
187        }
188    }
189
190    fn handle_mouse_event(&mut self, mouse: MouseEvent, area: Rect) {
191        let MouseEvent {
192            kind, column, row, ..
193        } = mouse;
194        let mouse_position = Position::new(column, row);
195
196        // adjust the area to account for the border
197        let [search_bar_area, content_area] = split_area(area);
198        let content_area = content_area.inner(Margin::new(1, 1));
199
200        if self.search_bar_focused {
201            if search_bar_area.contains(mouse_position) {
202                self.search_bar.handle_mouse_event(mouse, search_bar_area);
203            } else if content_area.contains(mouse_position)
204                && kind == MouseEventKind::Down(MouseButton::Left)
205            {
206                self.search_bar_focused = false;
207            }
208        } else if kind == MouseEventKind::Down(MouseButton::Left)
209            && search_bar_area.contains(mouse_position)
210        {
211            self.search_bar_focused = true;
212        } else {
213            let content_area = Rect {
214                height: content_area.height.saturating_sub(1),
215                ..content_area
216            };
217
218            let result = self
219                .tree_state
220                .lock()
221                .unwrap()
222                .handle_mouse_event(mouse, content_area);
223            if let Some(action) = result {
224                self.action_tx.send(action).unwrap();
225            }
226        }
227    }
228}
229
230fn split_area(area: Rect) -> [Rect; 2] {
231    let [search_bar_area, content_area] = *Layout::default()
232        .direction(Direction::Vertical)
233        .constraints([Constraint::Length(3), Constraint::Min(4)].as_ref())
234        .split(area)
235    else {
236        panic!("Failed to split search view area");
237    };
238    [search_bar_area, content_area]
239}
240
241impl ComponentRender<RenderProps> for SearchView {
242    fn render_border(&self, frame: &mut ratatui::Frame, props: RenderProps) -> RenderProps {
243        let border_style =
244            Style::default().fg(border_color(props.is_focused && !self.search_bar_focused).into());
245
246        // split view
247        let [search_bar_area, content_area] = split_area(props.area);
248
249        // render the search bar
250        self.search_bar.render(
251            frame,
252            input_box::RenderProps {
253                area: search_bar_area,
254                text_color: if self.search_bar_focused {
255                    TEXT_HIGHLIGHT_ALT.into()
256                } else {
257                    TEXT_NORMAL.into()
258                },
259                border: Block::bordered().title("Search").border_style(
260                    Style::default()
261                        .fg(border_color(self.search_bar_focused && props.is_focused).into()),
262                ),
263                show_cursor: self.search_bar_focused,
264            },
265        );
266
267        // put a border around the content area
268        let area = if self.search_bar_focused {
269            let border = Block::bordered()
270                .title_top("Results")
271                .title_bottom(" \u{23CE} : Search")
272                .border_style(border_style);
273            frame.render_widget(&border, content_area);
274            border.inner(content_area)
275        } else {
276            let border = Block::bordered()
277                .title_top("Results")
278                .title_bottom(" \u{23CE} : Open | ←/↑/↓/→: Navigate")
279                .border_style(border_style);
280            frame.render_widget(&border, content_area);
281            let content_area = border.inner(content_area);
282
283            let border = Block::default()
284                .borders(Borders::BOTTOM)
285                .title_bottom("/: Search | \u{2423} : Check")
286                .border_style(border_style);
287            frame.render_widget(&border, content_area);
288            border.inner(content_area)
289        };
290
291        // if there are checked items, put an additional border around the content area to display additional instructions
292        let area = if self
293            .tree_state
294            .lock()
295            .unwrap()
296            .get_checked_things()
297            .is_empty()
298        {
299            area
300        } else {
301            let border = Block::default()
302                .borders(Borders::TOP)
303                .title_top("q: add to queue | r: start radio | p: add to playlist")
304                .border_style(border_style);
305            frame.render_widget(&border, area);
306            border.inner(area)
307        };
308
309        RenderProps { area, ..props }
310    }
311
312    fn render_content(&self, frame: &mut ratatui::Frame, props: RenderProps) {
313        // if there are no search results, render a message
314        if self.props.search_results.is_empty() {
315            frame.render_widget(
316                Line::from("No results found")
317                    .style(Style::default().fg(TEXT_NORMAL.into()))
318                    .alignment(Alignment::Center),
319                props.area,
320            );
321            return;
322        }
323
324        // create tree to hold results
325        let song_tree = create_song_tree_item(&self.props.search_results.songs).unwrap();
326        let album_tree = create_album_tree_item(&self.props.search_results.albums).unwrap();
327        let artist_tree = create_artist_tree_item(&self.props.search_results.artists).unwrap();
328        let items = &[song_tree, album_tree, artist_tree];
329
330        // render the search results
331        frame.render_stateful_widget(
332            CheckTree::new(items)
333                .unwrap()
334                .highlight_style(Style::default().fg(TEXT_HIGHLIGHT.into()).bold())
335                .experimental_scrollbar(Some(Scrollbar::new(ScrollbarOrientation::VerticalRight))),
336            props.area,
337            &mut self.tree_state.lock().unwrap(),
338        );
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345    use crate::{
346        test_utils::{assert_buffer_eq, item_id, setup_test_terminal, state_with_everything},
347        ui::components::content_view::ActiveView,
348    };
349    use crossterm::event::KeyEvent;
350    use crossterm::event::KeyModifiers;
351    use pretty_assertions::assert_eq;
352    use ratatui::buffer::Buffer;
353
354    #[test]
355    fn test_render_search_focused() {
356        let (tx, _) = tokio::sync::mpsc::unbounded_channel();
357        let view = SearchView::new(&AppState::default(), tx).move_with_state(&AppState {
358            active_view: ActiveView::Search,
359            ..state_with_everything()
360        });
361
362        let (mut terminal, area) = setup_test_terminal(24, 8);
363        let props = RenderProps {
364            area,
365            is_focused: true,
366        };
367        let buffer = terminal
368            .draw(|frame| view.render(frame, props))
369            .unwrap()
370            .buffer
371            .clone();
372        let expected = Buffer::with_lines([
373            "┌Search────────────────┐",
374            "│                      │",
375            "└──────────────────────┘",
376            "┌Results───────────────┐",
377            "│▶ Songs (1):          │",
378            "│▶ Albums (1):         │",
379            "│▶ Artists (1):        │",
380            "└ ⏎ : Search───────────┘",
381        ]);
382
383        assert_buffer_eq(&buffer, &expected);
384    }
385
386    #[test]
387    fn test_render_empty() {
388        let (tx, _) = tokio::sync::mpsc::unbounded_channel();
389        let view = SearchView::new(&AppState::default(), tx).move_with_state(&AppState {
390            active_view: ActiveView::Search,
391            search: SearchResult::default(),
392            ..state_with_everything()
393        });
394
395        let (mut terminal, area) = setup_test_terminal(24, 8);
396        let props = RenderProps {
397            area,
398            is_focused: true,
399        };
400        let buffer = terminal
401            .draw(|frame| view.render(frame, props))
402            .unwrap()
403            .buffer
404            .clone();
405        let expected = Buffer::with_lines([
406            "┌Search────────────────┐",
407            "│                      │",
408            "└──────────────────────┘",
409            "┌Results───────────────┐",
410            "│   No results found   │",
411            "│                      │",
412            "│                      │",
413            "└ ⏎ : Search───────────┘",
414        ]);
415
416        assert_buffer_eq(&buffer, &expected);
417    }
418
419    #[test]
420    fn test_render_search_unfocused() {
421        let (tx, _) = tokio::sync::mpsc::unbounded_channel();
422        let mut view = SearchView::new(&AppState::default(), tx).move_with_state(&AppState {
423            active_view: ActiveView::Search,
424            ..state_with_everything()
425        });
426
427        let (mut terminal, area) = setup_test_terminal(32, 9);
428        let props = RenderProps {
429            area,
430            is_focused: true,
431        };
432
433        view.handle_key_event(KeyEvent::from(KeyCode::Enter));
434
435        let buffer = terminal
436            .draw(|frame| view.render(frame, props))
437            .unwrap()
438            .buffer
439            .clone();
440        let expected = Buffer::with_lines([
441            "┌Search────────────────────────┐",
442            "│                              │",
443            "└──────────────────────────────┘",
444            "┌Results───────────────────────┐",
445            "│▶ Songs (1):                  │",
446            "│▶ Albums (1):                 │",
447            "│▶ Artists (1):                │",
448            "│/: Search | ␣ : Check─────────│",
449            "└ ⏎ : Open | ←/↑/↓/→: Navigate─┘",
450        ]);
451        assert_buffer_eq(&buffer, &expected);
452    }
453
454    #[test]
455    fn smoke_navigation() {
456        let (tx, _) = tokio::sync::mpsc::unbounded_channel();
457        let mut view = SearchView::new(&AppState::default(), tx).move_with_state(&AppState {
458            active_view: ActiveView::Search,
459            ..state_with_everything()
460        });
461
462        view.handle_key_event(KeyEvent::from(KeyCode::Up));
463        view.handle_key_event(KeyEvent::from(KeyCode::PageUp));
464        view.handle_key_event(KeyEvent::from(KeyCode::Down));
465        view.handle_key_event(KeyEvent::from(KeyCode::PageDown));
466        view.handle_key_event(KeyEvent::from(KeyCode::Left));
467        view.handle_key_event(KeyEvent::from(KeyCode::Right));
468    }
469
470    #[test]
471    #[allow(clippy::too_many_lines)]
472    fn test_keys() {
473        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
474        let mut view = SearchView::new(&AppState::default(), tx).move_with_state(&AppState {
475            active_view: ActiveView::Search,
476            ..state_with_everything()
477        });
478
479        let (mut terminal, area) = setup_test_terminal(32, 10);
480        let props = RenderProps {
481            area,
482            is_focused: true,
483        };
484
485        view.handle_key_event(KeyEvent::from(KeyCode::Char('q')));
486        view.handle_key_event(KeyEvent::from(KeyCode::Char('r')));
487        view.handle_key_event(KeyEvent::from(KeyCode::Char('p')));
488
489        let buffer = terminal
490            .draw(|frame| view.render(frame, props))
491            .unwrap()
492            .buffer
493            .clone();
494        let expected = Buffer::with_lines([
495            "┌Search────────────────────────┐",
496            "│qrp                           │",
497            "└──────────────────────────────┘",
498            "┌Results───────────────────────┐",
499            "│▶ Songs (1):                  │",
500            "│▶ Albums (1):                 │",
501            "│▶ Artists (1):                │",
502            "│                              │",
503            "│                              │",
504            "└ ⏎ : Search───────────────────┘",
505        ]);
506        assert_buffer_eq(&buffer, &expected);
507
508        view.handle_key_event(KeyEvent::from(KeyCode::Enter));
509        let action = rx.blocking_recv().unwrap();
510        assert_eq!(action, Action::Search("qrp".to_string()));
511
512        let buffer = terminal
513            .draw(|frame| view.render(frame, props))
514            .unwrap()
515            .buffer
516            .clone();
517        let expected = Buffer::with_lines([
518            "┌Search────────────────────────┐",
519            "│                              │",
520            "└──────────────────────────────┘",
521            "┌Results───────────────────────┐",
522            "│▶ Songs (1):                  │",
523            "│▶ Albums (1):                 │",
524            "│▶ Artists (1):                │",
525            "│                              │",
526            "│/: Search | ␣ : Check─────────│",
527            "└ ⏎ : Open | ←/↑/↓/→: Navigate─┘",
528        ]);
529        assert_buffer_eq(&buffer, &expected);
530
531        view.handle_key_event(KeyEvent::from(KeyCode::Char('/')));
532        view.handle_key_event(KeyEvent::from(KeyCode::Enter));
533
534        let buffer = terminal
535            .draw(|frame| view.render(frame, props))
536            .unwrap()
537            .buffer
538            .clone();
539        assert_buffer_eq(&buffer, &expected);
540
541        view.handle_key_event(KeyEvent::from(KeyCode::Down));
542        view.handle_key_event(KeyEvent::from(KeyCode::Enter));
543
544        let buffer = terminal
545            .draw(|frame| view.render(frame, props))
546            .unwrap()
547            .buffer
548            .clone();
549        let expected = Buffer::with_lines([
550            "┌Search────────────────────────┐",
551            "│                              │",
552            "└──────────────────────────────┘",
553            "┌Results───────────────────────┐",
554            "│▼ Songs (1):                  │",
555            "│  ☐ Test Song Test Artist     │",
556            "│▶ Albums (1):                 │",
557            "│▶ Artists (1):                │",
558            "│/: Search | ␣ : Check─────────│",
559            "└ ⏎ : Open | ←/↑/↓/→: Navigate─┘",
560        ]);
561        assert_buffer_eq(&buffer, &expected);
562
563        view.handle_key_event(KeyEvent::from(KeyCode::Down));
564        view.handle_key_event(KeyEvent::from(KeyCode::Char(' ')));
565
566        let buffer = terminal
567            .draw(|frame| view.render(frame, props))
568            .unwrap()
569            .buffer
570            .clone();
571        let expected = Buffer::with_lines([
572            "┌Search────────────────────────┐",
573            "│                              │",
574            "└──────────────────────────────┘",
575            "┌Results───────────────────────┐",
576            "│q: add to queue | r: start rad│",
577            "│▼ Songs (1):                 ▲│",
578            "│  ☑ Test Song Test Artist    █│",
579            "│▶ Albums (1):                ▼│",
580            "│/: Search | ␣ : Check─────────│",
581            "└ ⏎ : Open | ←/↑/↓/→: Navigate─┘",
582        ]);
583        assert_buffer_eq(&buffer, &expected);
584
585        view.handle_key_event(KeyEvent::from(KeyCode::Char('q')));
586        let action = rx.blocking_recv().unwrap();
587        assert_eq!(
588            action,
589            Action::Audio(AudioAction::Queue(QueueAction::Add(vec![
590                ("song", item_id()).into()
591            ])))
592        );
593
594        view.handle_key_event(KeyEvent::from(KeyCode::Char('r')));
595        let action = rx.blocking_recv().unwrap();
596        assert_eq!(
597            action,
598            Action::ActiveView(ViewAction::Set(ActiveView::Radio(vec![
599                ("song", item_id()).into()
600            ],)))
601        );
602
603        view.handle_key_event(KeyEvent::from(KeyCode::Char('p')));
604        let action = rx.blocking_recv().unwrap();
605        assert_eq!(
606            action,
607            Action::Popup(PopupAction::Open(PopupType::Playlist(vec![
608                ("song", item_id()).into()
609            ])))
610        );
611    }
612
613    #[test]
614    #[allow(clippy::too_many_lines)]
615    fn test_mouse() {
616        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
617        let mut view = SearchView::new(&state_with_everything(), tx);
618
619        let (mut terminal, area) = setup_test_terminal(32, 10);
620        let props = RenderProps {
621            area,
622            is_focused: true,
623        };
624        let buffer = terminal
625            .draw(|frame| view.render(frame, props))
626            .unwrap()
627            .buffer
628            .clone();
629        let expected = Buffer::with_lines([
630            "┌Search────────────────────────┐",
631            "│                              │",
632            "└──────────────────────────────┘",
633            "┌Results───────────────────────┐",
634            "│▶ Songs (1):                  │",
635            "│▶ Albums (1):                 │",
636            "│▶ Artists (1):                │",
637            "│                              │",
638            "│                              │",
639            "└ ⏎ : Search───────────────────┘",
640        ]);
641        assert_buffer_eq(&buffer, &expected);
642
643        // put some text in the search bar
644        view.handle_key_event(KeyEvent::from(KeyCode::Char('a')));
645        view.handle_key_event(KeyEvent::from(KeyCode::Char('b')));
646        view.handle_key_event(KeyEvent::from(KeyCode::Char('c')));
647
648        let buffer = terminal
649            .draw(|frame| view.render(frame, props))
650            .unwrap()
651            .buffer
652            .clone();
653        let expected = Buffer::with_lines([
654            "┌Search────────────────────────┐",
655            "│abc                           │",
656            "└──────────────────────────────┘",
657            "┌Results───────────────────────┐",
658            "│▶ Songs (1):                  │",
659            "│▶ Albums (1):                 │",
660            "│▶ Artists (1):                │",
661            "│                              │",
662            "│                              │",
663            "└ ⏎ : Search───────────────────┘",
664        ]);
665        assert_buffer_eq(&buffer, &expected);
666
667        // click in the search bar and ensure the cursor is moved to the right place
668        view.handle_mouse_event(
669            MouseEvent {
670                kind: MouseEventKind::Down(MouseButton::Left),
671                column: 2,
672                row: 1,
673                modifiers: KeyModifiers::empty(),
674            },
675            area,
676        );
677        view.handle_key_event(KeyEvent::from(KeyCode::Char('c')));
678        let buffer = terminal
679            .draw(|frame| view.render(frame, props))
680            .unwrap()
681            .buffer
682            .clone();
683        let expected = Buffer::with_lines([
684            "┌Search────────────────────────┐",
685            "│acbc                          │",
686            "└──────────────────────────────┘",
687            "┌Results───────────────────────┐",
688            "│▶ Songs (1):                  │",
689            "│▶ Albums (1):                 │",
690            "│▶ Artists (1):                │",
691            "│                              │",
692            "│                              │",
693            "└ ⏎ : Search───────────────────┘",
694        ]);
695
696        assert_buffer_eq(&buffer, &expected);
697
698        // click out of the search bar
699        view.handle_mouse_event(
700            MouseEvent {
701                kind: MouseEventKind::Down(MouseButton::Left),
702                column: 2,
703                row: 5,
704                modifiers: KeyModifiers::empty(),
705            },
706            area,
707        );
708
709        // scroll down
710        view.handle_mouse_event(
711            MouseEvent {
712                kind: MouseEventKind::ScrollDown,
713                column: 2,
714                row: 4,
715                modifiers: KeyModifiers::empty(),
716            },
717            area,
718        );
719        view.handle_mouse_event(
720            MouseEvent {
721                kind: MouseEventKind::ScrollDown,
722                column: 2,
723                row: 4,
724                modifiers: KeyModifiers::empty(),
725            },
726            area,
727        );
728
729        // click on the selected dropdown
730        view.handle_mouse_event(
731            MouseEvent {
732                kind: MouseEventKind::Down(MouseButton::Left),
733                column: 2,
734                row: 5,
735                modifiers: KeyModifiers::empty(),
736            },
737            area,
738        );
739        let expected = Buffer::with_lines([
740            "┌Search────────────────────────┐",
741            "│acbc                          │",
742            "└──────────────────────────────┘",
743            "┌Results───────────────────────┐",
744            "│▶ Songs (1):                  │",
745            "│▼ Albums (1):                 │",
746            "│  ☐ Test Album Test Artist    │",
747            "│▶ Artists (1):                │",
748            "│/: Search | ␣ : Check─────────│",
749            "└ ⏎ : Open | ←/↑/↓/→: Navigate─┘",
750        ]);
751        let buffer = terminal
752            .draw(|frame| view.render(frame, props))
753            .unwrap()
754            .buffer
755            .clone();
756        assert_buffer_eq(&buffer, &expected);
757
758        // scroll up
759        view.handle_mouse_event(
760            MouseEvent {
761                kind: MouseEventKind::ScrollUp,
762                column: 2,
763                row: 4,
764                modifiers: KeyModifiers::empty(),
765            },
766            area,
767        );
768
769        // click on the selected dropdown
770        view.handle_mouse_event(
771            MouseEvent {
772                kind: MouseEventKind::Down(MouseButton::Left),
773                column: 2,
774                row: 4,
775                modifiers: KeyModifiers::empty(),
776            },
777            area,
778        );
779        let expected = Buffer::with_lines([
780            "┌Search────────────────────────┐",
781            "│acbc                          │",
782            "└──────────────────────────────┘",
783            "┌Results───────────────────────┐",
784            "│▼ Songs (1):                 ▲│",
785            "│  ☐ Test Song Test Artist    █│",
786            "│▼ Albums (1):                █│",
787            "│  ☐ Test Album Test Artist   ▼│",
788            "│/: Search | ␣ : Check─────────│",
789            "└ ⏎ : Open | ←/↑/↓/→: Navigate─┘",
790        ]);
791        let buffer = terminal
792            .draw(|frame| view.render(frame, props))
793            .unwrap()
794            .buffer
795            .clone();
796        assert_buffer_eq(&buffer, &expected);
797
798        // scroll down
799        view.handle_mouse_event(
800            MouseEvent {
801                kind: MouseEventKind::ScrollDown,
802                column: 2,
803                row: 4,
804                modifiers: KeyModifiers::empty(),
805            },
806            area,
807        );
808
809        // click on the selected item
810        view.handle_mouse_event(
811            MouseEvent {
812                kind: MouseEventKind::Down(MouseButton::Left),
813                column: 2,
814                row: 5,
815                modifiers: KeyModifiers::empty(),
816            },
817            area,
818        );
819        assert_eq!(
820            rx.blocking_recv().unwrap(),
821            Action::ActiveView(ViewAction::Set(ActiveView::Song(item_id())))
822        );
823        let expected = Buffer::with_lines([
824            "┌Search────────────────────────┐",
825            "│acbc                          │",
826            "└──────────────────────────────┘",
827            "┌Results───────────────────────┐",
828            "│q: add to queue | r: start rad│",
829            "│▼ Songs (1):                 ▲│",
830            "│  ☑ Test Song Test Artist    █│",
831            "│▼ Albums (1):                ▼│",
832            "│/: Search | ␣ : Check─────────│",
833            "└ ⏎ : Open | ←/↑/↓/→: Navigate─┘",
834        ]);
835        let buffer = terminal
836            .draw(|frame| view.render(frame, props))
837            .unwrap()
838            .buffer
839            .clone();
840        assert_buffer_eq(&buffer, &expected);
841    }
842}