1
//! Tree view widget with expandable/collapsible nodes.
2
//!
3
//! Provides [`TreeView`] and [`TreeViewNode`] for building hierarchical
4
//! tree structures with click callbacks and recursive DOM rendering.
5

            
6
use azul_core::{
7
    callbacks::{CoreCallback, CoreCallbackData, Update},
8
    dom::{
9
        Dom, DomVec, EventFilter, HoverEventFilter, IdOrClass, IdOrClass::Class, IdOrClassVec,
10
        TabIndex,
11
    },
12
    refany::RefAny,
13
};
14
#[allow(clippy::wildcard_imports)]
15
// widget/render module pulls in the css property/value types it builds with
16
use azul_css::{
17
    dynamic_selector::{
18
        CssPropertyWithConditions, CssPropertyWithConditionsVec, DynamicSelector, PseudoStateType,
19
        ThemeCondition,
20
    },
21
    props::{
22
        basic::{
23
            color::{ColorOrSystem, ColorU},
24
            font::{StyleFontFamily, StyleFontFamilyVec},
25
            *,
26
        },
27
        layout::*,
28
        property::CssProperty,
29
        style::*,
30
    },
31
    *,
32
};
33
use azul_css::{
34
    impl_option, impl_vec, impl_vec_clone, impl_vec_debug, impl_vec_mut, impl_vec_partialeq,
35
};
36

            
37
use crate::callbacks::{Callback, CallbackInfo};
38

            
39
// -- Callback type via macro --
40

            
41
/// Callback invoked when a tree node is clicked.
42
///
43
/// The `usize` parameter is the depth-first index of the clicked node
44
/// (0 = root, then incremented in pre-order traversal).
45
pub type TreeViewOnNodeClickCallbackType = extern "C" fn(RefAny, CallbackInfo, usize) -> Update;
46
impl_widget_callback!(
47
    TreeViewOnNodeClick,
48
    OptionTreeViewOnNodeClick,
49
    TreeViewOnNodeClickCallback,
50
    TreeViewOnNodeClickCallbackType
51
);
52

            
53
azul_core::impl_managed_callback! {
54
    wrapper:        TreeViewOnNodeClickCallback,
55
    info_ty:        CallbackInfo,
56
    return_ty:      Update,
57
    default_ret:    Update::DoNothing,
58
    invoker_static: TREE_VIEW_ON_NODE_CLICK_INVOKER,
59
    invoker_ty:     AzTreeViewOnNodeClickCallbackInvoker,
60
    thunk_fn:       az_tree_view_on_node_click_callback_thunk,
61
    setter_fn:      AzApp_setTreeViewOnNodeClickCallbackInvoker,
62
    from_handle_fn: AzTreeViewOnNodeClickCallback_createFromHostHandle,
63
    extra_args:     [ node_index: usize ],
64
}
65

            
66
// -- Font --
67

            
68
const SYSTEM_UI_STR: AzString = AzString::from_const_str("system:ui");
69
const SYSTEM_UI_FAMILIES: &[StyleFontFamily] = &[StyleFontFamily::System(SYSTEM_UI_STR)];
70
const SYSTEM_UI_FAMILY: StyleFontFamilyVec =
71
    StyleFontFamilyVec::from_const_slice(SYSTEM_UI_FAMILIES);
72

            
73
// -- Colors --
74

            
75
const TEXT_COLOR: ColorU = ColorU {
76
    r: 30,
77
    g: 30,
78
    b: 30,
79
    a: 255,
80
};
81
const SELECTED_BG: ColorU = ColorU {
82
    r: 0,
83
    g: 120,
84
    b: 215,
85
    a: 255,
86
};
87
const SELECTED_TEXT: ColorU = ColorU {
88
    r: 255,
89
    g: 255,
90
    b: 255,
91
    a: 255,
92
};
93
/// The tree is a FIELD, like the list view next to it: it draws its own
94
/// surface. Without one the control was transparent and inherited whatever it
95
/// happened to sit on, which is why it read as a floating list of labels
96
/// rather than a pane. Same value as `__azul_native_list-container`.
97
const FIELD_BG: ColorU = ColorU {
98
    r: 252,
99
    g: 252,
100
    b: 252,
101
    a: 255,
102
};
103
// -- Dark theme --
104
//
105
// Inline CSS carries `@theme dark` conditions (`dark_theme`), and a later
106
// property wins, so each dark value is declared right after the light one it
107
// replaces. These are DEFAULTS: an app that wants the exact platform palette
108
// still overrides them, but a tree must not be a white box in a dark window.
109
const FIELD_BG_DARK: ColorU = ColorU {
110
    r: 31,
111
    g: 31,
112
    b: 31,
113
    a: 255,
114
};
115
const TEXT_COLOR_DARK: ColorU = ColorU {
116
    r: 230,
117
    g: 230,
118
    b: 230,
119
    a: 255,
120
};
121
const SELECTED_BG_DARK: ColorU = ColorU {
122
    r: 9,
123
    g: 71,
124
    b: 113,
125
    a: 255,
126
};
127
const ICON_COLOR_DARK: ColorU = ColorU {
128
    r: 176,
129
    g: 176,
130
    b: 176,
131
    a: 255,
132
};
133
const ICON_COLOR: ColorU = ColorU {
134
    r: 100,
135
    g: 100,
136
    b: 100,
137
    a: 255,
138
};
139

            
140
// -- Tree container style --
141

            
142
static TREE_CONTAINER_STYLE: &[CssPropertyWithConditions] = &[
143
    CssPropertyWithConditions::simple(CssProperty::const_background_content(
144
        StyleBackgroundContentVec::from_const_slice(&[StyleBackgroundContent::Color(FIELD_BG)]),
145
    )),
146
    CssPropertyWithConditions::simple(CssProperty::const_overflow_y(LayoutOverflow::Auto)),
147
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
148
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
149
        LayoutFlexDirection::Column,
150
    )),
151
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(13))),
152
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SYSTEM_UI_FAMILY)),
153
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
154
        inner: TEXT_COLOR,
155
    })),
156
    CssPropertyWithConditions::dark_theme(CssProperty::const_background_content(
157
        StyleBackgroundContentVec::from_const_slice(&[StyleBackgroundContent::Color(
158
            FIELD_BG_DARK,
159
        )]),
160
    )),
161
    CssPropertyWithConditions::dark_theme(CssProperty::const_text_color(StyleTextColor {
162
        inner: TEXT_COLOR_DARK,
163
    })),
164
];
165

            
166
// -- Row style (each tree node row) --
167

            
168
static ROW_STYLE: &[CssPropertyWithConditions] = &[
169
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
170
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
171
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
172
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
173
        2,
174
    ))),
175
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
176
        LayoutPaddingBottom::const_px(2),
177
    )),
178
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
179
        LayoutPaddingLeft::const_px(4),
180
    )),
181
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
182
        LayoutPaddingRight::const_px(4),
183
    )),
184
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
185
    // Hover, light and dark. Declared in the theme module — see
186
    // `themes::flat::ROW_HOVER` — because the dark half needs a palette this
187
    // file cannot see. The pair used to live here, with the dark twin spelled
188
    // out by hand through `with_single_condition`.
189
    crate::widgets::themes::flat::ROW_HOVER,
190
    crate::widgets::themes::flat::ROW_HOVER_DARK,
191
];
192

            
193
// -- Selected row style --
194
// NOTE: Intentionally duplicates base properties from ROW_STYLE because
195
// const-slice styling does not support runtime composition. If you change
196
// padding/layout in ROW_STYLE, update ROW_SELECTED_STYLE to match.
197

            
198
static ROW_SELECTED_STYLE: &[CssPropertyWithConditions] = &[
199
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
200
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
201
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
202
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
203
        2,
204
    ))),
205
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
206
        LayoutPaddingBottom::const_px(2),
207
    )),
208
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
209
        LayoutPaddingLeft::const_px(4),
210
    )),
211
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
212
        LayoutPaddingRight::const_px(4),
213
    )),
214
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
215
    CssPropertyWithConditions::simple(CssProperty::const_background_content(
216
        StyleBackgroundContentVec::from_const_slice(&[StyleBackgroundContent::Color(SELECTED_BG)]),
217
    )),
218
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
219
        inner: SELECTED_TEXT,
220
    })),
221
    CssPropertyWithConditions::dark_theme(CssProperty::const_background_content(
222
        StyleBackgroundContentVec::from_const_slice(&[StyleBackgroundContent::Color(
223
            SELECTED_BG_DARK,
224
        )]),
225
    )),
226
];
227

            
228
// -- Children container style --
229

            
230
static CHILDREN_STYLE: &[CssPropertyWithConditions] = &[
231
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
232
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
233
        LayoutFlexDirection::Column,
234
    )),
235
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
236
        LayoutPaddingLeft::const_px(16),
237
    )),
238
];
239

            
240
// -- Disclosure icon style --
241
// NOTE: Icon font-size (16px) must match LEAF_SPACER_STYLE width so that
242
// leaf nodes align with parent nodes that have a disclosure icon.
243

            
244
static ICON_STYLE: &[CssPropertyWithConditions] = &[
245
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(16))),
246
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
247
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
248
        inner: ICON_COLOR,
249
    })),
250
    CssPropertyWithConditions::dark_theme(CssProperty::const_text_color(StyleTextColor {
251
        inner: ICON_COLOR_DARK,
252
    })),
253
];
254

            
255
// -- Leaf spacer (same width as icon, for alignment) --
256

            
257
static LEAF_SPACER_STYLE: &[CssPropertyWithConditions] = &[
258
    CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(16))),
259
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
260
];
261

            
262
// -- Label style --
263

            
264
static LABEL_STYLE: &[CssPropertyWithConditions] = &[
265
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
266
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
267
        LayoutPaddingLeft::const_px(4),
268
    )),
269
    // The dark text colour is declared HERE, on the node that carries the
270
    // text, not only on the container: a CONDITIONAL inline value does not
271
    // reach a child through inheritance, so labels kept the light colour and
272
    // came out near-black on the dark surface.
273
    CssPropertyWithConditions::dark_theme(CssProperty::const_text_color(StyleTextColor {
274
        inner: TEXT_COLOR_DARK,
275
    })),
276
];
277

            
278
// ============================================================================
279
// Data structures
280
// ============================================================================
281

            
282
/// A single node in a tree hierarchy, with optional children.
283
#[derive(Debug, Clone, PartialEq)]
284
#[repr(C)]
285
pub struct TreeViewNode {
286
    /// Display text for this node.
287
    pub label: AzString,
288
    /// Child nodes nested under this node.
289
    pub children: TreeViewNodeVec,
290
    /// Whether children are visible (only meaningful when `children` is non-empty).
291
    pub is_expanded: bool,
292
    /// Whether this node is visually selected.
293
    pub is_selected: bool,
294
}
295

            
296
impl TreeViewNode {
297
    /// Creates a new collapsed, unselected leaf node with the given label.
298
23983
    pub fn new<S: Into<AzString>>(label: S) -> Self {
299
23983
        Self {
300
23983
            label: label.into(),
301
23983
            children: TreeViewNodeVec::from_const_slice(&[]),
302
23983
            is_expanded: false,
303
23983
            is_selected: false,
304
23983
        }
305
23983
    }
306

            
307
    /// Appends a child node.
308
11041
    pub fn add_child(&mut self, child: Self) {
309
11041
        self.children.push(child);
310
11041
    }
311

            
312
    /// Builder method: appends a child node.
313
    #[must_use]
314
12792
    pub fn with_child(mut self, child: Self) -> Self {
315
12792
        self.children.push(child);
316
12792
        self
317
12792
    }
318

            
319
    /// Builder method: sets the expanded state.
320
    #[must_use]
321
12754
    pub const fn with_expanded(mut self, expanded: bool) -> Self {
322
12754
        self.is_expanded = expanded;
323
12754
        self
324
12754
    }
325

            
326
    /// Builder method: sets the selected state.
327
    #[must_use]
328
35
    pub const fn with_selected(mut self, selected: bool) -> Self {
329
35
        self.is_selected = selected;
330
35
        self
331
35
    }
332
}
333

            
334
impl_option!(
335
    TreeViewNode,
336
    OptionTreeViewNode,
337
    copy = false,
338
    [Debug, Clone, PartialEq]
339
);
340
impl_vec!(
341
    TreeViewNode,
342
    TreeViewNodeVec,
343
    TreeViewNodeVecDestructor,
344
    TreeViewNodeVecDestructorType,
345
    TreeViewNodeVecSlice,
346
    OptionTreeViewNode
347
);
348
impl_vec_clone!(TreeViewNode, TreeViewNodeVec, TreeViewNodeVecDestructor);
349
impl_vec_debug!(TreeViewNode, TreeViewNodeVec);
350
impl_vec_partialeq!(TreeViewNode, TreeViewNodeVec);
351
impl_vec_mut!(TreeViewNode, TreeViewNodeVec);
352

            
353
/// Hierarchical tree view widget with expandable/collapsible nodes.
354
#[derive(Debug, Clone, PartialEq)]
355
#[repr(C)]
356
pub struct TreeView {
357
    /// Root node of the tree hierarchy.
358
    pub root: TreeViewNode,
359
    /// Optional callback fired when any node is clicked.
360
    pub on_node_click: OptionTreeViewOnNodeClick,
361
}
362

            
363
impl TreeView {
364
    /// Creates a new tree view with the given root node and no click callback.
365
    #[must_use]
366
75
    pub fn new(root: TreeViewNode) -> Self {
367
75
        Self {
368
75
            root,
369
75
            on_node_click: None.into(),
370
75
        }
371
75
    }
372

            
373
    /// Sets the callback invoked when any tree node is clicked.
374
17
    pub fn set_on_node_click<C: Into<TreeViewOnNodeClickCallback>>(
375
17
        &mut self,
376
17
        data: RefAny,
377
17
        callback: C,
378
17
    ) {
379
17
        self.on_node_click = Some(TreeViewOnNodeClick {
380
17
            callback: callback.into(),
381
17
            refany: data,
382
17
        })
383
17
        .into();
384
17
    }
385

            
386
    /// Builder method: sets the node-click callback.
387
    #[must_use]
388
14
    pub fn with_on_node_click<C: Into<TreeViewOnNodeClickCallback>>(
389
14
        mut self,
390
14
        data: RefAny,
391
14
        callback: C,
392
14
    ) -> Self {
393
14
        self.set_on_node_click(data, callback);
394
14
        self
395
14
    }
396

            
397
    /// Renders the tree view into a [`Dom`] subtree.
398
    #[must_use]
399
61
    pub fn dom(self) -> Dom {
400
        const TREE_CLASS: &[IdOrClass] =
401
            &[Class(AzString::from_const_str("__azul-native-tree-view"))];
402

            
403
61
        let on_node_click = self.on_node_click;
404
61
        let root = self.root;
405

            
406
61
        let mut children = Vec::new();
407
61
        let mut index: usize = 0;
408
61
        render_node(&root, &on_node_click, &mut index, &mut children);
409

            
410
61
        Dom::create_div()
411
61
            .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
412
61
                TREE_CONTAINER_STYLE,
413
            ))
414
61
            .with_ids_and_classes(IdOrClassVec::from_const_slice(TREE_CLASS))
415
61
            .with_children(DomVec::from_vec(children))
416
61
    }
417
}
418

            
419
// ============================================================================
420
// Internal: recursive DOM rendering
421
// ============================================================================
422

            
423
7519
fn render_node(
424
7519
    node: &TreeViewNode,
425
7519
    on_click: &OptionTreeViewOnNodeClick,
426
7519
    index: &mut usize,
427
7519
    out: &mut Vec<Dom>,
428
7519
) {
429
7519
    let current_index = *index;
430
7519
    *index += 1;
431

            
432
7519
    let has_children = !node.children.as_slice().is_empty();
433

            
434
    // Choose row style based on selection state
435
7519
    let row_style = if node.is_selected {
436
24
        ROW_SELECTED_STYLE
437
    } else {
438
7495
        ROW_STYLE
439
    };
440

            
441
    // Build the disclosure icon or spacer
442
7519
    let icon_or_spacer = if has_children {
443
1751
        let icon_name = if node.is_expanded {
444
1697
            "expand_more"
445
        } else {
446
54
            "chevron_right"
447
        };
448
1751
        Dom::create_icon(AzString::from_const_str(icon_name))
449
1751
            .with_css_props(CssPropertyWithConditionsVec::from_const_slice(ICON_STYLE))
450
    } else {
451
        // Empty spacer for leaf alignment
452
5768
        Dom::create_div().with_css_props(CssPropertyWithConditionsVec::from_const_slice(
453
5768
            LEAF_SPACER_STYLE,
454
        ))
455
    };
456

            
457
    // Build the label
458
7519
    let label = crate::widgets::widget_p_with_text(node.label.clone())
459
7519
        .with_css_props(CssPropertyWithConditionsVec::from_const_slice(LABEL_STYLE));
460

            
461
    // Build the row with click callback
462
7519
    let mut row = Dom::create_div()
463
7519
        .with_css_props(CssPropertyWithConditionsVec::from_const_slice(row_style))
464
7519
        .with_tab_index(TabIndex::Auto)
465
            // Role so the accessibility tree knows what this IS:
466
            // a hierarchy, so level and expansion can be reported. The NAME comes from the widget's own text,
467
            // which azul derives when a readable label is present.
468
7519
            .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
469
7519
                role: azul_core::a11y::AccessibilityRole::Outline,
470
7519
                ..Default::default()
471
7519
            })
472
7519
        .with_children(DomVec::from_vec(vec![icon_or_spacer, label]));
473

            
474
    // Attach click callback if provided
475
7519
    if let Some(cb) = on_click.as_ref() {
476
5197
        let cb_data = NodeClickData {
477
5197
            node_index: current_index,
478
5197
            on_node_click: Some(TreeViewOnNodeClick {
479
5197
                callback: cb.callback.clone(),
480
5197
                refany: cb.refany.clone(),
481
5197
            })
482
5197
            .into(),
483
5197
        };
484
5197
        row = row.with_callbacks(
485
5197
            vec![CoreCallbackData {
486
5197
                event: EventFilter::Hover(HoverEventFilter::Click),
487
5197
                refany: RefAny::new(cb_data),
488
5197
                callback: CoreCallback {
489
5197
                    cb: on_tree_node_click as usize,
490
5197
                    ctx: azul_core::refany::OptionRefAny::None,
491
5197
                },
492
5197
            }]
493
5197
            .into(),
494
5197
        );
495
5197
    }
496

            
497
7519
    out.push(row);
498

            
499
    // Render children if expanded
500
7519
    if has_children && node.is_expanded {
501
1697
        let mut child_doms = Vec::new();
502
7388
        for child in node.children.as_slice() {
503
7388
            render_node(child, on_click, index, &mut child_doms);
504
7388
        }
505

            
506
1697
        let children_container = Dom::create_div()
507
1697
            .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
508
1697
                CHILDREN_STYLE,
509
            ))
510
1697
            .with_children(DomVec::from_vec(child_doms));
511

            
512
1697
        out.push(children_container);
513
5822
    } else if has_children {
514
54
        // Still count collapsed children for correct depth-first indexing
515
54
        count_descendants(node.children.as_slice(), index);
516
5768
    }
517
7519
}
518

            
519
/// Advance the index counter past all descendants without rendering them.
520
10140
fn count_descendants(nodes: &[TreeViewNode], index: &mut usize) {
521
21303
    for node in nodes {
522
11163
        *index += 1;
523
11163
        if !node.children.as_slice().is_empty() {
524
10046
            count_descendants(node.children.as_slice(), index);
525
10046
        }
526
    }
527
10140
}
528

            
529
// ============================================================================
530
// Internal callback data
531
// ============================================================================
532

            
533
struct NodeClickData {
534
    node_index: usize,
535
    on_node_click: OptionTreeViewOnNodeClick,
536
}
537

            
538
// ============================================================================
539
// Callbacks
540
// ============================================================================
541

            
542
20
extern "C" fn on_tree_node_click(mut refany: RefAny, info: CallbackInfo) -> Update {
543
20
    let Some(mut refany) = refany.downcast_mut::<NodeClickData>() else {
544
4
        return Update::DoNothing;
545
    };
546

            
547
16
    let node_index = refany.node_index;
548

            
549
16
    match refany.on_node_click.as_mut() {
550
14
        Some(TreeViewOnNodeClick { refany, callback }) => {
551
14
            (callback.cb)(refany.clone(), info, node_index)
552
        }
553
2
        None => Update::DoNothing,
554
    }
555
20
}
556

            
557
// ============================================================================
558
// Trait impls
559
// ============================================================================
560

            
561
impl From<TreeView> for Dom {
562
11
    fn from(tv: TreeView) -> Self {
563
11
        tv.dom()
564
11
    }
565
}
566

            
567
#[cfg(test)]
568
mod autotest_generated {
569
    use std::{
570
        collections::BTreeMap,
571
        sync::{Arc, Mutex},
572
    };
573

            
574
    use azul_core::{
575
        dom::{DomId, DomNodeId, NodeId, NodeType},
576
        geom::OptionLogicalPosition,
577
        gl::OptionGlContextPtr,
578
        hit_test::ScrollPosition,
579
        refany::OptionRefAny,
580
        resources::RendererResources,
581
        styled_dom::NodeHierarchyItemId,
582
        window::{MonitorVec, RawWindowHandle},
583
    };
584
    use azul_css::system::SystemStyle;
585
    use rust_fontconfig::FcFontCache;
586

            
587
    use super::*;
588
    #[cfg(feature = "icu")]
589
    use crate::icu::IcuLocalizerHandle;
590
    use crate::{
591
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
592
        window::LayoutWindow,
593
        window_state::FullWindowState,
594
    };
595

            
596
    // ------------------------------------------------------------------
597
    // Fixtures: trees
598
    // ------------------------------------------------------------------
599

            
600
    fn leaf(label: &str) -> TreeViewNode {
601
        TreeViewNode::new(label)
602
    }
603

            
604
    /// Total node count of a subtree: the node itself plus every descendant,
605
    /// expanded or not. This is the quantity `render_node` must advance the
606
    /// index counter by, whatever the expansion state.
607
    fn subtree_len(node: &TreeViewNode) -> usize {
608
        1 + node
609
            .children
610
            .as_slice()
611
            .iter()
612
            .map(subtree_len)
613
            .sum::<usize>()
614
    }
615

            
616
    /// A root with `n` leaf children.
617
    fn wide(n: usize, expanded: bool) -> TreeViewNode {
618
        let mut root = leaf("wide").with_expanded(expanded);
619
        for i in 0..n {
620
            root.add_child(leaf(&format!("c{i}")));
621
        }
622
        root
623
    }
624

            
625
    /// A left-spine chain `depth` nodes deep; `expanded` is applied to every
626
    /// level. Built bottom-up so *construction* is iterative — only the
627
    /// functions under test recurse.
628
    fn chain(depth: usize, expanded: bool) -> TreeViewNode {
629
        assert!(depth >= 1, "a chain has at least the root");
630
        let mut node = leaf("tip").with_expanded(expanded);
631
        for i in 1..depth {
632
            node = leaf(&format!("n{i}"))
633
                .with_child(node)
634
                .with_expanded(expanded);
635
        }
636
        node
637
    }
638

            
639
    /// Four levels with alternating expansion, so both `render_node` branches
640
    /// nest inside each other.
641
    fn deep_mixed() -> TreeViewNode {
642
        leaf("root")
643
            .with_expanded(true)
644
            .with_child(
645
                leaf("a")
646
                    .with_expanded(false) // collapsed: a1/a1x are counted, not drawn
647
                    .with_child(leaf("a1").with_expanded(true).with_child(leaf("a1x"))),
648
            )
649
            .with_child(
650
                leaf("b")
651
                    .with_expanded(true)
652
                    .with_child(leaf("b1"))
653
                    .with_child(leaf("b2").with_expanded(true).with_child(leaf("b2x"))),
654
            )
655
            .with_child(leaf("c").with_selected(true))
656
    }
657

            
658
    /// Every shape whose combination of branches `render_node` /
659
    /// `count_descendants` can take: leaves, expanded-but-childless nodes,
660
    /// collapsed parents, expanded parents, an expanded subtree buried under a
661
    /// collapsed one, and a collapsed subtree under an expanded one.
662
    fn shapes() -> Vec<TreeViewNode> {
663
        vec![
664
            leaf("solo"),
665
            leaf("solo-expanded").with_expanded(true), // expanded but childless
666
            leaf("solo-selected").with_selected(true),
667
            leaf("p").with_child(leaf("a")).with_child(leaf("b")),
668
            leaf("p")
669
                .with_child(leaf("a"))
670
                .with_child(leaf("b"))
671
                .with_expanded(true),
672
            leaf("p")
673
                .with_child(leaf("a").with_expanded(true).with_child(leaf("a1")))
674
                .with_expanded(true),
675
            leaf("p").with_child(leaf("a").with_expanded(true).with_child(leaf("a1"))),
676
            leaf("p")
677
                .with_child(leaf("a").with_child(leaf("a1")))
678
                .with_expanded(true),
679
            deep_mixed(),
680
            wide(64, false),
681
            wide(64, true),
682
        ]
683
    }
684

            
685
    /// Labels chosen to break naive string handling: empty, whitespace-only,
686
    /// embedded NUL (`AzString` is length-based, so it must not truncate),
687
    /// ZWJ emoji, RTL, stacked combining marks, zero-width/BOM, bidi override,
688
    /// control chars, and a string that looks like an icon name.
689
    fn pathological_labels() -> Vec<String> {
690
        vec![
691
            String::new(),
692
            "   ".to_string(),
693
            "a\u{0}b".to_string(),
694
            "👨‍👩‍👧‍👦".to_string(),
695
            "مرحبا".to_string(),
696
            "e\u{0301}\u{0301}\u{0301}".to_string(),
697
            "\u{200b}\u{feff}".to_string(),
698
            "\u{202e}gnirts".to_string(),
699
            "line\nbreak\ttab\r".to_string(),
700
            "chevron_right".to_string(),
701
            "x".repeat(100_000),
702
        ]
703
    }
704

            
705
    /// Runs `f` on a thread with a roomy stack. `render_node`,
706
    /// `count_descendants` and `TreeViewNode`'s drop glue all recurse once per
707
    /// tree level, and a blown stack aborts the whole test binary instead of
708
    /// failing one test — the explicit stack keeps the depth assertions
709
    /// meaningful rather than a coin flip on the harness default.
710
    fn on_big_stack<F: FnOnce() + Send + 'static>(f: F) {
711
        std::thread::Builder::new()
712
            .stack_size(64 * 1024 * 1024)
713
            .spawn(f)
714
            .expect("spawning the deep-recursion thread failed")
715
            .join()
716
            .expect("deep-recursion thread panicked");
717
    }
718

            
719
    // ------------------------------------------------------------------
720
    // Fixtures: DOM inspection
721
    // ------------------------------------------------------------------
722

            
723
    /// The text of a text node, looking through the `<p>` block wrapper the
724
    /// label convention mandates (`p > text`).
725
    fn text_of(dom: &Dom) -> Option<&str> {
726
        match dom.root.get_node_type() {
727
            NodeType::Text(s) => Some(s.as_ref().as_str()),
728
            NodeType::P => match dom.children.as_ref() {
729
                [only] => match only.root.get_node_type() {
730
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
731
                    _ => None,
732
                },
733
                _ => None,
734
            },
735
            _ => None,
736
        }
737
    }
738

            
739
    fn icon_of(dom: &Dom) -> Option<&str> {
740
        match dom.root.get_node_type() {
741
            NodeType::Icon(s) => Some(s.as_ref().as_str()),
742
            _ => None,
743
        }
744
    }
745

            
746
    /// True when a node's inline style is exactly the given const style slice.
747
    fn style_is(dom: &Dom, expected: &'static [CssPropertyWithConditions]) -> bool {
748
        *dom.root.get_style()
749
            == css::Css::from(CssPropertyWithConditionsVec::from_const_slice(expected))
750
    }
751

            
752
    /// The `(icon-or-spacer, label)` pair of a rendered row.
753
    fn row_parts(row: &Dom) -> (&Dom, &Dom) {
754
        let ch = row.children.as_ref();
755
        assert_eq!(ch.len(), 2, "every row is [icon|spacer, label]");
756
        (&ch[0], &ch[1])
757
    }
758

            
759
    /// Every rendered row in `nodes`, in visual order. Rows are the only nodes
760
    /// `render_node` gives a tab index to; everything else at this level is a
761
    /// children container, which is recursed into.
762
    fn collect_rows<'a>(nodes: &'a [Dom], out: &mut Vec<&'a Dom>) {
763
        for n in nodes {
764
            if n.root.get_tab_index().is_some() {
765
                out.push(n);
766
            } else {
767
                collect_rows(n.children.as_ref(), out);
768
            }
769
        }
770
    }
771

            
772
    fn rows_of(nodes: &[Dom]) -> Vec<&Dom> {
773
        let mut out = Vec::new();
774
        collect_rows(nodes, &mut out);
775
        out
776
    }
777

            
778
    /// The `node_index` the row's click payload carries (`None` when the row
779
    /// has no callback attached).
780
    fn click_index_of(row: &Dom) -> Option<usize> {
781
        let mut data = row.root.get_callbacks().as_ref().first()?.refany.clone();
782
        let payload = data
783
            .downcast_ref::<NodeClickData>()
784
            .expect("a row callback payload is always a NodeClickData");
785
        let index = payload.node_index;
786
        drop(payload);
787
        Some(index)
788
    }
789

            
790
    /// `(node_index, label)` for every rendered row.
791
    fn rendered_pairs(nodes: &[Dom]) -> Vec<(usize, String)> {
792
        rows_of(nodes)
793
            .iter()
794
            .map(|row| {
795
                let (_, label) = row_parts(row);
796
                (
797
                    click_index_of(row).expect("row must carry a click payload"),
798
                    text_of(label)
799
                        .expect("a row's second child is the label text node")
800
                        .to_string(),
801
                )
802
            })
803
            .collect()
804
    }
805

            
806
    /// Independent reference model of what `render_node` should emit:
807
    /// pre-order over the *whole* tree, but only visible nodes produce a row.
808
    /// Written from the documented contract, not from the implementation.
809
    fn expected_pairs(node: &TreeViewNode, next: &mut usize, out: &mut Vec<(usize, String)>) {
810
        let index = *next;
811
        *next += 1;
812
        out.push((index, node.label.as_str().to_string()));
813

            
814
        let children = node.children.as_slice();
815
        if node.is_expanded && !children.is_empty() {
816
            for c in children {
817
                expected_pairs(c, next, out);
818
            }
819
        } else {
820
            // Hidden descendants still consume indices.
821
            *next += subtree_len(node) - 1;
822
        }
823
    }
824

            
825
    fn expected_of(tree: &TreeViewNode, start: usize) -> Vec<(usize, String)> {
826
        let mut next = start;
827
        let mut out = Vec::new();
828
        expected_pairs(tree, &mut next, &mut out);
829
        out
830
    }
831

            
832
    /// The true recursive descendant count — what `estimated_total_children`
833
    /// caches and what `convert_dom_into_compact_dom` allocates from.
834
    fn recursive_descendants(dom: &Dom) -> usize {
835
        dom.children
836
            .as_ref()
837
            .iter()
838
            .map(|c| 1 + recursive_descendants(c))
839
            .sum()
840
    }
841

            
842
    fn assert_estimates_consistent(dom: &Dom) {
843
        assert_eq!(
844
            dom.estimated_total_children,
845
            recursive_descendants(dom),
846
            "estimated_total_children desynced from the real subtree size"
847
        );
848
        for c in dom.children.as_ref() {
849
            assert_estimates_consistent(c);
850
        }
851
    }
852

            
853
    // ------------------------------------------------------------------
854
    // Fixtures: callbacks
855
    // ------------------------------------------------------------------
856

            
857
    type ClickLog = Arc<Mutex<Vec<usize>>>;
858

            
859
    /// Offset applied by `record_click_all_windows` so the two recorders stay
860
    /// distinguishable in the log.
861
    const SENTINEL: usize = 1_000_000;
862

            
863
    extern "C" fn record_click(mut data: RefAny, _info: CallbackInfo, node_index: usize) -> Update {
864
        if let Some(log) = data.downcast_ref::<ClickLog>() {
865
            log.lock().expect("click log poisoned").push(node_index);
866
        }
867
        Update::RefreshDom
868
    }
869

            
870
    /// A second callback with a *deliberately different body*: two identical
871
    /// `extern "C"` bodies are fair game for identical-code folding, which
872
    /// would merge their addresses and make "last write wins" vacuous.
873
    extern "C" fn record_click_all_windows(
874
        mut data: RefAny,
875
        _info: CallbackInfo,
876
        node_index: usize,
877
    ) -> Update {
878
        if let Some(log) = data.downcast_ref::<ClickLog>() {
879
            log.lock()
880
                .expect("click log poisoned")
881
                .push(node_index.wrapping_add(SENTINEL));
882
        }
883
        Update::RefreshDomAllWindows
884
    }
885

            
886
    /// Forces the `fn`-item -> `fn`-pointer coercion the `Into` bound needs.
887
    fn cb(f: TreeViewOnNodeClickCallbackType) -> TreeViewOnNodeClickCallback {
888
        f.into()
889
    }
890

            
891
    fn new_log() -> ClickLog {
892
        Arc::new(Mutex::new(Vec::new()))
893
    }
894

            
895
    fn entries(log: &ClickLog) -> Vec<usize> {
896
        log.lock().expect("click log poisoned").clone()
897
    }
898

            
899
    fn some_click(f: TreeViewOnNodeClickCallbackType, log: &ClickLog) -> OptionTreeViewOnNodeClick {
900
        Some(TreeViewOnNodeClick {
901
            callback: cb(f),
902
            refany: RefAny::new(log.clone()),
903
        })
904
        .into()
905
    }
906

            
907
    /// Invokes `on_tree_node_click` once per payload against one shared
908
    /// `CallbackInfo`. `on_tree_node_click` never touches the layout results,
909
    /// so an empty `LayoutWindow` is enough.
910
    fn run_clicks(payloads: Vec<RefAny>) -> Vec<Update> {
911
        let layout_window =
912
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
913
        let renderer_resources = RendererResources::default();
914
        let previous_window_state: Option<FullWindowState> = None;
915
        let current_window_state = FullWindowState::default();
916
        let gl_context = OptionGlContextPtr::None;
917
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
918
            BTreeMap::new();
919
        let window_handle = RawWindowHandle::Unsupported;
920
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
921

            
922
        let ref_data = CallbackInfoRefData {
923
            layout_window: &layout_window,
924
            renderer_resources: &renderer_resources,
925
            previous_window_state: &previous_window_state,
926
            current_window_state: &current_window_state,
927
            gl_context: &gl_context,
928
            current_scroll_manager: &scroll_states,
929
            current_window_handle: &window_handle,
930
            system_callbacks: &system_callbacks,
931
            system_style: Arc::new(SystemStyle::default()),
932
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
933
            #[cfg(feature = "icu")]
934
            icu_localizer: IcuLocalizerHandle::default(),
935
            ctx: OptionRefAny::None,
936
        };
937

            
938
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
939

            
940
        let info = CallbackInfo::new(
941
            &ref_data,
942
            &changes,
943
            DomNodeId {
944
                dom: DomId::ROOT_ID,
945
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0))),
946
            },
947
            OptionLogicalPosition::None,
948
            OptionLogicalPosition::None,
949
        );
950

            
951
        payloads
952
            .into_iter()
953
            .map(|p| on_tree_node_click(p, info))
954
            .collect()
955
    }
956

            
957
    // ==================================================================
958
    // TreeViewNode::new
959
    // ==================================================================
960

            
961
    #[test]
962
    fn new_defaults_to_a_collapsed_unselected_childless_node() {
963
        let node = TreeViewNode::new("Root");
964

            
965
        assert_eq!(node.label.as_str(), "Root");
966
        assert!(
967
            node.children.as_slice().is_empty(),
968
            "a fresh node has no children"
969
        );
970
        assert_eq!(node.children.len(), 0);
971
        assert!(
972
            node.children.capacity() >= node.children.len(),
973
            "len must never exceed capacity"
974
        );
975
        assert!(!node.is_expanded, "a fresh node is collapsed");
976
        assert!(!node.is_selected, "a fresh node is unselected");
977
    }
978

            
979
    #[test]
980
    fn new_preserves_pathological_labels_byte_for_byte() {
981
        for label in pathological_labels() {
982
            let node = TreeViewNode::new(label.clone());
983
            assert_eq!(
984
                node.label.as_str(),
985
                label.as_str(),
986
                "label must survive verbatim"
987
            );
988
            assert_eq!(
989
                node.label.as_str().len(),
990
                label.len(),
991
                "an embedded NUL must not truncate the label"
992
            );
993
            // …and the state defaults must not depend on the label at all.
994
            assert!(!node.is_expanded);
995
            assert!(!node.is_selected);
996
            assert!(node.children.as_slice().is_empty());
997
        }
998
    }
999

            
    #[test]
    fn new_accepts_every_into_azstring_source_identically() {
        let from_str = TreeViewNode::new("same");
        let from_string = TreeViewNode::new("same".to_string());
        let from_azstring = TreeViewNode::new(AzString::from("same"));
        assert_eq!(from_str, from_string);
        assert_eq!(from_str, from_azstring);
    }
    #[test]
    fn new_with_a_megabyte_label_does_not_truncate_or_panic() {
        let huge = "λ".repeat(500_000); // 1 MB of UTF-8
        let node = TreeViewNode::new(huge.clone());
        assert_eq!(node.label.as_str().len(), huge.len());
        assert_eq!(node.label.as_str(), huge);
    }
    // ==================================================================
    // TreeViewNode::add_child / with_child
    // ==================================================================
    #[test]
    fn add_child_and_with_child_agree() {
        let mut mutated = leaf("root");
        mutated.add_child(leaf("a"));
        mutated.add_child(leaf("b"));
        let built = leaf("root").with_child(leaf("a")).with_child(leaf("b"));
        assert_eq!(
            mutated, built,
            "the builder and the mutator must produce the same node"
        );
    }
    #[test]
    fn add_child_preserves_order_duplicates_and_len_capacity_invariants() {
        let n = 5_000;
        let mut root = leaf("root");
        for i in 0..n {
            root.add_child(leaf(&format!("c{i}")));
            assert_eq!(root.children.len(), i + 1, "len must track every push");
            assert!(
                root.children.capacity() >= root.children.len(),
                "capacity must never fall below len"
            );
        }
        // Order is insertion order, and nothing is deduplicated.
        root.add_child(leaf("c0"));
        assert_eq!(
            root.children.len(),
            n + 1,
            "duplicates are kept, not merged"
        );
        assert_eq!(root.children.as_slice()[0].label.as_str(), "c0");
        assert_eq!(root.children.as_slice()[n - 1].label.as_str(), "c4999");
        assert_eq!(root.children.as_slice()[n].label.as_str(), "c0");
        assert_eq!(subtree_len(&root), n + 2);
    }
    #[test]
    fn child_vec_survives_the_borrowed_to_owned_transition() {
        // `TreeViewNode::new` seeds `children` from a *const* slice (no
        // destructor, zero capacity). The first push has to switch it to an
        // owned heap buffer; a clone taken afterwards must be fully
        // independent, or dropping either one would free the other's memory.
        let mut root = leaf("root");
        assert_eq!(root.children.capacity(), 0);
        root.add_child(leaf("a"));
        root.add_child(leaf("b"));
        let mut copy = root.clone();
        copy.add_child(leaf("c"));
        copy.children.as_mut()[0].label = AzString::from("mutated");
        assert_eq!(root.children.len(), 2, "the original must not see the push");
        assert_eq!(
            root.children.as_slice()[0].label.as_str(),
            "a",
            "the clone must own its own child storage"
        );
        assert_eq!(copy.children.len(), 3);
        assert_eq!(copy.children.as_slice()[0].label.as_str(), "mutated");
        drop(copy);
        // Original still readable after the clone is gone (no shared buffer).
        assert_eq!(root.children.as_slice()[1].label.as_str(), "b");
    }
    #[test]
    fn with_child_nests_arbitrarily_deep_without_panicking() {
        on_big_stack(|| {
            let depth = 1_000;
            let root = chain(depth, true);
            assert_eq!(subtree_len(&root), depth);
            // Deep clone + deep drop both recurse per level as well.
            let copy = root.clone();
            assert_eq!(copy, root);
            drop(copy);
            drop(root);
        });
    }
    // ==================================================================
    // TreeViewNode::with_expanded / with_selected
    // ==================================================================
    #[test]
    fn with_expanded_and_with_selected_are_orthogonal_and_idempotent() {
        for expanded in [false, true] {
            for selected in [false, true] {
                let node = leaf("n").with_expanded(expanded).with_selected(selected);
                assert_eq!(node.is_expanded, expanded);
                assert_eq!(node.is_selected, selected);
                // Order must not matter…
                let flipped = leaf("n").with_selected(selected).with_expanded(expanded);
                assert_eq!(node, flipped);
                // …and applying the same value twice must be a no-op.
                let twice = node.clone().with_expanded(expanded).with_selected(selected);
                assert_eq!(node, twice);
                // The last write wins when the value is flipped.
                let overwritten = node.clone().with_expanded(!expanded);
                assert_eq!(overwritten.is_expanded, !expanded);
                assert_eq!(
                    overwritten.is_selected, selected,
                    "with_expanded must not touch is_selected"
                );
            }
        }
    }
    #[test]
    fn state_builders_do_not_disturb_label_or_children() {
        let base = leaf("keep me").with_child(leaf("a")).with_child(leaf("b"));
        let styled = base
            .clone()
            .with_expanded(true)
            .with_selected(true)
            .with_expanded(false);
        assert_eq!(styled.label, base.label);
        assert_eq!(styled.children, base.children);
        assert!(!styled.is_expanded);
        assert!(styled.is_selected);
    }
    #[test]
    fn nodes_differing_only_in_state_are_not_equal() {
        let base = leaf("n");
        assert_ne!(base, base.clone().with_expanded(true));
        assert_ne!(base, base.clone().with_selected(true));
        assert_ne!(base, base.clone().with_child(leaf("a")));
        assert_ne!(base, leaf("m"));
    }
    #[test]
    fn equality_ignores_how_the_child_vec_was_built() {
        let pushed = leaf("root").with_child(leaf("a")).with_child(leaf("b"));
        let from_vec = TreeViewNode {
            label: AzString::from("root"),
            children: TreeViewNodeVec::from_vec(vec![leaf("a"), leaf("b")]),
            is_expanded: false,
            is_selected: false,
        };
        assert_eq!(
            pushed, from_vec,
            "the vec's allocation strategy must not leak into equality"
        );
    }
    // ==================================================================
    // TreeView::new / set_on_node_click / with_on_node_click
    // ==================================================================
    #[test]
    fn treeview_new_keeps_the_root_intact_and_installs_no_callback() {
        for root in shapes() {
            let tv = TreeView::new(root.clone());
            assert_eq!(tv.root, root, "new must not rewrite the tree");
            assert!(
                tv.on_node_click.as_ref().is_none(),
                "new must not install a callback"
            );
        }
    }
    #[test]
    fn set_on_node_click_installs_then_overwrites() {
        let log = new_log();
        let mut tv = TreeView::new(leaf("root"));
        tv.set_on_node_click(RefAny::new(log.clone()), cb(record_click));
        assert!(tv.on_node_click.as_ref().is_some());
        tv.set_on_node_click(RefAny::new(log.clone()), cb(record_click_all_windows));
        let installed = tv
            .on_node_click
            .as_ref()
            .expect("a callback is still installed");
        assert_eq!(
            installed.callback,
            cb(record_click_all_windows),
            "the last write must win"
        );
        assert_ne!(installed.callback, cb(record_click));
    }
    #[test]
    fn with_on_node_click_matches_set_on_node_click() {
        // Both sides get *clones of the same* `RefAny`: `RefAny`'s equality is
        // shared-identity, so two independent `RefAny::new` calls would never
        // compare equal no matter what the builders do.
        let data = RefAny::new(new_log());
        let mut mutated = TreeView::new(leaf("root"));
        mutated.set_on_node_click(data.clone(), cb(record_click));
        let built = TreeView::new(leaf("root")).with_on_node_click(data.clone(), cb(record_click));
        assert_eq!(mutated, built);
    }
    // ==================================================================
    // count_descendants  (numeric: zero / min-max / overflow)
    // ==================================================================
    #[test]
    fn count_descendants_of_an_empty_slice_is_a_no_op_even_at_usize_max() {
        // usize has no negative domain; the adversarial extremes are 0 and MAX.
        for start in [0usize, 1, usize::MAX / 2, usize::MAX - 1, usize::MAX] {
            let mut index = start;
            count_descendants(&[], &mut index);
            assert_eq!(
                index, start,
                "an empty slice must not touch the counter (and must not overflow at MAX)"
            );
        }
    }
    #[test]
    fn count_descendants_counts_every_node_regardless_of_expansion() {
        for shape in shapes() {
            let nodes = shape.children.as_slice();
            let expected: usize = nodes.iter().map(subtree_len).sum();
            for start in [0usize, 7, 1_000_000] {
                let mut index = start;
                count_descendants(nodes, &mut index);
                assert_eq!(
                    index - start,
                    expected,
                    "collapsed and expanded descendants must count the same"
                );
            }
        }
    }
    #[test]
    fn count_descendants_reaches_exactly_usize_max_without_overflowing() {
        let tree = deep_mixed();
        let nodes = tree.children.as_slice();
        let total: usize = nodes.iter().map(subtree_len).sum();
        let mut index = usize::MAX - total;
        count_descendants(nodes, &mut index);
        assert_eq!(
            index,
            usize::MAX,
            "landing exactly on usize::MAX must not overflow"
        );
    }
    #[test]
    fn count_descendants_survives_a_deep_chain() {
        on_big_stack(|| {
            let depth = 10_000;
            let root = chain(depth, false);
            let mut index = 0usize;
            count_descendants(root.children.as_slice(), &mut index);
            assert_eq!(index, depth - 1, "every hidden descendant is counted once");
        });
    }
    // ==================================================================
    // render_node  (numeric: index accounting)
    // ==================================================================
    #[test]
    fn render_node_advance_equals_subtree_size_for_every_shape() {
        // The load-bearing invariant: whether a subtree is drawn or skipped,
        // it must consume exactly one index per node — otherwise a collapsed
        // sibling shifts every later row's click index.
        for shape in shapes() {
            let expected = subtree_len(&shape);
            for start in [0usize, 1, 12_345, usize::MAX / 4] {
                let mut index = start;
                let mut out = Vec::new();
                render_node(
                    &shape,
                    &OptionTreeViewOnNodeClick::None,
                    &mut index,
                    &mut out,
                );
                assert_eq!(
                    index - start,
                    expected,
                    "index advance must equal the subtree size, expanded or not"
                );
                assert!(!out.is_empty(), "every node renders at least its own row");
            }
        }
    }
    #[test]
    fn render_node_emits_preorder_indices_for_visible_rows_only() {
        for shape in shapes() {
            let log = new_log();
            let on_click = some_click(record_click, &log);
            let mut index = 0usize;
            let mut out = Vec::new();
            render_node(&shape, &on_click, &mut index, &mut out);
            assert_eq!(
                rendered_pairs(&out),
                expected_of(&shape, 0),
                "rendered rows must match the independent pre-order model"
            );
        }
    }
    #[test]
    fn render_node_appends_and_offsets_from_a_nonzero_start_index() {
        let start = 12_345usize;
        let shape = deep_mixed();
        let log = new_log();
        let on_click = some_click(record_click, &log);
        // Pre-existing content in `out` must be preserved, not clobbered.
        let mut out = vec![
            Dom::create_div(),
            Dom::create_text_do_not_use_without_block_level_wrapper("sentinel"),
        ];
        let mut index = start;
        render_node(&shape, &on_click, &mut index, &mut out);
        assert_eq!(
            text_of(&out[1]),
            Some("sentinel"),
            "render_node must append to `out`, never rewrite it"
        );
        assert_eq!(
            rendered_pairs(&out[2..]),
            expected_of(&shape, start),
            "a non-zero start index must offset every emitted index"
        );
        assert_eq!(index, start + subtree_len(&shape));
    }
    #[test]
    fn render_node_lands_exactly_on_usize_max_without_overflowing() {
        // Three nodes, started so the *last* index handed out is usize::MAX - 1
        // and the counter finishes on usize::MAX: one node short of the cliff.
        let tree = leaf("root")
            .with_child(leaf("a"))
            .with_child(leaf("b"))
            .with_expanded(true);
        assert_eq!(subtree_len(&tree), 3);
        let log = new_log();
        let on_click = some_click(record_click, &log);
        let mut index = usize::MAX - 3;
        let mut out = Vec::new();
        render_node(&tree, &on_click, &mut index, &mut out);
        assert_eq!(index, usize::MAX, "must land exactly on MAX, not wrap");
        let indices: Vec<usize> = rows_of(&out)
            .iter()
            .filter_map(|r| click_index_of(r))
            .collect();
        assert_eq!(
            indices,
            vec![usize::MAX - 3, usize::MAX - 2, usize::MAX - 1],
            "extreme indices must be carried verbatim into the click payloads"
        );
    }
    #[cfg(all(debug_assertions, panic = "unwind"))]
    #[test]
    fn render_node_index_overflow_is_loud_not_silently_wrapped() {
        // `render_node` does an unguarded `*index += 1`. Starting at
        // usize::MAX must not quietly wrap the counter to 0 (which would give
        // two different rows the same click index); an overflow-checked build
        // has to panic instead.
        let node = leaf("boom");
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let mut index = usize::MAX;
            let mut out = Vec::new();
            render_node(
                &node,
                &OptionTreeViewOnNodeClick::None,
                &mut index,
                &mut out,
            );
            index
        }));
        match result {
            Err(_) => {} // overflow-checked build: panicked, as required
            Ok(index) => assert_eq!(
                index, 0,
                "without overflow checks the counter must wrap cleanly, not corrupt"
            ),
        }
    }
    #[test]
    fn render_node_without_a_callback_attaches_none() {
        for shape in shapes() {
            let mut index = 0usize;
            let mut out = Vec::new();
            render_node(
                &shape,
                &OptionTreeViewOnNodeClick::None,
                &mut index,
                &mut out,
            );
            for row in rows_of(&out) {
                assert!(
                    row.root.get_callbacks().as_ref().is_empty(),
                    "no callback configured => no callback attached"
                );
            }
        }
    }
    #[test]
    fn render_node_survives_a_deep_expanded_chain() {
        on_big_stack(|| {
            let depth = 800;
            let root = chain(depth, true);
            let mut index = 0usize;
            let mut out = Vec::new();
            render_node(
                &root,
                &OptionTreeViewOnNodeClick::None,
                &mut index,
                &mut out,
            );
            assert_eq!(index, depth, "one index per level");
            assert_eq!(rows_of(&out).len(), depth, "every level renders one row");
            drop(out);
        });
    }
    #[test]
    fn render_node_handles_a_wide_fanout() {
        let n = 5_000;
        let root = wide(n, true);
        let log = new_log();
        let on_click = some_click(record_click, &log);
        let mut index = 0usize;
        let mut out = Vec::new();
        render_node(&root, &on_click, &mut index, &mut out);
        assert_eq!(index, n + 1);
        assert_eq!(out.len(), 2, "an expanded parent emits [row, container]");
        assert_eq!(out[1].children.as_ref().len(), n, "every child gets a row");
        let indices: Vec<usize> = rows_of(&out)
            .iter()
            .filter_map(|r| click_index_of(r))
            .collect();
        assert_eq!(indices, (0..=n).collect::<Vec<_>>());
    }
    // ==================================================================
    // TreeView::dom
    // ==================================================================
    #[test]
    fn dom_root_carries_the_container_class_and_style() {
        let dom = TreeView::new(leaf("root")).dom();
        let classes = dom.root.get_ids_and_classes();
        assert!(
            classes
                .as_ref()
                .iter()
                .any(|c| matches!(c, Class(s) if s.as_str() == "__azul-native-tree-view")),
            "the container must be findable by its widget class"
        );
        assert!(
            style_is(&dom, TREE_CONTAINER_STYLE),
            "the container must use the shared const style"
        );
    }
    #[test]
    fn dom_leaf_renders_a_spacer_and_no_icon() {
        let dom = TreeView::new(leaf("only")).dom();
        assert_eq!(dom.children.as_ref().len(), 1, "a leaf emits just its row");
        let row = &dom.children.as_ref()[0];
        let (icon, label) = row_parts(row);
        assert_eq!(
            icon_of(icon),
            None,
            "a childless node gets no disclosure icon"
        );
        assert!(
            style_is(icon, LEAF_SPACER_STYLE),
            "the placeholder must use the leaf-spacer style so labels stay aligned"
        );
        assert_eq!(text_of(label), Some("only"));
        assert!(style_is(label, LABEL_STYLE));
    }
    #[test]
    fn dom_expanded_parent_uses_expand_more_and_emits_a_container() {
        let tree = leaf("p")
            .with_child(leaf("a"))
            .with_child(leaf("b"))
            .with_expanded(true);
        let dom = TreeView::new(tree).dom();
        assert_eq!(
            dom.children.as_ref().len(),
            2,
            "an expanded parent emits [row, children container]"
        );
        let (icon, _) = row_parts(&dom.children.as_ref()[0]);
        assert_eq!(icon_of(icon), Some("expand_more"));
        assert!(style_is(icon, ICON_STYLE));
        let container = &dom.children.as_ref()[1];
        assert!(style_is(container, CHILDREN_STYLE));
        assert_eq!(container.children.as_ref().len(), 2, "both children drawn");
    }
    #[test]
    fn dom_collapsed_parent_uses_chevron_and_draws_no_children() {
        let tree = leaf("p").with_child(leaf("a")).with_child(leaf("b"));
        let dom = TreeView::new(tree).dom();
        assert_eq!(
            dom.children.as_ref().len(),
            1,
            "a collapsed parent must not emit a children container"
        );
        let (icon, _) = row_parts(&dom.children.as_ref()[0]);
        assert_eq!(icon_of(icon), Some("chevron_right"));
        assert_eq!(
            rows_of(dom.children.as_ref()).len(),
            1,
            "children stay hidden"
        );
    }
    #[test]
    fn dom_expanded_but_childless_node_still_renders_a_spacer() {
        // `is_expanded` is documented as meaningful only with children.
        let dom = TreeView::new(leaf("empty").with_expanded(true)).dom();
        assert_eq!(dom.children.as_ref().len(), 1, "nothing to expand into");
        let (icon, _) = row_parts(&dom.children.as_ref()[0]);
        assert_eq!(icon_of(icon), None);
        assert!(style_is(icon, LEAF_SPACER_STYLE));
    }
    #[test]
    fn dom_selected_rows_use_the_selected_style() {
        let tree = leaf("p")
            .with_expanded(true)
            .with_child(leaf("a").with_selected(true))
            .with_child(leaf("b"));
        let dom = TreeView::new(tree).dom();
        let rows = rows_of(dom.children.as_ref());
        assert_eq!(rows.len(), 3);
        assert!(
            style_is(rows[0], ROW_STYLE),
            "unselected root uses ROW_STYLE"
        );
        assert!(
            style_is(rows[1], ROW_SELECTED_STYLE),
            "the selected node must switch to the selected style"
        );
        assert!(style_is(rows[2], ROW_STYLE));
        assert!(
            !style_is(rows[1], ROW_STYLE),
            "the two row styles must be distinguishable"
        );
    }
    #[test]
    fn dom_keeps_estimated_total_children_consistent_for_every_shape() {
        // A stale estimate makes `convert_dom_into_compact_dom` under-allocate
        // and panic out of bounds, so this is a crash invariant, not cosmetics.
        for shape in shapes() {
            let dom = TreeView::new(shape).dom();
            assert_estimates_consistent(&dom);
        }
    }
    #[test]
    fn dom_labels_survive_the_round_trip_unchanged() {
        let labels = pathological_labels();
        let mut root = leaf("root").with_expanded(true);
        for l in &labels {
            root.add_child(TreeViewNode::new(l.clone()));
        }
        let dom = TreeView::new(root).dom();
        let rows = rows_of(dom.children.as_ref());
        assert_eq!(rows.len(), labels.len() + 1);
        let rendered: Vec<&str> = rows[1..]
            .iter()
            .map(|r| text_of(row_parts(r).1).expect("label text node"))
            .collect();
        let expected: Vec<&str> = labels.iter().map(String::as_str).collect();
        assert_eq!(rendered, expected, "labels must survive byte-for-byte");
    }
    #[test]
    fn dom_rows_are_focusable_and_carry_exactly_one_click_callback() {
        let log = new_log();
        let tv = TreeView::new(deep_mixed())
            .with_on_node_click(RefAny::new(log.clone()), cb(record_click));
        let dom = tv.dom();
        for row in rows_of(dom.children.as_ref()) {
            assert!(
                matches!(row.root.get_tab_index(), Some(TabIndex::Auto)),
                "every row must be keyboard focusable"
            );
            let cbs = row.root.get_callbacks();
            assert_eq!(cbs.as_ref().len(), 1, "exactly one click callback per row");
            assert_eq!(
                cbs.as_ref()[0].event,
                EventFilter::Hover(HoverEventFilter::Click),
                "rows fire on mouse-up"
            );
        }
    }
    #[test]
    fn dom_indices_skip_collapsed_subtrees_but_stay_preorder() {
        for shape in shapes() {
            let log = new_log();
            let dom = TreeView::new(shape.clone())
                .with_on_node_click(RefAny::new(log.clone()), cb(record_click))
                .dom();
            assert_eq!(
                rendered_pairs(dom.children.as_ref()),
                expected_of(&shape, 0),
                "dom() must index nodes pre-order over the whole tree, including the collapsed \
                 ones it does not draw"
            );
        }
    }
    #[test]
    fn dom_of_an_empty_labelled_tree_does_not_panic() {
        let dom = TreeView::new(leaf("")).dom();
        let rows = rows_of(dom.children.as_ref());
        assert_eq!(rows.len(), 1);
        assert_eq!(text_of(row_parts(rows[0]).1), Some(""));
    }
    #[test]
    fn from_treeview_for_dom_matches_dom() {
        for shape in shapes() {
            let via_trait: Dom = TreeView::new(shape.clone()).into();
            let via_method = TreeView::new(shape).dom();
            assert_eq!(via_trait, via_method);
        }
    }
    #[test]
    fn dom_survives_a_deep_expanded_chain() {
        on_big_stack(|| {
            let depth = 800;
            let dom = TreeView::new(chain(depth, true)).dom();
            assert_eq!(rows_of(dom.children.as_ref()).len(), depth);
            assert_estimates_consistent(&dom);
            drop(dom);
        });
    }
    // ==================================================================
    // on_tree_node_click
    // ==================================================================
    #[test]
    fn click_with_a_foreign_payload_returns_do_nothing() {
        // A `RefAny` of the wrong type must be rejected, not reinterpreted.
        let payloads = vec![
            RefAny::new(0usize),
            RefAny::new(String::from("not a NodeClickData")),
            RefAny::new(leaf("also not one")),
            RefAny::new(()),
        ];
        let updates = run_clicks(payloads);
        assert_eq!(
            updates,
            vec![Update::DoNothing; 4],
            "a foreign payload must be a no-op, not a panic or a wild call"
        );
    }
    #[test]
    fn click_without_a_user_callback_returns_do_nothing() {
        let payloads = vec![
            RefAny::new(NodeClickData {
                node_index: 0,
                on_node_click: OptionTreeViewOnNodeClick::None,
            }),
            RefAny::new(NodeClickData {
                node_index: usize::MAX,
                on_node_click: OptionTreeViewOnNodeClick::None,
            }),
        ];
        assert_eq!(run_clicks(payloads), vec![Update::DoNothing; 2]);
    }
    #[test]
    fn click_forwards_the_index_verbatim_including_the_extremes() {
        let log = new_log();
        let indices = vec![0usize, 1, usize::MAX / 2, usize::MAX - 1, usize::MAX];
        let payloads: Vec<RefAny> = indices
            .iter()
            .map(|i| {
                RefAny::new(NodeClickData {
                    node_index: *i,
                    on_node_click: some_click(record_click, &log),
                })
            })
            .collect();
        let updates = run_clicks(payloads);
        assert_eq!(updates, vec![Update::RefreshDom; 5]);
        assert_eq!(
            entries(&log),
            indices,
            "the node index must reach the user callback unmodified"
        );
    }
    #[test]
    fn click_propagates_the_user_update_verbatim() {
        let log = new_log();
        let payloads = vec![
            RefAny::new(NodeClickData {
                node_index: 3,
                on_node_click: some_click(record_click, &log),
            }),
            RefAny::new(NodeClickData {
                node_index: 4,
                on_node_click: some_click(record_click_all_windows, &log),
            }),
        ];
        assert_eq!(
            run_clicks(payloads),
            vec![Update::RefreshDom, Update::RefreshDomAllWindows],
            "the dispatcher must not downgrade or upgrade the user's Update"
        );
        assert_eq!(entries(&log), vec![3, 4 + SENTINEL]);
    }
    #[test]
    fn clicking_every_rendered_row_reports_its_visual_index() {
        let shape = deep_mixed();
        let log = new_log();
        let dom = TreeView::new(shape.clone())
            .with_on_node_click(RefAny::new(log.clone()), cb(record_click))
            .dom();
        let payloads: Vec<RefAny> = rows_of(dom.children.as_ref())
            .iter()
            .map(|row| {
                row.root
                    .get_callbacks()
                    .as_ref()
                    .first()
                    .expect("every row carries the click callback")
                    .refany
                    .clone()
            })
            .collect();
        let expected: Vec<usize> = expected_of(&shape, 0).into_iter().map(|(i, _)| i).collect();
        let updates = run_clicks(payloads);
        assert_eq!(updates, vec![Update::RefreshDom; expected.len()]);
        assert_eq!(
            entries(&log),
            expected,
            "clicking row N must report N's pre-order index, collapsed siblings included"
        );
    }
}