src/items/searchbar.rs

238 lines · 8383 bytes

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