Revert regex and String implementation

Use Vec<char> for search_input to prevent panics when using multi-byte characters, use lowercase conversion instead of regex, Added comments for clarity
This commit is contained in:
Jeevitha Kannan K S 2024-11-11 13:23:36 +05:30
parent 35159b8393
commit 2d1f5dbc80
No known key found for this signature in database
GPG Key ID: 5904C34A2F7CE333
3 changed files with 67 additions and 66 deletions

2
Cargo.lock generated
View File

@ -449,13 +449,13 @@ dependencies = [
"portable-pty", "portable-pty",
"rand", "rand",
"ratatui", "ratatui",
"regex",
"temp-dir", "temp-dir",
"textwrap", "textwrap",
"time", "time",
"tree-sitter-bash", "tree-sitter-bash",
"tree-sitter-highlight", "tree-sitter-highlight",
"tui-term", "tui-term",
"unicode-width 0.2.0",
"zips", "zips",
] ]

View File

@ -29,7 +29,7 @@ textwrap = "0.16.1"
anstyle = "1.0.8" anstyle = "1.0.8"
ansi-to-tui = "7.0.0" ansi-to-tui = "7.0.0"
zips = "0.1.7" zips = "0.1.7"
regex = { version = "1.3", default-features = false, features = ["std"] } unicode-width = "0.2.0"
[[bin]] [[bin]]
name = "linutil" name = "linutil"

View File

@ -8,7 +8,7 @@ use ratatui::{
widgets::{Block, Borders, Paragraph}, widgets::{Block, Borders, Paragraph},
Frame, Frame,
}; };
use regex::RegexBuilder; use unicode_width::UnicodeWidthChar;
pub enum SearchAction { pub enum SearchAction {
None, None,
@ -17,17 +17,19 @@ pub enum SearchAction {
} }
pub struct Filter { pub struct Filter {
search_input: String, // Use Vec<char> to handle multi-byte characters like emojis
search_input: Vec<char>,
in_search_mode: bool, in_search_mode: bool,
input_position: usize, input_position: usize,
items: Vec<ListEntry>, items: Vec<ListEntry>,
// No complex string manipulation is done with completion_preview so we can use String unlike search_input
completion_preview: Option<String>, completion_preview: Option<String>,
} }
impl Filter { impl Filter {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
search_input: String::new(), search_input: vec![],
in_search_mode: false, in_search_mode: false,
input_position: 0, input_position: 0,
items: vec![], items: vec![],
@ -62,12 +64,14 @@ impl Filter {
.collect(); .collect();
} else { } else {
self.items.clear(); self.items.clear();
if let Ok(regex) = self.regex_builder(&regex::escape(&self.search_input)) { let query_lower = self.search_input.iter().collect::<String>().to_lowercase();
for tab in tabs { for tab in tabs {
let mut stack = vec![tab.tree.root().id()]; let mut stack = vec![tab.tree.root().id()];
while let Some(node_id) = stack.pop() { while let Some(node_id) = stack.pop() {
let node = tab.tree.get(node_id).unwrap(); let node = tab.tree.get(node_id).unwrap();
if regex.is_match(&node.value().name) && !node.has_children() { if node.value().name.to_lowercase().contains(&query_lower)
&& !node.has_children()
{
self.items.push(ListEntry { self.items.push(ListEntry {
node: node.value().clone(), node: node.value().clone(),
id: node.id(), id: node.id(),
@ -79,9 +83,6 @@ impl Filter {
} }
self.items self.items
.sort_unstable_by(|a, b| a.node.name.cmp(&b.node.name)); .sort_unstable_by(|a, b| a.node.name.cmp(&b.node.name));
} else {
self.search_input.clear();
}
} }
self.update_completion_preview(); self.update_completion_preview();
} }
@ -90,16 +91,15 @@ impl Filter {
self.completion_preview = if self.items.is_empty() || self.search_input.is_empty() { self.completion_preview = if self.items.is_empty() || self.search_input.is_empty() {
None None
} else { } else {
let pattern = format!("(?i)^{}", regex::escape(&self.search_input)); let input = self.search_input.iter().collect::<String>().to_lowercase();
if let Ok(regex) = self.regex_builder(&pattern) {
self.items.iter().find_map(|item| { self.items.iter().find_map(|item| {
regex let item_name_lower = &item.node.name.to_lowercase();
.find(&item.node.name) if item_name_lower.starts_with(&input) {
.map(|mat| item.node.name[mat.end()..].to_string()) Some(item_name_lower[input.len()..].to_string())
})
} else { } else {
None None
} }
})
} }
} }
@ -108,10 +108,8 @@ impl Filter {
let display_text = if !self.in_search_mode && self.search_input.is_empty() { let display_text = if !self.in_search_mode && self.search_input.is_empty() {
Span::raw("Press / to search") Span::raw("Press / to search")
} else { } else {
Span::styled( let input_text = self.search_input.iter().collect::<String>();
&self.search_input, Span::styled(input_text, Style::default().fg(theme.focused_color()))
Style::default().fg(theme.focused_color()),
)
}; };
let search_color = if self.in_search_mode { let search_color = if self.in_search_mode {
@ -135,15 +133,31 @@ impl Filter {
// Render cursor in search bar // Render cursor in search bar
if self.in_search_mode { if self.in_search_mode {
let x = area.x + self.input_position as u16 + 1; // Calculate the visual width of search input so that completion preview can be displayed after the search input
let search_input_size: u16 = self
.search_input
.iter()
.map(|c| c.width().unwrap_or(1) as u16)
.sum();
let cursor_position: u16 = self.search_input[..self.input_position]
.iter()
.map(|c| c.width().unwrap_or(1) as u16)
.sum();
let x = area.x + cursor_position + 1;
let y = area.y + 1; let y = area.y + 1;
frame.set_cursor_position(Position::new(x, y)); frame.set_cursor_position(Position::new(x, y));
if let Some(preview) = &self.completion_preview { if let Some(preview) = &self.completion_preview {
let preview_x = area.x + self.search_input.len() as u16 + 1; let preview_x = area.x + search_input_size + 1;
let preview_span = let preview_span =
Span::styled(preview, Style::default().fg(theme.search_preview_color())); Span::styled(preview, Style::default().fg(theme.search_preview_color()));
let preview_area = Rect::new(preview_x, y, preview.len() as u16, 1); let preview_area = Rect::new(
preview_x,
y,
(preview.len() as u16).min(area.width - search_input_size - 1), // Ensure the completion preview stays within the search bar bounds
1,
);
frame.render_widget(Paragraph::new(preview_span), preview_area); frame.render_widget(Paragraph::new(preview_span), preview_area);
} }
} }
@ -211,37 +225,24 @@ impl Filter {
} }
} }
fn regex_builder(&self, pattern: &str) -> Result<regex::Regex, regex::Error> {
RegexBuilder::new(pattern).case_insensitive(true).build()
}
fn complete_search(&mut self) -> SearchAction { fn complete_search(&mut self) -> SearchAction {
if self.completion_preview.is_none() { if self.completion_preview.is_some() {
SearchAction::None let input = &self.search_input.iter().collect::<String>().to_lowercase();
} else { if let Some(search_completion) = self
let pattern = format!("(?i)^{}", self.search_input);
if let Ok(regex) = self.regex_builder(&pattern) {
self.search_input = self
.items .items
.iter() .iter()
.find_map(|item| { .find(|item| item.node.name.to_lowercase().starts_with(input))
if regex.is_match(&item.node.name) { {
Some(item.node.name.clone()) self.search_input = search_completion.node.name.chars().collect();
} else {
None
} }
})
.unwrap_or_default();
self.completion_preview = None;
self.input_position = self.search_input.len(); self.input_position = self.search_input.len();
self.completion_preview = None;
SearchAction::Update SearchAction::Update
} else { } else {
SearchAction::None SearchAction::None
} }
} }
}
pub fn clear_search(&mut self) { pub fn clear_search(&mut self) {
self.search_input.clear(); self.search_input.clear();