src/items/searchbar.rs

187 lines · 5877 bytes

  1use std::error::Error;
  2
  3use crate::{config::*, global::structs::*};
  4
  5#[cfg(feature = "clipboard")]
  6use crate::global::functions::*;
  7
  8use crossterm::event::KeyCode;
  9use ratatui::{
 10    layout::Alignment,
 11    style::Style,
 12    widgets::{Block, Borders},
 13};
 14use tui_additions::{framework::FrameworkItem, widgets::TextField};
 15
 16/// the search bar item
 17#[derive(Clone, Default)]
 18pub struct SearchBar {
 19    pub text_field: TextField,
 20}
 21
 22impl FrameworkItem for SearchBar {
 23    // basically is a TextField with borders
 24    fn render(
 25        &mut self,
 26        frame: &mut ratatui::Frame<ratatui::backend::CrosstermBackend<std::io::Stdout>>,
 27        framework: &mut tui_additions::framework::FrameworkClean,
 28        area: ratatui::layout::Rect,
 29        popup_render: bool,
 30        info: tui_additions::framework::ItemInfo,
 31    ) {
 32        if popup_render {
 33            return;
 34        }
 35
 36        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
 37
 38        let block = Block::default()
 39            .title("Search YouTube")
 40            .title_alignment(Alignment::Center)
 41            .borders(Borders::ALL)
 42            .border_type(appearance.borders)
 43            .border_style(Style::default().fg(if info.hover {
 44                appearance.colors.outline_hover
 45            } else if info.selected {
 46                appearance.colors.outline_selected
 47            } else {
 48                appearance.colors.outline
 49            }));
 50
 51        let inner = block.inner(area);
 52
 53        frame.render_widget(block, area);
 54
 55        self.text_field.set_width(inner.width);
 56
 57        frame.render_widget(self.text_field.clone(), inner);
 58    }
 59
 60    // sets text field content to the curreny search query, thats it
 61    // kinda pointless if it doesnt break anything gonna remove it
 62    fn load_item(
 63        &mut self,
 64        framework: &mut tui_additions::framework::FrameworkClean,
 65        _info: tui_additions::framework::ItemInfo,
 66    ) -> Result<(), Box<dyn Error>> {
 67        let search = framework.data.state.get::<Search>().unwrap().query.clone();
 68        self.text_field.content = search;
 69        let _ = self.text_field.last();
 70
 71        Ok(())
 72    }
 73
 74    fn key_event(
 75        &mut self,
 76        framework: &mut tui_additions::framework::FrameworkClean,
 77        key: crossterm::event::KeyEvent,
 78        _info: tui_additions::framework::ItemInfo,
 79    ) -> Result<(), Box<dyn Error>> {
 80        // pasting clipboard content
 81        #[cfg(feature = "clipboard")]
 82        if framework
 83            .data
 84            .global
 85            .get::<KeyBindingsConfig>()
 86            .unwrap()
 87            .get(key)
 88            == Some(KeyAction::Paste)
 89        {
 90            let content = get_clipboard();
 91            if content.is_empty() {
 92                *framework.data.global.get_mut::<Message>().unwrap() =
 93                    Message::Error(String::from("Clipboard empty"));
 94                framework
 95                    .data
 96                    .state
 97                    .get_mut::<Tasks>()
 98                    .unwrap()
 99                    .priority
100                    .push(Task::RenderAll);
101                return Ok(());
102            }
103
104            // push all characters at cursor location
105            content.chars().for_each(|c| {
106                let _ = self.text_field.push(c);
107            });
108            framework
109                .data
110                .state
111                .get_mut::<Tasks>()
112                .unwrap()
113                .priority
114                .push(Task::RenderAll);
115            return Ok(());
116        }
117
118        let updated = match key.code {
119            KeyCode::Backspace => self.text_field.remove(self.text_field.cursor).is_ok(),
120            KeyCode::Char(c) => self.text_field.push(c).is_ok(),
121            KeyCode::Up => self.text_field.first().is_ok(),
122            KeyCode::Down => self.text_field.last().is_ok(),
123            KeyCode::Right => self.text_field.right().is_ok(),
124            KeyCode::Left => self.text_field.left().is_ok(),
125            KeyCode::Enter => {
126                if self.text_field.content.is_empty() {
127                    *framework.data.global.get_mut::<Message>().unwrap() =
128                        Message::Message(String::from("Search string must not be empty"));
129                    framework
130                        .data
131                        .state
132                        .get_mut::<Tasks>()
133                        .unwrap()
134                        .priority
135                        .push(Task::RenderAll);
136                    return Ok(());
137                }
138
139                let mut search = framework.data.state.get_mut::<Search>().unwrap();
140                search.query = self.text_field.content.clone();
141                let search = search.clone();
142                let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
143                tasks.priority.push(Task::LoadPage(Page::Search(search)));
144                false
145            }
146            _ => false,
147        };
148
149        // only re-render screen if updated
150        if updated {
151            let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
152            tasks.priority.push(Task::RenderAll);
153        }
154
155        Ok(())
156    }
157
158    fn mouse_event(
159        &mut self,
160        _framework: &mut tui_additions::framework::FrameworkClean,
161        mut x: u16,
162        y: u16,
163        _absolute_x: u16,
164        _absolute_y: u16,
165    ) -> bool {
166        if y != 1 || x == 0 {
167            return false;
168        }
169
170        x -= 1; // there is 1 character to the left of the text field
171
172        if x == self.text_field.cursor as u16 {
173            return false;
174        }
175
176        if x > self.text_field.content.len() as u16 {
177            return self.text_field.last().is_ok();
178        }
179
180        self.text_field.cursor = x as usize;
181        self.text_field.update().is_ok()
182    }
183
184    fn selectable(&self) -> bool {
185        true
186    }
187}