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