Skip to main content

egui_pop_views/tree/
filter.rs

1//! A tree's filter: the query, how a node matches it, and the field that
2//! types it ([`FilterField`]).
3//!
4//! **Matching**: the query is cut into words at spaces; a node matches
5//! when every word is somewhere in its match text
6//! ([`TreeSource::match_text`](super::TreeSource::match_text): its plain
7//! name, plus the words its source adds), as a substring, ignoring case
8//! and the accents of Latin letters (`ecran` finds `Écran`). Substrings
9//! rather than a fuzzy subsequence (the command palette's): a filter
10//! hides what does not match, and a few letters in order are found in
11//! almost any long description, so a fuzzy filter would hide nothing.
12//! Substrings rather than word starts: `board` finds `keyboard`. This is
13//! VS Code's "contiguous" find mode for trees, with several words.
14//!
15//! **Showing**: while the query is not empty, the nodes that match show
16//! with their ancestors, which open without touching the fold the tree
17//! keeps (opening or closing a branch meanwhile lasts until the query
18//! changes, and runs no `tree.expand`); a branch that matches opens onto
19//! all of its children. The rest is hidden; nothing left shows a "No
20//! match" row. Only the nodes loaded are searched: a lazy branch never
21//! opened is not asked for.
22//!
23//! ```
24//! use egui_pop_views::tree::filter::Query;
25//!
26//! let q = Query::new("ecran lum");
27//! assert!(q.matches("Écran et luminosité"));
28//! assert!(!q.matches("Écran"));
29//! assert_eq!(q.positions("Écran"), [0, 1, 2, 3, 4]);
30//! ```
31
32use std::collections::BTreeMap;
33use std::sync::{Arc, Mutex};
34
35use egui::text::LayoutJob;
36use egui::{
37    Color32, Context, FontId, Id, Key as EguiKey, Response, Role, Stroke, TextEdit, TextFormat, Ui,
38};
39use egui_pop_core::strings::{tr, tr_with};
40use egui_pop_core::{a11y, focus, lock};
41use serde_json::{Value as Json, json};
42
43use super::{Row, TreeState};
44use crate::select::Key;
45use crate::strings as s;
46
47/// The focus surface of a tree drawn with a filter field: its keys
48/// (`tree.filter`'s Ctrl+F and `/`) are bound there (`treeFilterFocus`).
49pub const SURFACE: &str = "treeFilter";
50
51/// A character as the filter compares it: lower case, a Latin letter
52/// without its accent. One character for one, so that positions in the
53/// folded text are positions in the text.
54pub fn fold(c: char) -> char {
55    let c = c.to_lowercase().next().unwrap_or(c);
56    match c {
57        'à'..='å' | 'ā' | 'ă' | 'ą' => 'a',
58        'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => 'c',
59        'ď' | 'đ' => 'd',
60        'è'..='ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',
61        'ĝ' | 'ğ' | 'ġ' | 'ģ' => 'g',
62        'ĥ' | 'ħ' => 'h',
63        'ì'..='ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' | 'ı' => 'i',
64        'ĵ' => 'j',
65        'ķ' => 'k',
66        'ĺ' | 'ļ' | 'ľ' | 'ŀ' | 'ł' => 'l',
67        'ñ' | 'ń' | 'ņ' | 'ň' => 'n',
68        'ò'..='ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o',
69        'ŕ' | 'ŗ' | 'ř' => 'r',
70        'ś' | 'ŝ' | 'ş' | 'š' => 's',
71        'ţ' | 'ť' | 'ŧ' => 't',
72        'ù'..='ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u',
73        'ŵ' => 'w',
74        'ý' | 'ÿ' | 'ŷ' => 'y',
75        'ź' | 'ż' | 'ž' => 'z',
76        c => c,
77    }
78}
79
80fn folded(text: &str) -> Vec<char> {
81    text.chars().map(fold).collect()
82}
83
84/// Where `word` starts in `text`, every time.
85fn occurrences<'a>(text: &'a [char], word: &'a [char]) -> impl Iterator<Item = usize> + 'a {
86    let last = (text.len() + 1).saturating_sub(word.len());
87    (0..last).filter(move |&i| text[i..i + word.len()] == *word)
88}
89
90/// A filter's query: its words, folded.
91#[derive(Clone, Debug, Default, PartialEq, Eq)]
92pub struct Query {
93    words: Vec<Vec<char>>,
94}
95
96impl Query {
97    pub fn new(text: &str) -> Self {
98        Self {
99            words: text.split_whitespace().map(folded).collect(),
100        }
101    }
102
103    /// No words: everything shows.
104    pub fn is_empty(&self) -> bool {
105        self.words.is_empty()
106    }
107
108    /// Whether every word is in `text`.
109    pub fn matches(&self, text: &str) -> bool {
110        let t = folded(text);
111        self.words
112            .iter()
113            .all(|w| occurrences(&t, w).next().is_some())
114    }
115
116    /// The characters of `text` (indices in `char`s, ascending) that a
117    /// word covers, wherever it is: what a row highlights.
118    pub fn positions(&self, text: &str) -> Vec<usize> {
119        let t = folded(text);
120        let mut hit = vec![false; t.len()];
121        for w in &self.words {
122            for at in occurrences(&t, w) {
123                hit[at..at + w.len()].iter_mut().for_each(|h| *h = true);
124            }
125        }
126        (0..t.len()).filter(|&i| hit[i]).collect()
127    }
128}
129
130/// The field typing a tree's filter, drawn above the tree (or anywhere
131/// near it) with the tree's state.
132///
133/// - Its text is the tree's filter ([`TreeState::set_filter`]); beside
134///   it, while it filters, how many nodes match of how many are loaded
135///   ("3 of 57"), which is also announced to screen readers.
136/// - Ctrl+F or `/` in the tree comes here: the `tree.filter` command,
137///   bound on the tree's [`SURFACE`] by [`ViewsPlugin`](crate::ViewsPlugin)
138///   (rebindable in the keymap; that plugin must be connected).
139/// - Escape clears the text, then a second one gives the focus back to
140///   the tree; Down goes to the tree, its cursor on the first match.
141#[derive(Debug)]
142pub struct FilterField {
143    id: String,
144    hint: Option<String>,
145}
146
147impl FilterField {
148    /// The field of the tree named `tree` (its [`TreeView`](super::TreeView)'s id).
149    pub fn new(tree: impl Into<String>) -> Self {
150        Self {
151            id: tree.into(),
152            hint: None,
153        }
154    }
155
156    /// Its placeholder and accessible name (default: "Filter").
157    pub fn hint(mut self, hint: impl Into<String>) -> Self {
158        self.hint = Some(hint.into());
159        self
160    }
161
162    /// Draws the field; the tree shows the filter from its next draw.
163    pub fn show<K: Key>(self, ui: &mut Ui, state: &mut TreeState<K>) -> Response {
164        let id = Id::unique(("egui_pop_views::tree_filter", &self.id));
165        state.field = Some(id);
166        let ctx = ui.ctx().clone();
167        let hint = self.hint.unwrap_or_else(|| tr(&ctx, &s::TREE_FILTER));
168        let count = state.filter_count();
169        // One line high, the count at the right end.
170        let size = egui::vec2(ui.available_width(), ui.spacing().interact_size.y);
171        let layout = egui::Layout::right_to_left(egui::Align::Center);
172        ui.allocate_ui_with_layout(size, layout, |ui| {
173            match count {
174                Some((0, _)) => {
175                    ui.weak(tr(&ctx, &s::TREE_FILTER_NONE));
176                }
177                Some((n, total)) => {
178                    ui.weak(tr_with(
179                        &ctx,
180                        &s::TREE_FILTER_COUNT,
181                        &[("count", n.into()), ("total", total.into())],
182                    ));
183                }
184                None => {}
185            }
186            let mut text = state.filter().to_string();
187            let edit = ui.add(
188                TextEdit::singleline(&mut text)
189                    .id(id)
190                    .hint_text(&hint)
191                    .desired_width(ui.available_width()),
192            );
193            a11y::name(&edit, Role::SearchInput, &hint);
194            if std::mem::take(&mut state.field_focus) {
195                edit.request_focus();
196            }
197            if edit.changed() {
198                state.set_filter(text);
199                ctx.request_repaint();
200            }
201            let escaped = focus::escape_left(&ctx, id)
202                || (edit.lost_focus() && ui.input(|i| i.key_pressed(EguiKey::Escape)));
203            if escaped {
204                if state.filter().is_empty() {
205                    state.focus_tree = true;
206                } else {
207                    state.set_filter("");
208                    edit.request_focus();
209                }
210                ctx.request_repaint();
211            } else if edit.has_focus() && ui.input(|i| i.key_pressed(EguiKey::ArrowDown)) {
212                state.focus_tree = true;
213                ctx.request_repaint();
214            }
215            edit
216        })
217        .inner
218    }
219}
220
221/// A label with the characters at `hits` in `strong`, underlined.
222pub(crate) fn highlighted(
223    label: &str,
224    hits: &[usize],
225    font: FontId,
226    normal: Color32,
227    strong: Color32,
228) -> LayoutJob {
229    let mut job = LayoutJob::default();
230    let format = |hit: bool| TextFormat {
231        font_id: font.clone(),
232        color: if hit { strong } else { normal },
233        underline: if hit {
234            Stroke::new(1.0, strong)
235        } else {
236            Stroke::NONE
237        },
238        ..TextFormat::default()
239    };
240    // In runs of the same format.
241    let mut run = String::new();
242    let mut run_hit = false;
243    for (i, c) in label.chars().enumerate() {
244        let hit = hits.binary_search(&i).is_ok();
245        if hit != run_hit && !run.is_empty() {
246            job.append(&std::mem::take(&mut run), 0.0, format(run_hit));
247        }
248        run_hit = hit;
249        run.push(c);
250    }
251    if !run.is_empty() {
252        job.append(&run, 0.0, format(run_hit));
253    }
254    job
255}
256
257fn request_id() -> Id {
258    Id::unique("egui_pop_views::tree_filter::request")
259}
260
261/// Asks the focused tree's filter field for the focus (`tree.filter`).
262#[cfg(feature = "api")]
263pub(crate) fn request(ctx: &Context) {
264    let now = ctx.cumulative_pass_nr();
265    ctx.data_mut(|d| d.insert_temp(request_id(), now));
266    ctx.request_repaint();
267}
268
269/// Whether the field was asked for, this pass or the last; spent once.
270pub(crate) fn take_request(ctx: &Context) -> bool {
271    let now = ctx.cumulative_pass_nr();
272    ctx.data_mut(|d| {
273        d.remove_temp::<u64>(request_id())
274            .is_some_and(|at| at + 1 >= now)
275    })
276}
277
278/// How many rows a tree reports to agents at most.
279pub const REPORTED_ROWS: usize = 200;
280
281type Reports = Arc<Mutex<BTreeMap<String, Json>>>;
282
283fn reports(ctx: &Context) -> Reports {
284    ctx.data_mut(|d| {
285        d.get_temp_mut_or_default::<Reports>(Id::unique("egui_pop_views::trees"))
286            .clone()
287    })
288}
289
290/// Reports a tree to agents when its rows changed since the last time.
291pub(crate) fn report<K: Key>(ctx: &Context, tree: &str, state: &mut TreeState<K>) {
292    let at = state.model.flattens();
293    if state.reported == Some(at) {
294        return;
295    }
296    state.reported = Some(at);
297    let model = &state.model;
298    let rows = model.rows_now();
299    let shown: Vec<Json> = rows
300        .iter()
301        .take(REPORTED_ROWS)
302        .map(|r| match r {
303            Row::Node { key, depth } => {
304                let label = model.node(key).map_or("", |n| n.label.as_str());
305                let mut row = json!({ "key": key, "label": label, "depth": depth });
306                if model.is_filtered() {
307                    row["match"] = json!(model.is_match(key));
308                }
309                if model.node(key).is_some_and(|n| n.branch) {
310                    row["open"] = json!(model.is_open(key));
311                }
312                row
313            }
314            Row::Loading { depth, .. } => json!({ "row": "loading", "depth": depth }),
315            Row::Failed { depth, reason, .. } => {
316                json!({ "row": "failed", "depth": depth, "reason": reason })
317            }
318            Row::Empty { depth, .. } => json!({ "row": "empty", "depth": depth }),
319        })
320        .collect();
321    let report = json!({
322        "filter": state.filter(),
323        "matches": model.matches(),
324        "nodes": model.len(),
325        "rows": rows.len(),
326        "no_match": rows.is_empty() && model.is_filtered(),
327        "shown": shown,
328        "field": state.field.is_some(),
329    });
330    lock(&reports(ctx)).insert(tree.to_string(), report);
331}
332
333/// The trees drawn so far, by id, as last reported: the filter, how many
334/// nodes match it (`null`: none set) of how many are loaded, and the rows
335/// shown (the first [`REPORTED_ROWS`]: key, label, depth, whether it
336/// matches, whether a branch is open). The `trees` debug collector of
337/// [`ViewsPlugin`](crate::ViewsPlugin).
338pub fn drawn(ctx: &Context) -> Json {
339    Json::Object(
340        lock(&reports(ctx))
341            .iter()
342            .map(|(k, v)| (k.clone(), v.clone()))
343            .collect(),
344    )
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    #[test]
352    fn every_word_is_a_substring_ignoring_case_and_accents() {
353        let q = Query::new("  BOARD  ecr ");
354        assert!(q.matches("Keyboard: the écran"));
355        assert!(!q.matches("Keyboard"));
356        assert!(Query::new("").is_empty());
357        assert!(Query::new("Œuvre").matches("œuvre"));
358        assert!(Query::new("zurich").matches("Zürich"));
359    }
360
361    #[test]
362    fn positions_cover_every_occurrence_of_every_word() {
363        let q = Query::new("an é");
364        assert_eq!(q.positions("Anne et Jean"), [0, 1, 3, 5, 9, 10, 11]);
365        assert!(Query::new("x").positions("abc").is_empty());
366        // Folding keeps one character for one.
367        assert_eq!(Query::new("i").positions("İi"), [0, 1]);
368    }
369}