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(
441                        flat_nodes_rc
442                            .iter()
443                            .enumerate()
444                            .map(|(_abs_idx, flat_node)| {
445                                let is_selected = selected_id.as_ref() == Some(&flat_node.node_id);
446                                let is_expanded = expanded_ids_rc.contains(&flat_node.node_id);
447                                let has_children = !flat_node.node.children.is_empty()
448                                    || flat_node.node.has_lazy_children;
449                                let indent = px((flat_node.level as f32) * 16.0);
450
451                                div()
452                                    .w_full()
453                                    .h(px(ROW_HEIGHT))
454                                    .flex()
455                                    .items_center()
456                                    .px(px(8.0))
457                                    .pl(indent + px(8.0))
458                                    .cursor(if flat_node.node.disabled {
459                                        CursorStyle::Arrow
460                                    } else {
461                                        CursorStyle::PointingHand
462                                    })
463                                    .bg(if is_selected {
464                                        theme.tokens.accent
465                                    } else {
466                                        gpui::transparent_black()
467                                    })
468                                    .text_color(if is_selected {
469                                        theme.tokens.accent_foreground
470                                    } else if flat_node.node.disabled {
471                                        theme.tokens.muted_foreground
472                                    } else {
473                                        theme.tokens.primary
474                                    })
475                                    .when(!flat_node.node.disabled && !is_selected, |div| {
476                                        div.hover(|mut style| {
477                                            style.background =
478                                                Some(theme.tokens.accent.opacity(0.5).into());
479                                            style
480                                        })
481                                    })
482                                    .when(!flat_node.node.disabled, {
483                                        let on_select = on_select.clone();
484                                        let on_toggle = on_toggle.clone();
485                                        let node_id = flat_node.node_id.clone();
486
487                                        move |this| {
488                                            this.on_mouse_down(
489                                                MouseButton::Left,
490                                                move |_, window, cx| {
491                                                    if let Some(on_select) = on_select.clone() {
492                                                        on_select(&node_id, window, cx);
493                                                    }
494
495                                                    if has_children {
496                                                        if let Some(on_toggle) = on_toggle.clone() {
497                                                            on_toggle(
498                                                                &node_id,
499                                                                !is_expanded,
500                                                                window,
501                                                                cx,
502                                                            );
503                                                        }
504                                                    }
505                                                },
506                                            )
507                                        }
508                                    })
509                                    .when(!flat_node.node.disabled, {
510                                        let on_right_click = on_right_click.clone();
511                                        let node_id = flat_node.node_id.clone();
512
513                                        move |this| {
514                                            this.on_mouse_down(
515                                                MouseButton::Right,
516                                                move |event, window, cx| {
517                                                    if let Some(on_right_click) =
518                                                        on_right_click.clone()
519                                                    {
520                                                        on_right_click(&node_id, event, window, cx);
521                                                    }
522                                                },
523                                            )
524                                        }
525                                    })
526                                    .child(
527                                        div()
528                                            .flex()
529                                            .items_center()
530                                            .gap(px(8.0))
531                                            .children(flat_node.node.icon.as_ref().map(|icon| {
532                                                Icon::new(icon.clone()).size(px(16.0)).color(
533                                                    if is_selected {
534                                                        theme.tokens.accent_foreground
535                                                    } else if flat_node.node.disabled {
536                                                        theme.tokens.muted_foreground
537                                                    } else {
538                                                        theme.tokens.primary
539                                                    },
540                                                )
541                                            }))
542                                            .child(
543                                                div()
544                                                    .flex_1()
545                                                    .text_size(px(14.0))
546                                                    .font_family(theme.tokens.font_family.clone())
547                                                    .font_weight(if is_selected {
548                                                        FontWeight::SEMIBOLD
549                                                    } else {
550                                                        FontWeight::NORMAL
551                                                    })
552                                                    .child({
553                                                        let ranges = match_ranges_rc
554                                                            .get(&flat_node.node_id)
555                                                            .map(|r| r.as_slice())
556                                                            .unwrap_or(&[]);
557
558                                                        if !ranges.is_empty() && highlight_matches {
559                                                            self.render_highlighted_text(
560                                                                &flat_node.node.label,
561                                                                ranges,
562                                                                &theme,
563                                                                is_selected,
564                                                            )
565                                                            .into_any_element()
566                                                        } else {
567                                                            div()
568                                                                .child(flat_node.node.label.clone())
569                                                                .into_any_element()
570                                                        }
571                                                    }),
572                                            )
573                                            .children(if has_children {
574                                                Some(
575                                                    div()
576                                                        .w(px(16.0))
577                                                        .h(px(16.0))
578                                                        .flex()
579                                                        .items_center()
580                                                        .justify_center()
581                                                        .child(
582                                                            Icon::new(if is_expanded {
583                                                                "arrow-down"
584                                                            } else {
585                                                                "arrow-right"
586                                                            })
587                                                            .size(px(12.0))
588                                                            .color(theme.tokens.primary),
589                                                        ),
590                                                )
591                                            } else {
592                                                None
593                                            }),
594                                    )
595                            }),
596                    ),
597            )
598    }
599}
600
601#[derive(Clone)]
602pub struct ListItem<T: Clone> {
603    pub id: T,
604    pub label: SharedString,
605    pub icon: Option<IconSource>,
606    pub badge: Option<SharedString>,
607    pub disabled: bool,
608}
609
610impl<T: Clone> ListItem<T> {
611    pub fn new(id: T, label: impl Into<SharedString>) -> Self {
612        Self {
613            id,
614            label: label.into(),
615            icon: None,
616            badge: None,
617            disabled: false,
618        }
619    }
620
621    pub fn with_icon(mut self, icon: impl Into<IconSource>) -> Self {
622        self.icon = Some(icon.into());
623        self
624    }
625
626    pub fn with_badge(mut self, badge: impl Into<SharedString>) -> Self {
627        self.badge = Some(badge.into());
628        self
629    }
630
631    pub fn disabled(mut self, disabled: bool) -> Self {
632        self.disabled = disabled;
633        self
634    }
635}
636
637#[derive(IntoElement)]
638pub struct List<T: Clone + PartialEq + 'static> {
639    items: Vec<ListItem<T>>,
640    selected_id: Option<T>,
641    on_select: Option<Arc<dyn Fn(&T, &mut Window, &mut App) + Send + Sync + 'static>>,
642}
643
644impl<T: Clone + PartialEq + 'static> Default for List<T> {
645    fn default() -> Self {
646        Self::new()
647    }
648}
649
650impl<T: Clone + PartialEq + 'static> List<T> {
651    pub fn new() -> Self {
652        Self {
653            items: Vec::new(),
654            selected_id: None,
655            on_select: None,
656        }
657    }
658
659    pub fn items(mut self, items: Vec<ListItem<T>>) -> Self {
660        self.items = items;
661        self
662    }
663
664    pub fn selected_id(mut self, id: T) -> Self {
665        self.selected_id = Some(id);
666        self
667    }
668
669    pub fn on_select<F>(mut self, f: F) -> Self
670    where
671        F: Fn(&T, &mut Window, &mut App) + Send + Sync + 'static,
672    {
673        self.on_select = Some(Arc::new(f));
674        self
675    }
676
677    fn is_selected(&self, item_id: &T) -> bool {
678        self.selected_id.as_ref() == Some(item_id)
679    }
680
681    fn render_item(
682        &self,
683        item: &ListItem<T>,
684        theme: &crate::capabilities::foundation::theme::Theme,
685    ) -> impl IntoElement {
686        let is_selected = self.is_selected(&item.id);
687
688        let base = div()
689            .flex()
690            .items_center()
691            .w_full()
692            .px(px(12.0))
693            .py(px(8.0))
694            .cursor(if item.disabled {
695                CursorStyle::Arrow
696            } else {
697                CursorStyle::PointingHand
698            });
699
700        let styled = base
701            .bg(if is_selected {
702                theme.tokens.accent
703            } else {
704                gpui::transparent_black()
705            })
706            .text_color(if is_selected {
707                theme.tokens.accent_foreground
708            } else if item.disabled {
709                theme.tokens.muted_foreground
710            } else {
711                theme.tokens.primary
712            })
713            .when(!item.disabled && !is_selected, |div| {
714                div.hover(|mut style| {
715                    style.background = Some(theme.tokens.accent.opacity(0.5).into());
716                    style
717                })
718            });
719
720        let element = if let Some(icon) = item.icon.as_ref() {
721            styled.child(
722                div()
723                    .mr(px(10.0))
724                    .child(
725                        Icon::new(icon.clone())
726                            .size(px(18.0))
727                            .color(if is_selected {
728                                theme.tokens.accent_foreground
729                            } else if item.disabled {
730                                theme.tokens.muted_foreground
731                            } else {
732                                theme.tokens.primary
733                            }),
734                    ),
735            )
736        } else {
737            styled
738        };
739
740        let with_label = element.child(
741            div()
742                .flex_1()
743                .text_size(px(14.0))
744                .font_family(theme.tokens.font_family.clone())
745                .font_weight(if is_selected {
746                    FontWeight::SEMIBOLD
747                } else {
748                    FontWeight::NORMAL
749                })
750                .child(item.label.clone()),
751        );
752
753        let with_badge = with_label.when_some(item.badge.as_ref(), |parent, badge| {
754            parent.child(
755                div()
756                    .px(px(6.0))
757                    .py(px(2.0))
758                    .rounded(px(10.0))
759                    .bg(if is_selected {
760                        theme.tokens.accent_foreground.opacity(0.2)
761                    } else {
762                        theme.tokens.muted
763                    })
764                    .text_size(px(11.0))
765                    .font_family(theme.tokens.font_family.clone())
766                    .font_weight(FontWeight::SEMIBOLD)
767                    .text_color(if is_selected {
768                        theme.tokens.accent_foreground
769                    } else {
770                        theme.tokens.muted_foreground
771                    })
772                    .child(badge.clone()),
773            )
774        });
775
776        with_badge.when(!item.disabled, |this| {
777            let on_select = self.on_select.clone();
778            let item_id = item.id.clone();
779
780            this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
781                if let Some(on_select) = on_select.clone() {
782                    on_select(&item_id, window, cx);
783                }
784            })
785        })
786    }
787}
788
789impl<T: Clone + PartialEq + 'static> RenderOnce for List<T> {
790    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
791        let theme = use_theme(cx);
792
793        div()
794            .flex()
795            .flex_col()
796            .w_full()
797            .bg(theme.tokens.background)
798            .children(
799                self.items
800                    .iter()
801                    .map(|item| self.render_item(item, &theme).into_any_element()),
802            )
803    }
804}
805
806#[cfg(test)]
807mod tests {
808    use super::{filter_tree, find_matches, TreeList, TreeNode};
809    use crate::capabilities::foundation::theme::Theme;
810
811    /// The library documents match ranges as char indices into the label; this
812    /// helper applies them the same way `render_highlighted_text` does.
813    fn char_slice(text: &str, (start, end): (usize, usize)) -> String {
814        text.chars().skip(start).take(end - start).collect()
815    }
816
817    #[test]
818    fn find_matches_on_cjk_label_returns_char_index_ranges() {
819        let (matched, ranges) = find_matches("日本語テスト", "本語");
820        assert!(matched);
821        assert_eq!(ranges, vec![(1, 3)]);
822        assert_eq!(char_slice("日本語テスト", ranges[0]), "本語");
823    }
824
825    #[test]
826    fn find_matches_on_mixed_label_is_case_insensitive_with_char_indices() {
827        let (matched, ranges) = find_matches("中文目录abc", "ABC");
828        assert!(matched);
829        assert_eq!(ranges, vec![(4, 7)]);
830        assert_eq!(char_slice("中文目录abc", ranges[0]), "abc");
831    }
832
833    #[test]
834    fn find_matches_fuzzy_fallback_returns_char_index_ranges() {
835        let (matched, ranges) = find_matches("中文目录", "中录");
836        assert!(matched);
837        assert_eq!(ranges, vec![(0, 4)]);
838        assert_eq!(char_slice("中文目录", ranges[0]), "中文目录");
839    }
840
841    #[test]
842    fn filtering_mid_char_hits_and_highlight_rendering_do_not_panic() {
843        let nodes = vec![
844            TreeNode::new(1, "日本語テスト"),
845            TreeNode::new(2, "中文目录abc"),
846        ];
847
848        // 过滤词命中非 ASCII label 的中部字符(2/3 号 char)
849        let filtered = filter_tree(&nodes, "語テ");
850        assert_eq!(filtered.len(), 1);
851        let entry = &filtered[0];
852        assert_eq!(entry.node.id, 1);
853        assert_eq!(entry.match_ranges, vec![(2, 4)]);
854
855        // 区间应能按 char 索引合法切回原 label,且与预期高亮一致
856        assert_eq!(char_slice(&entry.node.label, entry.match_ranges[0]), "語テ");
857
858        // 修复前按字节区间切 chars 会越界/切乱;现沿渲染路径构造元素必须不 panic
859        let theme = Theme::light();
860        let list = <TreeList<i32>>::new().highlight_matches(true);
861        list.render_highlighted_text(&entry.node.label, &entry.match_ranges, &theme, false);
862    }
863}