1use 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
47pub const SURFACE: &str = "treeFilter";
50
51pub 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
84fn 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#[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 pub fn is_empty(&self) -> bool {
105 self.words.is_empty()
106 }
107
108 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 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#[derive(Debug)]
142pub struct FilterField {
143 id: String,
144 hint: Option<String>,
145}
146
147impl FilterField {
148 pub fn new(tree: impl Into<String>) -> Self {
150 Self {
151 id: tree.into(),
152 hint: None,
153 }
154 }
155
156 pub fn hint(mut self, hint: impl Into<String>) -> Self {
158 self.hint = Some(hint.into());
159 self
160 }
161
162 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 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
221pub(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 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#[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
269pub(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
278pub 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
290pub(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
333pub 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 assert_eq!(Query::new("i").positions("İi"), [0, 1]);
368 }
369}