Skip to main content

egui_selectable_table/
fuzzy_matcher.rs

1use nucleo_matcher::pattern::{CaseMatching, Normalization, Pattern};
2use nucleo_matcher::{Matcher, Utf32Str};
3use std::hash::Hash;
4
5use crate::{ColumnOperations, ColumnOrdering, SelectableRow, SelectableTable};
6
7impl<Row, F, Conf> SelectableTable<Row, F, Conf>
8where
9    Row: Clone + Send + Sync,
10    F: Eq
11        + Hash
12        + Clone
13        + Ord
14        + Send
15        + Sync
16        + Default
17        + ColumnOperations<Row, F, Conf>
18        + ColumnOrdering<Row>,
19    Conf: Default,
20{
21    /// Performs a fuzzy search using specified columns across all rows and updates the displayed rows.
22    ///
23    /// This function filters the table rows based on a search `query` using `nucleo-matcher`
24    /// crate.
25    /// It checks the specified `column_list` for each row, concatenates their string representations,
26    /// and scores them using the provided or generated `Pattern`. Only rows with a non-`None` score
27    /// are retained.
28    ///
29    /// If a `limit` is provided, it will result at most `limit` rows.
30    ///
31    /// # Parameters:
32    /// - `column_list`: A list of columns to search across. Does nothing if empty.
33    /// - `query`: The search string. Does nothing if empty.
34    /// - `limit`: Optional limit on the number of results returned. Does nothing if `0`. Defaults
35    ///   to no limit
36    /// - `pattern`: Optional precomputed fuzzy `Pattern`. Default pattern is created from the query using
37    ///   case-insensitive matching and smart normalization.
38    ///
39    /// The search is relatively fast even with a million rows but it should not be called every
40    /// frame and be used sparingly.
41    ///
42    /// To reset search results, call [`recreate_rows`](SelectableTable::recreate_rows).
43    ///
44    /// # Example:
45    /// ```rust,ignore
46    /// table.search_and_show(&vec![Column::Name, Column::Username], "john", Some(10), None);
47    /// ```
48    pub fn search_and_show(
49        &mut self,
50        column_list: &Vec<F>,
51        query: &str,
52        limit: Option<usize>,
53        pattern: Option<Pattern>,
54    ) {
55        if query.is_empty() {
56            return;
57        }
58
59        if column_list.is_empty() {
60            return;
61        }
62
63        if let Some(limit) = limit
64            && limit == 0
65        {
66            return;
67        }
68
69        let pattern = pattern
70            .unwrap_or_else(|| Pattern::parse(query, CaseMatching::Ignore, Normalization::Smart));
71
72        let mut buf = Vec::new();
73        let mut row_data: Vec<SelectableRow<Row, F>> = Vec::new();
74
75        for val in self.rows.values() {
76            let mut string_val = String::new();
77
78            for column in column_list {
79                let value = column.column_text(&val.row_data);
80                string_val.push_str(&value);
81                string_val.push(' ');
82            }
83
84            if pattern
85                .score(Utf32Str::new(&string_val, &mut buf), &mut self.matcher)
86                .is_some()
87            {
88                row_data.push(val.clone());
89
90                if let Some(max) = limit
91                    && row_data.len() >= max
92                {
93                    break;
94                }
95            }
96        }
97
98        self.formatted_rows.clear();
99        self.active_rows.clear();
100        self.active_columns.clear();
101
102        self.sort_and_index(&mut row_data);
103
104        self.formatted_rows = row_data;
105    }
106
107    /// Sets a custom matcher to use for fuzzy searching rows
108    ///
109    /// This allows the table to use a custom `Matcher` from `nucleo-matcher` crate
110    /// for searching/filtering through rows based on the input text. Use this to change
111    /// the search algorithm or tweak scoring behavior.
112    ///
113    /// # Parameters:
114    /// - `matcher`: The matcher instance to use for row filtering.
115    ///
116    /// # Returns:
117    /// - `Self`: The modified table with the specified matcher applied.
118    ///
119    /// # Example:
120    /// ```rust,ignore
121    /// let matcher = Matcher::default();
122    /// let table = SelectableTable::new(columns)
123    ///     .matcher(matcher);
124    /// ```
125    #[must_use]
126    pub fn matcher(mut self, matcher: Matcher) -> Self {
127        self.matcher = matcher;
128        self
129    }
130
131    /// Replaces the current matcher with a new one.
132    ///
133    /// This method allows updating the fuzzy search matcher dynamically.
134    ///
135    /// # Parameters:
136    /// - `matcher`: The new matcher instance to set.
137    ///
138    /// # Example:
139    /// ```rust,ignore
140    /// table.set_matcher(new_matcher);
141    /// ```
142    pub fn set_matcher(&mut self, matcher: Matcher) {
143        self.matcher = matcher;
144    }
145}