Skip to main content

fc_ui/capabilities/navigation/
tree.rs

1//! Tree navigation component with hierarchical data support.
2
3use crate::capabilities::foundation::theme::use_theme;
4use crate::capabilities::primitives::icon::Icon;
5use crate::capabilities::primitives::icon_source::IconSource;
6use gpui::{prelude::*, *};
7use std::collections::{HashMap, HashSet};
8use std::hash::Hash;
9use std::rc::Rc;
10use std::sync::Arc;
11
12#[derive(Clone)]
13pub struct TreeNode<T: Clone> {
14    pub id: T,
15    pub label: SharedString,
16    pub children: Vec<TreeNode<T>>,
17    pub icon: Option<IconSource>,
18    pub icon_color: Option<Hsla>,
19    pub disabled: bool,
20    pub has_lazy_children: bool,
21}
22
23impl<T: Clone> TreeNode<T> {
24    pub fn new(id: T, label: impl Into<SharedString>) -> Self {
25        Self {
26            id,
27            label: label.into(),
28            children: Vec::new(),
29            icon: None,
30            icon_color: None,
31            disabled: false,
32            has_lazy_children: false,
33        }
34    }
35
36    pub fn with_icon(mut self, icon: impl Into<IconSource>) -> Self {
37        self.icon = Some(icon.into());
38        self
39    }
40
41    pub fn with_icon_color(mut self, color: Hsla) -> Self {
42        self.icon_color = Some(color);
43        self
44    }
45
46    pub fn with_children(mut self, children: Vec<TreeNode<T>>) -> Self {
47        self.children = children;
48        self
49    }
50
51    pub fn disabled(mut self, disabled: bool) -> Self {
52        self.disabled = disabled;
53        self
54    }
55
56    pub fn with_lazy_children(mut self, has_lazy: bool) -> Self {
57        self.has_lazy_children = has_lazy;
58        self
59    }
60}
61
62#[derive(Clone)]
63struct FlatTreeNode<T: Clone> {
64    node: TreeNode<T>,
65    level: usize,
66    node_id: T,
67}
68
69#[derive(Clone)]
70struct FilteredNode<T: Clone> {
71    node: TreeNode<T>,
72    match_ranges: Vec<(usize, usize)>,
73    children: Vec<FilteredNode<T>>,
74}
75
76fn filter_tree<T: Clone>(nodes: &[TreeNode<T>], filter: &str) -> Vec<FilteredNode<T>> {
77    if filter.is_empty() {
78        return nodes
79            .iter()
80            .map(|node| FilteredNode {
81                node: node.clone(),
82                match_ranges: Vec::new(),
83                children: filter_tree(&node.children, filter),
84            })
85            .collect();
86    }
87
88    let mut filtered = Vec::new();
89
90    for node in nodes {
91        let (matches, match_ranges) = find_matches(&node.label, filter);
92
93        let filtered_children = filter_tree(&node.children, filter);
94        if matches || !filtered_children.is_empty() {
95            filtered.push(FilteredNode {
96                node: node.clone(),
97                match_ranges,
98                children: filtered_children,
99            });
100        }
101    }
102
103    filtered
104}
105
106/// Match ranges are char indices into `text`, so they can be applied directly
107/// to the original label when rendering highlights.
108fn find_matches(text: &str, filter: &str) -> (bool, Vec<(usize, usize)>) {
109    if filter.is_empty() {
110        return (false, Vec::new());
111    }
112
113    let text_chars: Vec<char> = text.chars().collect();
114    let filter_chars: Vec<char> = filter.chars().collect();
115
116    let mut match_ranges = Vec::new();
117    if filter_chars.len() <= text_chars.len() {
118        for start in 0..=(text_chars.len() - filter_chars.len()) {
119            if filter_chars
120                .iter()
121                .enumerate()
122                .all(|(i, &f)| chars_match_ci(text_chars[start + i], f))
123            {
124                match_ranges.push((start, start + filter_chars.len()));
125            }
126        }
127    }
128
129    if !match_ranges.is_empty() {
130        return (true, match_ranges);
131    }
132
133    let mut filter_idx = 0;
134    let mut current_match_start = None;
135    let mut fuzzy_ranges = Vec::new();
136
137    for (text_idx, &text_char) in text_chars.iter().enumerate() {
138        if filter_idx < filter_chars.len() && chars_match_ci(text_char, filter_chars[filter_idx]) {
139            if current_match_start.is_none() {
140                current_match_start = Some(text_idx);
141            }
142            filter_idx += 1;
143
144            if filter_idx == filter_chars.len() {
145                if let Some(start) = current_match_start {
146                    fuzzy_ranges.push((start, text_idx + 1));
147                }
148                return (true, fuzzy_ranges);
149            }
150        }
151    }
152
153    (false, Vec::new())
154}
155
156fn chars_match_ci(a: char, b: char) -> bool {
157    a == b || a.to_lowercase().eq(b.to_lowercase())
158}
159
160fn flatten_filtered_tree<T: Clone + PartialEq + Eq + Hash>(
161    filtered_nodes: &[FilteredNode<T>],
162    expanded_ids: &HashSet<T>,
163    level: usize,
164    auto_expand_matches: bool,
165) -> Vec<(FlatTreeNode<T>, Vec<(usize, usize)>)> {
166    let mut flat = Vec::new();
167
168    for filtered_node in filtered_nodes {
169        flat.push((
170            FlatTreeNode {
171                node: filtered_node.node.clone(),
172                level,
173                node_id: filtered_node.node.id.clone(),
174            },
175            filtered_node.match_ranges.clone(),
176        ));
177
178        let should_expand = expanded_ids.contains(&filtered_node.node.id)
179            || (auto_expand_matches && !filtered_node.children.is_empty());
180
181        if should_expand {
182            let children = flatten_filtered_tree(
183                &filtered_node.children,
184                expanded_ids,
185                level + 1,
186                auto_expand_matches,
187            );
188            flat.extend(children);
189        }
190    }
191
192    flat
193}
194
195fn flatten_tree<T: Clone + PartialEq + Eq + Hash>(
196    nodes: &[TreeNode<T>],
197    expanded_ids: &HashSet<T>,
198    level: usize,
199) -> Vec<FlatTreeNode<T>> {
200    let mut flat = Vec::new();
201
202    for node in nodes {
203        flat.push(FlatTreeNode {
204            node: node.clone(),
205            level,
206            node_id: node.id.clone(),
207        });
208
209        if !node.children.is_empty() && expanded_ids.contains(&node.id) {
210            let children = flatten_tree(&node.children, expanded_ids, level + 1);
211            flat.extend(children);
212        }
213    }
214
215    flat
216}
217
218const ROW_HEIGHT: f32 = 32.0;
219
220#[derive(IntoElement)]
221pub struct TreeList<T: Clone + PartialEq + Eq + Hash + 'static> {
222    nodes: Vec<TreeNode<T>>,
223    selected_id: Option<T>,
224    expanded_ids: Vec<T>,
225    filter: Option<String>,
226    auto_expand_matches: bool,
227    highlight_matches: bool,
228    on_select: Option<Arc<dyn Fn(&T, &mut Window, &mut App) + Send + Sync + 'static>>,
229    on_toggle: Option<Arc<dyn Fn(&T, bool, &mut Window, &mut App) + Send + Sync + 'static>>,
230    on_right_click:
231        Option<Arc<dyn Fn(&T, &MouseDownEvent, &mut Window, &mut App) + Send + Sync + 'static>>,
232    style: StyleRefinement,
233}
234
235impl<T: Clone + PartialEq + Eq + Hash + 'static> Default for TreeList<T> {
236    fn default() -> Self {
237        Self::new()
238    }
239}
240
241impl<T: Clone + PartialEq + Eq + Hash + 'static> TreeList<T> {
242    pub fn new() -> Self {
243        Self {
244            nodes: Vec::new(),
245            selected_id: None,
246            expanded_ids: Vec::new(),
247            filter: None,
248            auto_expand_matches: false,
249            highlight_matches: true,
250            on_select: None,
251            on_toggle: None,
252            on_right_click: None,
253            style: StyleRefinement::default(),
254        }
255    }
256
257    pub fn nodes(mut self, nodes: Vec<TreeNode<T>>) -> Self {
258        self.nodes = nodes;
259        self
260    }
261
262    pub fn selected_id(mut self, id: T) -> Self {
263        self.selected_id = Some(id);
264        self
265    }
266
267    pub fn expanded_ids(mut self, ids: Vec<T>) -> Self {
268        self.expanded_ids = ids;
269        self
270    }
271
272    pub fn filter(mut self, filter: impl Into<String>) -> Self {
273        let filter_str = filter.into();
274        self.filter = if filter_str.is_empty() {
275            None
276        } else {
277            Some(filter_str)
278        };
279        self
280    }
281
282    pub fn auto_expand_matches(mut self, auto_expand: bool) -> Self {
283        self.auto_expand_matches = auto_expand;
284        self
285    }
286
287    pub fn highlight_matches(mut self, highlight: bool) -> Self {
288        self.highlight_matches = highlight;
289        self
290    }
291
292    pub fn on_select<F>(mut self, f: F) -> Self
293    where
294        F: Fn(&T, &mut Window, &mut App) + Send + Sync + 'static,
295    {
296        self.on_select = Some(Arc::new(f));
297        self
298    }
299
300    pub fn on_toggle<F>(mut self, f: F) -> Self
301    where
302        F: Fn(&T, bool, &mut Window, &mut App) + Send + Sync + 'static,
303    {
304        self.on_toggle = Some(Arc::new(f));
305        self
306    }
307
308    pub fn on_right_click<F>(mut self, f: F) -> Self
309    where
310        F: Fn(&T, &MouseDownEvent, &mut Window, &mut App) + Send + Sync + 'static,
311    {
312        self.on_right_click = Some(Arc::new(f));
313        self
314    }
315
316    fn render_highlighted_text(
317        &self,
318        text: &str,
319        match_ranges: &[(usize, usize)],
320        theme: &crate::capabilities::foundation::theme::Theme,
321        is_selected: bool,
322    ) -> impl IntoElement {
323        if match_ranges.is_empty() || !self.highlight_matches {
324            return div().child(text.to_string()).into_any_element();
325        }
326
327        let mut parts = Vec::new();
328        let mut last_end = 0;
329        let text_chars: Vec<char> = text.chars().collect();
330
331        let mut sorted_ranges = match_ranges.to_vec();
332        sorted_ranges.sort_by_key(|r| r.0);
333
334        for (start, end) in sorted_ranges {
335            if last_end < start {
336                let part: String = text_chars[last_end..start].iter().collect();
337                parts.push((part, false));
338            }
339
340            let highlighted: String = text_chars[start..end.min(text_chars.len())]
341                .iter()
342                .collect();
343            parts.push((highlighted, true));
344            last_end = end.min(text_chars.len());
345        }
346
347        if last_end < text_chars.len() {
348            let part: String = text_chars[last_end..].iter().collect();
349            parts.push((part, false));
350        }
351
352        div()
353            .flex()
354            .children(parts.into_iter().map(|(text, is_match)| {
355                if is_match {
356                    div()
357                        .bg(if is_selected {
358                            theme.tokens.accent_foreground.opacity(0.3)
359                        } else {
360                            theme.tokens.accent.opacity(0.3)
361                        })
362                        .rounded_sm()
363                        .px(px(1.0))
364                        .child(text)
365                        .into_any_element()
366                } else {
367                    div().child(text).into_any_element()
368                }
369            }))
370            .into_any_element()
371    }
372}
373
374impl<T: Clone + PartialEq + Eq + Hash + 'static> Styled for TreeList<T> {
375    fn style(&mut self) -> &mut StyleRefinement {
376        &mut self.style
377    }
378}
379
380impl<T: Clone + PartialEq + Eq + Hash + 'static> RenderOnce for TreeList<T> {
381    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
382        let theme = use_theme(cx);
383
384        let expanded_set: HashSet<T> = self.expanded_ids.iter().cloned().collect();
385
386        let (flat_nodes, match_ranges_map): (
387            Vec<FlatTreeNode<T>>,
388            HashMap<T, Vec<(usize, usize)>>,
389        ) = if let Some(ref filter) = self.filter {
390            let filtered = filter_tree(&self.nodes, filter);
391            let flat_with_ranges =
392                flatten_filtered_tree(&filtered, &expanded_set, 0, self.auto_expand_matches);
393
394            let mut nodes = Vec::new();
395            let mut ranges_map = HashMap::new();
396
397            for (node, ranges) in flat_with_ranges {
398                ranges_map.insert(node.node_id.clone(), ranges);
399                nodes.push(node);
400            }
401
402            (nodes, ranges_map)
403        } else {
404            (flatten_tree(&self.nodes, &expanded_set, 0), HashMap::new())
405        };
406
407        let total_items = flat_nodes.len();
408
409        let _item_sizes: Rc<Vec<Size<Pixels>>> = Rc::new(
410            (0..total_items)
411                .map(|_| Size {
412                    width: px(0.), // Width will be determined by container
413                    height: px(ROW_HEIGHT),
414                })
415                .collect(),
416        );
417
418        let flat_nodes_rc = Rc::new(flat_nodes);
419        let match_ranges_rc = Rc::new(match_ranges_map);
420        let selected_id = self.selected_id.clone();
421        let expanded_ids_rc = Rc::new(expanded_set);
422        let on_select = self.on_select.clone();
423        let on_toggle = self.on_toggle.clone();
424        let on_right_click = self.on_right_click.clone();
425        let highlight_matches = self.highlight_matches;
426        let user_style = self.style.clone();
427
428        div()
429            .flex()
430            .flex_col()
431            .w_full()
432            .bg(theme.tokens.background)
433            .map(|mut this| {
434                this.style().refine(&user_style);
435                this
436            })
437            .child(
438                div()
439                    .w_full()
440                    .children(flat_nodes_rc.iter().map(|flat_node| {
441                        let is_selected = selected_id.as_ref() == Some(&flat_node.node_id);
442                        let is_expanded = expanded_ids_rc.contains(&flat_node.node_id);
443                        let has_children =
444                            !flat_node.node.children.is_empty() || flat_node.node.has_lazy_children;
445                        let indent = px((flat_node.level as f32) * 16.0);
446
447                        div()
448                            .w_full()
449                            .h(px(ROW_HEIGHT))
450                            .flex()
451                            .items_center()
452                            .px(px(8.0))
453                            .pl(indent + px(8.0))
454                            .cursor(if flat_node.node.disabled {
455                                CursorStyle::Arrow
456                            } else {
457                                CursorStyle::PointingHand
458                            })
459                            .bg(if is_selected {
460                                theme.tokens.accent
461                            } else {
462                                gpui::transparent_black()
463                            })
464                            .text_color(if is_selected {
465                                theme.tokens.accent_foreground
466                            } else if flat_node.node.disabled {
467                                theme.tokens.muted_foreground
468                            } else {
469                                theme.tokens.primary
470                            })
471                            .when(!flat_node.node.disabled && !is_selected, |div| {
472                                div.hover(|mut style| {
473                                    style.background =
474                                        Some(theme.tokens.accent.opacity(0.5).into());
475                                    style
476                                })
477                            })
478                            .when(!flat_node.node.disabled, {
479                                let on_select = on_select.clone();
480                                let on_toggle = on_toggle.clone();
481                                let node_id = flat_node.node_id.clone();
482
483                                move |this| {
484                                    this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
485                                        if let Some(on_select) = on_select.clone() {
486                                            on_select(&node_id, window, cx);
487                                        }
488
489                                        if has_children {
490                                            if let Some(on_toggle) = on_toggle.clone() {
491                                                on_toggle(&node_id, !is_expanded, window, cx);
492                                            }
493                                        }
494                                    })
495                                }
496                            })
497                            .when(!flat_node.node.disabled, {
498                                let on_right_click = on_right_click.clone();
499                                let node_id = flat_node.node_id.clone();
500
501                                move |this| {
502                                    this.on_mouse_down(
503                                        MouseButton::Right,
504                                        move |event, window, cx| {
505                                            if let Some(on_right_click) = on_right_click.clone() {
506                                                on_right_click(&node_id, event, window, cx);
507                                            }
508                                        },
509                                    )
510                                }
511                            })
512                            .child(
513                                div()
514                                    .flex()
515                                    .items_center()
516                                    .gap(px(8.0))
517                                    .children(flat_node.node.icon.as_ref().map(|icon| {
518                                        Icon::new(icon.clone()).size(px(16.0)).color(
519                                            if is_selected {
520                                                theme.tokens.accent_foreground
521                                            } else if flat_node.node.disabled {
522                                                theme.tokens.muted_foreground
523                                            } else {
524                                                theme.tokens.primary
525                                            },
526                                        )
527                                    }))
528                                    .child(
529                                        div()
530                                            .flex_1()
531                                            .text_size(px(14.0))
532                                            .font_family(theme.tokens.font_family.clone())
533                                            .font_weight(if is_selected {
534                                                FontWeight::SEMIBOLD
535                                            } else {
536                                                FontWeight::NORMAL
537                                            })
538                                            .child({
539                                                let ranges = match_ranges_rc
540                                                    .get(&flat_node.node_id)
541                                                    .map(|r| r.as_slice())
542                                                    .unwrap_or(&[]);
543
544                                                if !ranges.is_empty() && highlight_matches {
545                                                    self.render_highlighted_text(
546                                                        &flat_node.node.label,
547                                                        ranges,
548                                                        &theme,
549                                                        is_selected,
550                                                    )
551                                                    .into_any_element()
552                                                } else {
553                                                    div()
554                                                        .child(flat_node.node.label.clone())
555                                                        .into_any_element()
556                                                }
557                                            }),
558                                    )
559                                    .children(if has_children {
560                                        Some(
561                                            div()
562                                                .w(px(16.0))
563                                                .h(px(16.0))
564                                                .flex()
565                                                .items_center()
566                                                .justify_center()
567                                                .child(
568                                                    Icon::new(if is_expanded {
569                                                        "arrow-down"
570                                                    } else {
571                                                        "arrow-right"
572                                                    })
573                                                    .size(px(12.0))
574                                                    .color(theme.tokens.primary),
575                                                ),
576                                        )
577                                    } else {
578                                        None
579                                    }),
580                            )
581                    })),
582            )
583    }
584}
585
586#[derive(Clone)]
587pub struct ListItem<T: Clone> {
588    pub id: T,
589    pub label: SharedString,
590    pub icon: Option<IconSource>,
591    pub badge: Option<SharedString>,
592    pub disabled: bool,
593}
594
595impl<T: Clone> ListItem<T> {
596    pub fn new(id: T, label: impl Into<SharedString>) -> Self {
597        Self {
598            id,
599            label: label.into(),
600            icon: None,
601            badge: None,
602            disabled: false,
603        }
604    }
605
606    pub fn with_icon(mut self, icon: impl Into<IconSource>) -> Self {
607        self.icon = Some(icon.into());
608        self
609    }
610
611    pub fn with_badge(mut self, badge: impl Into<SharedString>) -> Self {
612        self.badge = Some(badge.into());
613        self
614    }
615
616    pub fn disabled(mut self, disabled: bool) -> Self {
617        self.disabled = disabled;
618        self
619    }
620}
621
622#[derive(IntoElement)]
623pub struct List<T: Clone + PartialEq + 'static> {
624    items: Vec<ListItem<T>>,
625    selected_id: Option<T>,
626    on_select: Option<Arc<dyn Fn(&T, &mut Window, &mut App) + Send + Sync + 'static>>,
627}
628
629impl<T: Clone + PartialEq + 'static> Default for List<T> {
630    fn default() -> Self {
631        Self::new()
632    }
633}
634
635impl<T: Clone + PartialEq + 'static> List<T> {
636    pub fn new() -> Self {
637        Self {
638            items: Vec::new(),
639            selected_id: None,
640            on_select: None,
641        }
642    }
643
644    pub fn items(mut self, items: Vec<ListItem<T>>) -> Self {
645        self.items = items;
646        self
647    }
648
649    pub fn selected_id(mut self, id: T) -> Self {
650        self.selected_id = Some(id);
651        self
652    }
653
654    pub fn on_select<F>(mut self, f: F) -> Self
655    where
656        F: Fn(&T, &mut Window, &mut App) + Send + Sync + 'static,
657    {
658        self.on_select = Some(Arc::new(f));
659        self
660    }
661
662    fn is_selected(&self, item_id: &T) -> bool {
663        self.selected_id.as_ref() == Some(item_id)
664    }
665
666    fn render_item(
667        &self,
668        item: &ListItem<T>,
669        theme: &crate::capabilities::foundation::theme::Theme,
670    ) -> impl IntoElement {
671        let is_selected = self.is_selected(&item.id);
672
673        let base = div()
674            .flex()
675            .items_center()
676            .w_full()
677            .px(px(12.0))
678            .py(px(8.0))
679            .cursor(if item.disabled {
680                CursorStyle::Arrow
681            } else {
682                CursorStyle::PointingHand
683            });
684
685        let styled = base
686            .bg(if is_selected {
687                theme.tokens.accent
688            } else {
689                gpui::transparent_black()
690            })
691            .text_color(if is_selected {
692                theme.tokens.accent_foreground
693            } else if item.disabled {
694                theme.tokens.muted_foreground
695            } else {
696                theme.tokens.primary
697            })
698            .when(!item.disabled && !is_selected, |div| {
699                div.hover(|mut style| {
700                    style.background = Some(theme.tokens.accent.opacity(0.5).into());
701                    style
702                })
703            });
704
705        let element = if let Some(icon) = item.icon.as_ref() {
706            styled.child(
707                div()
708                    .mr(px(10.0))
709                    .child(
710                        Icon::new(icon.clone())
711                            .size(px(18.0))
712                            .color(if is_selected {
713                                theme.tokens.accent_foreground
714                            } else if item.disabled {
715                                theme.tokens.muted_foreground
716                            } else {
717                                theme.tokens.primary
718                            }),
719                    ),
720            )
721        } else {
722            styled
723        };
724
725        let with_label = element.child(
726            div()
727                .flex_1()
728                .text_size(px(14.0))
729                .font_family(theme.tokens.font_family.clone())
730                .font_weight(if is_selected {
731                    FontWeight::SEMIBOLD
732                } else {
733                    FontWeight::NORMAL
734                })
735                .child(item.label.clone()),
736        );
737
738        let with_badge = with_label.when_some(item.badge.as_ref(), |parent, badge| {
739            parent.child(
740                div()
741                    .px(px(6.0))
742                    .py(px(2.0))
743                    .rounded(px(10.0))
744                    .bg(if is_selected {
745                        theme.tokens.accent_foreground.opacity(0.2)
746                    } else {
747                        theme.tokens.muted
748                    })
749                    .text_size(px(11.0))
750                    .font_family(theme.tokens.font_family.clone())
751                    .font_weight(FontWeight::SEMIBOLD)
752                    .text_color(if is_selected {
753                        theme.tokens.accent_foreground
754                    } else {
755                        theme.tokens.muted_foreground
756                    })
757                    .child(badge.clone()),
758            )
759        });
760
761        with_badge.when(!item.disabled, |this| {
762            let on_select = self.on_select.clone();
763            let item_id = item.id.clone();
764
765            this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
766                if let Some(on_select) = on_select.clone() {
767                    on_select(&item_id, window, cx);
768                }
769            })
770        })
771    }
772}
773
774impl<T: Clone + PartialEq + 'static> RenderOnce for List<T> {
775    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
776        let theme = use_theme(cx);
777
778        div()
779            .flex()
780            .flex_col()
781            .w_full()
782            .bg(theme.tokens.background)
783            .children(
784                self.items
785                    .iter()
786                    .map(|item| self.render_item(item, &theme).into_any_element()),
787            )
788    }
789}
790
791#[cfg(test)]
792mod tests {
793    use super::{filter_tree, find_matches, TreeList, TreeNode};
794    use crate::capabilities::foundation::theme::Theme;
795
796    /// The library documents match ranges as char indices into the label; this
797    /// helper applies them the same way `render_highlighted_text` does.
798    fn char_slice(text: &str, (start, end): (usize, usize)) -> String {
799        text.chars().skip(start).take(end - start).collect()
800    }
801
802    #[test]
803    fn find_matches_on_cjk_label_returns_char_index_ranges() {
804        let (matched, ranges) = find_matches("日本語テスト", "本語");
805        assert!(matched);
806        assert_eq!(ranges, vec![(1, 3)]);
807        assert_eq!(char_slice("日本語テスト", ranges[0]), "本語");
808    }
809
810    #[test]
811    fn find_matches_on_mixed_label_is_case_insensitive_with_char_indices() {
812        let (matched, ranges) = find_matches("中文目录abc", "ABC");
813        assert!(matched);
814        assert_eq!(ranges, vec![(4, 7)]);
815        assert_eq!(char_slice("中文目录abc", ranges[0]), "abc");
816    }
817
818    #[test]
819    fn find_matches_fuzzy_fallback_returns_char_index_ranges() {
820        let (matched, ranges) = find_matches("中文目录", "中录");
821        assert!(matched);
822        assert_eq!(ranges, vec![(0, 4)]);
823        assert_eq!(char_slice("中文目录", ranges[0]), "中文目录");
824    }
825
826    #[test]
827    fn filtering_mid_char_hits_and_highlight_rendering_do_not_panic() {
828        let nodes = vec![
829            TreeNode::new(1, "日本語テスト"),
830            TreeNode::new(2, "中文目录abc"),
831        ];
832
833        // 过滤词命中非 ASCII label 的中部字符(2/3 号 char)
834        let filtered = filter_tree(&nodes, "語テ");
835        assert_eq!(filtered.len(), 1);
836        let entry = &filtered[0];
837        assert_eq!(entry.node.id, 1);
838        assert_eq!(entry.match_ranges, vec![(2, 4)]);
839
840        // 区间应能按 char 索引合法切回原 label,且与预期高亮一致
841        assert_eq!(char_slice(&entry.node.label, entry.match_ranges[0]), "語テ");
842
843        // 修复前按字节区间切 chars 会越界/切乱;现沿渲染路径构造元素必须不 panic
844        let theme = Theme::light();
845        let list = <TreeList<i32>>::new().highlight_matches(true);
846        list.render_highlighted_text(&entry.node.label, &entry.match_ranges, &theme, false);
847    }
848}