1
//! Breadcrumb widget — a horizontal path-navigation trail: a row of clickable
2
//! crumb links separated by a "/" glyph, where the last crumb is the current
3
//! page (non-clickable, muted + bold). A blend of [`crate::widgets::segmented::Segmented`]
4
//! (the horizontal row of clickable text nodes whose clicked index is derived
5
//! from sibling position) and [`crate::widgets::button::Button`]'s `Link` look
6
//! (blue, pointer cursor) for the crumb links.
7
//!
8
//! Clicking a crumb invokes the user's `on_navigate(index)` carrying the clicked
9
//! crumb's index in [`BreadcrumbState`] (exactly how segmented carries its
10
//! selected index). Unlike segmented there is no persistent selection to
11
//! re-style: navigating a breadcrumb is expected to rebuild the page, so the
12
//! handler only reports the index and does not live-restyle.
13
//!
14
//! Index derivation: the children alternate `crumb, separator, crumb, separator,
15
//! …, current`, so crumb `i` sits at sibling position `2*i`; the handler computes
16
//! `index = position / 2`. Separators and the final current crumb carry no
17
//! callback, so the hit node is always a clickable crumb (an even position).
18
//!
19
//! Key types: [`Breadcrumb`], [`BreadcrumbState`], [`BreadcrumbOnNavigate`].
20

            
21
use std::vec::Vec;
22

            
23
use azul_core::{
24
    callbacks::{CoreCallbackData, Update},
25
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec, TabIndex},
26
    refany::RefAny,
27
};
28
use azul_css::{
29
    dynamic_selector::{
30
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
31
    },
32
    impl_option_inner,
33
    props::{
34
        basic::{color::ColorU, StyleFontSize, StyleFontWeight},
35
        layout::{
36
            LayoutAlignItems, LayoutAlignSelf, LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow,
37
            LayoutMarginLeft, LayoutMarginRight,
38
        },
39
        property::{CssProperty, *},
40
        style::{StyleCursor, StyleTextColor, StyleUserSelect},
41
    },
42
    AzString, StringVec,
43
};
44

            
45
use crate::callbacks::{Callback, CallbackInfo};
46

            
47
static BREADCRUMB_CLASS: &[IdOrClass] =
48
    &[Class(AzString::from_const_str("__azul-native-breadcrumb"))];
49
static BREADCRUMB_ITEM_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
50
    "__azul-native-breadcrumb-item",
51
))];
52
static BREADCRUMB_CURRENT_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
53
    "__azul-native-breadcrumb-current",
54
))];
55
static BREADCRUMB_SEPARATOR_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
56
    "__azul-native-breadcrumb-separator",
57
))];
58

            
59
/// Separator glyph rendered between crumbs.
60
const SEPARATOR_GLYPH: AzString = AzString::from_const_str("/");
61

            
62
/// Callback function type invoked when a (non-current) crumb is clicked.
63
pub type BreadcrumbOnNavigateCallbackType =
64
    extern "C" fn(RefAny, CallbackInfo, BreadcrumbState) -> Update;
65
impl_widget_callback!(
66
    BreadcrumbOnNavigate,
67
    OptionBreadcrumbOnNavigate,
68
    BreadcrumbOnNavigateCallback,
69
    BreadcrumbOnNavigateCallbackType
70
);
71

            
72
azul_core::impl_managed_callback! {
73
    wrapper:        BreadcrumbOnNavigateCallback,
74
    info_ty:        CallbackInfo,
75
    return_ty:      Update,
76
    default_ret:    Update::DoNothing,
77
    invoker_static: BREADCRUMB_ON_NAVIGATE_INVOKER,
78
    invoker_ty:     AzBreadcrumbOnNavigateCallbackInvoker,
79
    thunk_fn:       az_breadcrumb_on_navigate_callback_thunk,
80
    setter_fn:      AzApp_setBreadcrumbOnNavigateCallbackInvoker,
81
    from_handle_fn: AzBreadcrumbOnNavigateCallback_createFromHostHandle,
82
    extra_args:     [ state: BreadcrumbState ],
83
}
84

            
85
/// A horizontal trail of clickable crumb links ending in the current page.
86
#[derive(Debug, Clone, PartialEq, Eq)]
87
#[repr(C)]
88
pub struct Breadcrumb {
89
    pub breadcrumb_state: BreadcrumbStateWrapper,
90
    /// The crumb labels, in order (the last is the current, non-clickable page).
91
    pub labels: StringVec,
92
    /// Style for the row container, or `None` for "no opinion" — in which case
93
    /// the widget's default applies.
94
    ///
95
    /// `None` and `Some(empty)` are different answers: the first means the
96
    /// widget picks, the second means the caller asked for no properties at all
97
    /// and gets none.
98
    pub container_style: OptionCssPropertyWithConditionsVec,
99
}
100

            
101
#[derive(Debug, Default, Clone, PartialEq, Eq)]
102
#[repr(C)]
103
pub struct BreadcrumbStateWrapper {
104
    /// The last-clicked crumb index.
105
    pub inner: BreadcrumbState,
106
    /// Optional: function to call when a crumb is clicked.
107
    pub on_navigate: OptionBreadcrumbOnNavigate,
108
}
109

            
110
/// State of a [`Breadcrumb`]: the index of the most recently clicked crumb.
111
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
112
#[repr(C)]
113
pub struct BreadcrumbState {
114
    /// Zero-based index of the clicked crumb.
115
    pub selected_index: usize,
116
}
117

            
118
// ---- colours ----
119
/// Crumb-link colour (#0d6efd, Bootstrap link blue).
120
const LINK_COLOR: ColorU = ColorU {
121
    r: 13,
122
    g: 110,
123
    b: 253,
124
    a: 255,
125
};
126
/// Current-crumb colour (#495057, muted dark grey).
127
const CURRENT_COLOR: ColorU = ColorU {
128
    r: 73,
129
    g: 80,
130
    b: 87,
131
    a: 255,
132
};
133
/// Separator colour (#6c757d, grey).
134
const SEPARATOR_COLOR: ColorU = ColorU {
135
    r: 108,
136
    g: 117,
137
    b: 125,
138
    a: 255,
139
};
140

            
141
/// Row container: a horizontal flex row that hugs its content.
142
static BREADCRUMB_CONTAINER_STYLE: &[CssPropertyWithConditions] = &[
143
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
144
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
145
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
146
    CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Start)),
147
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
148
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(14))),
149
];
150

            
151
/// Clickable crumb-link style (blue, pointer cursor). A hover underline is
152
/// omitted to keep the style a const slice (`TextDecoration::Underline.into()`
153
/// is not const); the link colour + pointer already read clearly as a link.
154
static BREADCRUMB_ITEM_STYLE: &[CssPropertyWithConditions] = &[
155
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
156
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
157
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
158
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
159
        inner: LINK_COLOR,
160
    })),
161
];
162

            
163
/// Current (last) crumb style: muted dark, bold, not clickable.
164
static BREADCRUMB_CURRENT_STYLE: &[CssPropertyWithConditions] = &[
165
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
166
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
167
    CssPropertyWithConditions::simple(CssProperty::font_weight(StyleFontWeight::Bold)),
168
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
169
        inner: CURRENT_COLOR,
170
    })),
171
];
172

            
173
/// Separator-glyph style: grey, with a small horizontal gap on each side.
174
static BREADCRUMB_SEPARATOR_STYLE: &[CssPropertyWithConditions] = &[
175
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
176
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
177
    CssPropertyWithConditions::simple(CssProperty::const_margin_left(LayoutMarginLeft::const_px(
178
        8,
179
    ))),
180
    CssPropertyWithConditions::simple(CssProperty::const_margin_right(
181
        LayoutMarginRight::const_px(8),
182
    )),
183
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
184
        inner: SEPARATOR_COLOR,
185
    })),
186
];
187

            
188
impl Breadcrumb {
189
    /// Creates a breadcrumb from the given labels (the last is the current page).
190
    #[must_use]
191
354
    pub fn create(labels: StringVec) -> Self {
192
354
        Self {
193
354
            breadcrumb_state: BreadcrumbStateWrapper::default(),
194
354
            labels,
195
354
            container_style: OptionCssPropertyWithConditionsVec::None,
196
354
        }
197
354
    }
198

            
199
    /// The container CSS this breadcrumb renders with.
200
    ///
201
    /// `None` means no opinion, so the widget's default applies — the same
202
    /// answer both themes give, asked in one place so they cannot drift.
203
    #[must_use]
204
41
    pub fn resolved_container_style(&self) -> CssPropertyWithConditionsVec {
205
41
        self.container_style
206
41
            .clone()
207
41
            .into_option()
208
41
            .unwrap_or_else(|| {
209
41
                CssPropertyWithConditionsVec::from_const_slice(BREADCRUMB_CONTAINER_STYLE)
210
41
            })
211
41
    }
212

            
213
    #[inline]
214
    #[must_use]
215
104
    pub fn swap_with_default(&mut self) -> Self {
216
104
        let mut s = Self::create(StringVec::from_const_slice(&[]));
217
104
        core::mem::swap(&mut s, self);
218
104
        s
219
104
    }
220

            
221
    #[inline]
222
8
    pub fn set_on_navigate<C: Into<BreadcrumbOnNavigateCallback>>(
223
8
        &mut self,
224
8
        data: RefAny,
225
8
        on_navigate: C,
226
8
    ) {
227
8
        self.breadcrumb_state.on_navigate = Some(BreadcrumbOnNavigate {
228
8
            callback: on_navigate.into(),
229
8
            refany: data,
230
8
        })
231
8
        .into();
232
8
    }
233

            
234
    #[inline]
235
    #[must_use]
236
6
    pub fn with_on_navigate<C: Into<BreadcrumbOnNavigateCallback>>(
237
6
        mut self,
238
6
        data: RefAny,
239
6
        on_navigate: C,
240
6
    ) -> Self {
241
6
        self.set_on_navigate(data, on_navigate);
242
6
        self
243
6
    }
244

            
245
    #[must_use]
246
34
    pub fn dom(self) -> Dom {
247
        use azul_core::{
248
            callbacks::CoreCallback,
249
            dom::{EventFilter, HoverEventFilter},
250
            refany::OptionRefAny,
251
        };
252

            
253
34
        let count = self.labels.as_ref().len();
254
        // Resolved before `self.breadcrumb_state` is moved out below.
255
34
        let container_style = self.resolved_container_style();
256

            
257
        // One shared RefAny across every crumb callback (RefAny::clone shares the
258
        // underlying state — same pattern as segmented/tabs/map).
259
34
        let state = RefAny::new(self.breadcrumb_state);
260

            
261
34
        let mut children: Vec<Dom> = Vec::with_capacity(count.saturating_mul(2));
262
664
        for (i, label) in self.labels.as_ref().iter().enumerate() {
263
664
            let is_last = i + 1 == count;
264

            
265
664
            if is_last {
266
31
                // The current page: muted + bold, non-clickable (no callback).
267
31
                children.push(
268
31
                    crate::widgets::widget_p_with_text(label.clone())
269
31
                        .with_ids_and_classes(IdOrClassVec::from_const_slice(
270
31
                            BREADCRUMB_CURRENT_CLASS,
271
31
                        ))
272
31
                        .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
273
31
                            BREADCRUMB_CURRENT_STYLE,
274
31
                        )),
275
31
                );
276
633
            } else {
277
633
                // A clickable crumb link.
278
633
                children.push(
279
633
                    crate::widgets::widget_p_with_text(label.clone())
280
633
                        .with_ids_and_classes(IdOrClassVec::from_const_slice(BREADCRUMB_ITEM_CLASS))
281
633
                        .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
282
633
                            BREADCRUMB_ITEM_STYLE,
283
633
                        ))
284
633
                        .with_callbacks(
285
633
                            vec![CoreCallbackData {
286
633
                                event: EventFilter::Hover(HoverEventFilter::Click),
287
633
                                callback: CoreCallback {
288
633
                                    cb: on_crumb_click as usize,
289
633
                                    ctx: OptionRefAny::None,
290
633
                                },
291
633
                                refany: state.clone(),
292
633
                            }]
293
633
                            .into(),
294
633
                        )
295
633
                        .with_tab_index(TabIndex::Auto)
296
633
            // Role so the accessibility tree knows what this IS:
297
633
            // each crumb navigates. The NAME comes from the widget's own text,
298
633
            // which azul derives when a readable label is present.
299
633
            .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
300
633
                role: azul_core::a11y::AccessibilityRole::Link,
301
633
                ..Default::default()
302
633
            }),
303
633
                );
304
633
                // Separator after every non-last crumb.
305
633
                children.push(
306
633
                    crate::widgets::widget_p_with_text(SEPARATOR_GLYPH)
307
633
                        .with_ids_and_classes(IdOrClassVec::from_const_slice(
308
633
                            BREADCRUMB_SEPARATOR_CLASS,
309
633
                        ))
310
633
                        .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
311
633
                            BREADCRUMB_SEPARATOR_STYLE,
312
633
                        )),
313
633
                );
314
633
            }
315
        }
316

            
317
34
        Dom::create_div()
318
34
            .with_ids_and_classes(IdOrClassVec::from_const_slice(BREADCRUMB_CLASS))
319
34
            .with_css_props(container_style)
320
34
            .with_children(children.into())
321
34
    }
322
}
323

            
324
impl Default for Breadcrumb {
325
203
    fn default() -> Self {
326
203
        Self::create(StringVec::from_const_slice(&[]))
327
203
    }
328
}
329

            
330
/// Click handler shared by all crumb links. Determines the clicked crumb's index
331
/// from its position among its siblings (`index = position / 2`, since the
332
/// children alternate crumb/separator), updates the state, and invokes the user
333
/// `on_navigate` callback. No live restyle — navigating is expected to rebuild
334
/// the page.
335
17
extern "C" fn on_crumb_click(mut data: RefAny, mut info: CallbackInfo) -> Update {
336
    use azul_core::dom::DomNodeId;
337

            
338
17
    let clicked = info.get_hit_node();
339
17
    let Some(parent) = info.get_parent(clicked) else {
340
3
        return Update::DoNothing;
341
    };
342

            
343
    // Collect the children in document order, then find the clicked crumb's slot.
344
14
    let mut siblings: Vec<DomNodeId> = Vec::new();
345
14
    let mut cur = info.get_first_child(parent);
346
216
    while let Some(node) = cur {
347
202
        siblings.push(node);
348
202
        cur = info.get_next_sibling(node);
349
202
    }
350

            
351
163
    let Some(pos) = siblings.iter().position(|n| *n == clicked) else {
352
        return Update::DoNothing;
353
    };
354
    // Crumbs sit at even positions (crumb, separator, crumb, separator, …).
355
14
    let index = pos / 2;
356

            
357
14
    let Some(mut bc) = data.downcast_mut::<BreadcrumbStateWrapper>() else {
358
2
        return Update::DoNothing;
359
    };
360
12
    bc.inner.selected_index = index;
361
12
    let inner = bc.inner;
362
12
    let bc = &mut *bc;
363
12
    match bc.on_navigate.as_mut() {
364
4
        Some(BreadcrumbOnNavigate { callback, refany }) => {
365
4
            (callback.cb)(refany.clone(), info, inner)
366
        }
367
8
        None => Update::DoNothing,
368
    }
369
17
}
370

            
371
impl From<Breadcrumb> for Dom {
372
    fn from(b: Breadcrumb) -> Self {
373
        b.dom()
374
    }
375
}
376

            
377
#[cfg(test)]
378
mod autotest_generated {
379
    use std::{
380
        collections::{BTreeMap, HashMap},
381
        sync::{Arc, Mutex},
382
    };
383

            
384
    use azul_core::{
385
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, NodeId, NodeType},
386
        geom::{LogicalRect, OptionLogicalPosition},
387
        gl::OptionGlContextPtr,
388
        hit_test::ScrollPosition,
389
        refany::OptionRefAny,
390
        resources::RendererResources,
391
        styled_dom::{NodeHierarchyItemId, StyledDom},
392
        window::{MonitorVec, RawWindowHandle},
393
    };
394
    use azul_css::system::SystemStyle;
395
    use rust_fontconfig::FcFontCache;
396

            
397
    use super::*;
398
    #[cfg(feature = "icu")]
399
    use crate::icu::IcuLocalizerHandle;
400
    use crate::{
401
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
402
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
403
        window::{DomLayoutResult, LayoutWindow},
404
        window_state::FullWindowState,
405
    };
406

            
407
    // ------------------------------------------------------------------
408
    // Helpers
409
    // ------------------------------------------------------------------
410

            
411
    fn labels(v: &[&str]) -> StringVec {
412
        StringVec::from_vec(v.iter().map(|s| AzString::from(*s)).collect::<Vec<_>>())
413
    }
414

            
415
    /// `n` distinct labels: `c0, c1, … c{n-1}`.
416
    fn n_labels(n: usize) -> StringVec {
417
        StringVec::from_vec(
418
            (0..n)
419
                .map(|i| AzString::from(format!("c{i}")))
420
                .collect::<Vec<_>>(),
421
        )
422
    }
423

            
424
    /// The text of a text node, looking through the `<p>` block wrapper the
425
    /// label convention mandates (`p > text`).
426
    fn text_of(node: &Dom) -> Option<&str> {
427
        match node.root.get_node_type() {
428
            NodeType::Text(s) => Some(s.as_ref().as_str()),
429
            NodeType::P => match node.children.as_ref() {
430
                [only] => match only.root.get_node_type() {
431
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
432
                    _ => None,
433
                },
434
                _ => None,
435
            },
436
            _ => None,
437
        }
438
    }
439

            
440
    /// The true recursive descendant count of a `Dom` — what
441
    /// `estimated_total_children` is documented to cache.
442
    fn recursive_descendants(node: &Dom) -> usize {
443
        node.children
444
            .as_ref()
445
            .iter()
446
            .map(|c| 1 + recursive_descendants(c))
447
            .sum()
448
    }
449

            
450
    /// The `color` (text colour) declared by a style slice.
451
    fn text_color(style: &[CssPropertyWithConditions]) -> Option<ColorU> {
452
        style.iter().find_map(|p| match &p.property {
453
            CssProperty::TextColor(v) => v.get_property().map(|c| c.inner),
454
            _ => None,
455
        })
456
    }
457

            
458
    fn has_property(style: &[CssPropertyWithConditions], wanted: &CssProperty) -> bool {
459
        style.iter().any(|p| p.property == *wanted)
460
    }
461

            
462
    fn has_cursor(style: &[CssPropertyWithConditions]) -> bool {
463
        style
464
            .iter()
465
            .any(|p| matches!(&p.property, CssProperty::Cursor(_)))
466
    }
467

            
468
    /// A `RefAny` payload recording every index a user `on_navigate` sees.
469
    struct NavLog {
470
        seen: Vec<usize>,
471
    }
472

            
473
    extern "C" fn record_nav(mut data: RefAny, _: CallbackInfo, state: BreadcrumbState) -> Update {
474
        if let Some(mut log) = data.downcast_mut::<NavLog>() {
475
            log.seen.push(state.selected_index);
476
        }
477
        Update::RefreshDom
478
    }
479

            
480
    extern "C" fn nav_do_nothing(_: RefAny, _: CallbackInfo, _: BreadcrumbState) -> Update {
481
        Update::DoNothing
482
    }
483

            
484
    extern "C" fn nav_refresh_all(_: RefAny, _: CallbackInfo, _: BreadcrumbState) -> Update {
485
        Update::RefreshDomAllWindows
486
    }
487

            
488
    /// Forces the `fn`-item -> `fn`-pointer coercion the `Into` bound needs.
489
    fn nav_cb(f: BreadcrumbOnNavigateCallbackType) -> BreadcrumbOnNavigateCallback {
490
        f.into()
491
    }
492

            
493
    fn log_indices(data: &mut RefAny) -> Vec<usize> {
494
        data.downcast_ref::<NavLog>()
495
            .expect("payload must still be a NavLog")
496
            .seen
497
            .clone()
498
    }
499

            
500
    fn selected_index_of(data: &mut RefAny) -> usize {
501
        data.downcast_ref::<BreadcrumbStateWrapper>()
502
            .expect("payload must still be a BreadcrumbStateWrapper")
503
            .inner
504
            .selected_index
505
    }
506

            
507
    /// The `RefAny` carried by crumb `i`'s click callback (crumbs sit at even
508
    /// child positions).
509
    fn crumb_state(dom: &Dom, crumb: usize) -> RefAny {
510
        let cbs = dom.children.as_ref()[crumb * 2].root.get_callbacks();
511
        cbs.as_ref()
512
            .first()
513
            .expect("a non-last crumb must carry the click callback")
514
            .refany
515
            .clone()
516
    }
517

            
518
    /// A `DomLayoutResult` with an *empty* layout tree: `on_crumb_click` only
519
    /// walks `styled_dom.node_hierarchy`, so no real layout (and no font) is needed.
520
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
521
        DomLayoutResult {
522
            styled_dom,
523
            layout_tree: LayoutTree {
524
                nodes: Vec::new(),
525
                warm: Vec::new(),
526
                cold: Vec::new(),
527
                root: 0,
528
                dom_to_layout: BTreeMap::new(),
529
                children_arena: Vec::new(),
530
                children_offsets: Vec::new(),
531
                subtree_needs_intrinsic: Vec::new(),
532
            },
533
            calculated_positions: Vec::new(),
534
            viewport: LogicalRect::zero(),
535
            display_list: Arc::new(DisplayList::default()),
536
            scroll_ids: HashMap::new(),
537
            scroll_id_to_node_id: HashMap::new(),
538
        }
539
    }
540

            
541
    /// Flattens `bc.dom()` and hands back the shared state `RefAny` the crumb
542
    /// callbacks carry. Requires >= 2 labels (so that crumb 0 is clickable).
543
    fn flatten(bc: Breadcrumb) -> (StyledDom, RefAny) {
544
        let dom = bc.dom();
545
        let state = crumb_state(&dom, 0);
546
        (StyledDom::create_from_dom(dom), state)
547
    }
548

            
549
    /// Invokes `on_crumb_click` against a `LayoutWindow` holding `styled` (or
550
    /// nothing at all, when `styled` is `None`), with node `hit` as the hit node.
551
    /// Returns the `Update` plus every recorded `CallbackChange`.
552
    fn run_click(
553
        styled: Option<StyledDom>,
554
        hit: usize,
555
        data: RefAny,
556
    ) -> (Update, Vec<CallbackChange>) {
557
        let mut layout_window =
558
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
559
        if let Some(sd) = styled {
560
            layout_window
561
                .layout_results
562
                .insert(DomId::ROOT_ID, layout_result(sd));
563
        }
564

            
565
        let renderer_resources = RendererResources::default();
566
        let previous_window_state: Option<FullWindowState> = None;
567
        let current_window_state = FullWindowState::default();
568
        let gl_context = OptionGlContextPtr::None;
569
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
570
            BTreeMap::new();
571
        let window_handle = RawWindowHandle::Unsupported;
572
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
573

            
574
        let ref_data = CallbackInfoRefData {
575
            layout_window: &layout_window,
576
            renderer_resources: &renderer_resources,
577
            previous_window_state: &previous_window_state,
578
            current_window_state: &current_window_state,
579
            gl_context: &gl_context,
580
            current_scroll_manager: &scroll_states,
581
            current_window_handle: &window_handle,
582
            system_callbacks: &system_callbacks,
583
            system_style: Arc::new(SystemStyle::default()),
584
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
585
            #[cfg(feature = "icu")]
586
            icu_localizer: IcuLocalizerHandle::default(),
587
            ctx: OptionRefAny::None,
588
        };
589

            
590
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
591

            
592
        let info = CallbackInfo::new(
593
            &ref_data,
594
            &changes,
595
            DomNodeId {
596
                dom: DomId::ROOT_ID,
597
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(hit))),
598
            },
599
            OptionLogicalPosition::None,
600
            OptionLogicalPosition::None,
601
        );
602

            
603
        let update = on_crumb_click(data, info);
604
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
605
        (update, recorded)
606
    }
607

            
608
    // ------------------------------------------------------------------
609
    // Breadcrumb::create
610
    // ------------------------------------------------------------------
611

            
612
    #[test]
613
    fn create_preserves_labels_verbatim_and_defaults_the_state() {
614
        for case in [
615
            vec![],
616
            vec!["only"],
617
            vec!["Home", "Docs"],
618
            vec!["Home", "Docs", "Widgets", "Breadcrumb"],
619
        ] {
620
            let bc = Breadcrumb::create(labels(&case));
621

            
622
            let got: Vec<&str> = bc.labels.as_ref().iter().map(AzString::as_str).collect();
623
            assert_eq!(got, case, "create must not reorder/drop/rewrite labels");
624

            
625
            assert_eq!(
626
                bc.breadcrumb_state.inner.selected_index, 0,
627
                "a fresh breadcrumb starts at crumb 0"
628
            );
629
            assert!(
630
                bc.breadcrumb_state.on_navigate.as_ref().is_none(),
631
                "create must not install a callback"
632
            );
633
            assert_eq!(
634
                bc.resolved_container_style().as_ref(),
635
                BREADCRUMB_CONTAINER_STYLE,
636
                "create must use the shared const container style"
637
            );
638
        }
639
    }
640

            
641
    #[test]
642
    fn create_survives_pathological_labels() {
643
        // empty string, whitespace-only, a label that *is* the separator glyph,
644
        // emoji + ZWJ, RTL, combining marks, NUL, and a 100k-char label.
645
        let huge = "x".repeat(100_000);
646
        let case = vec![
647
            "",
648
            "   ",
649
            "/",
650
            "//",
651
            "a\u{0}b",
652
            "👨‍👩‍👧‍👦",
653
            "مرحبا",
654
            "e\u{0301}\u{0301}\u{0301}",
655
            "\u{200b}\u{feff}",
656
            huge.as_str(),
657
        ];
658
        let bc = Breadcrumb::create(labels(&case));
659

            
660
        let got: Vec<&str> = bc.labels.as_ref().iter().map(AzString::as_str).collect();
661
        assert_eq!(got, case, "labels must survive byte-for-byte");
662
        assert_eq!(bc.labels.as_ref()[9].as_str().len(), 100_000);
663

            
664
        // …and they must survive the trip through the DOM unchanged.
665
        let dom = bc.dom();
666
        let texts: Vec<&str> = dom
667
            .children
668
            .as_ref()
669
            .iter()
670
            .enumerate()
671
            .filter(|(i, _)| i % 2 == 0) // crumbs sit at even positions
672
            .filter_map(|(_, c)| text_of(c))
673
            .collect();
674
        assert_eq!(texts, case);
675
    }
676

            
677
    #[test]
678
    fn create_with_many_labels_does_not_panic() {
679
        let n = 10_000;
680
        let bc = Breadcrumb::create(n_labels(n));
681
        assert_eq!(bc.labels.as_ref().len(), n);
682
        assert_eq!(bc.labels.as_ref()[n - 1].as_str(), "c9999");
683
    }
684

            
685
    #[test]
686
    fn default_equals_create_with_no_labels() {
687
        assert_eq!(
688
            Breadcrumb::default(),
689
            Breadcrumb::create(StringVec::from_const_slice(&[]))
690
        );
691
        assert!(Breadcrumb::default().labels.as_ref().is_empty());
692
    }
693

            
694
    // ------------------------------------------------------------------
695
    // Breadcrumb::swap_with_default
696
    // ------------------------------------------------------------------
697

            
698
    #[test]
699
    fn swap_with_default_returns_the_old_value_and_resets_self() {
700
        let mut bc = Breadcrumb::create(labels(&["Home", "Docs", "Here"]));
701
        let old = bc.swap_with_default();
702

            
703
        let old_labels: Vec<&str> = old.labels.as_ref().iter().map(AzString::as_str).collect();
704
        assert_eq!(
705
            old_labels,
706
            ["Home", "Docs", "Here"],
707
            "the old value moves out"
708
        );
709
        assert!(
710
            bc.labels.as_ref().is_empty(),
711
            "self must be left as a default (empty) breadcrumb"
712
        );
713
        assert_eq!(bc, Breadcrumb::default());
714
    }
715

            
716
    #[test]
717
    fn swap_with_default_moves_the_callback_out_of_self() {
718
        let mut bc = Breadcrumb::create(labels(&["a", "b"]))
719
            .with_on_navigate(RefAny::new(NavLog { seen: Vec::new() }), nav_cb(record_nav));
720

            
721
        let old = bc.swap_with_default();
722
        assert!(
723
            old.breadcrumb_state.on_navigate.as_ref().is_some(),
724
            "the callback must travel with the returned value"
725
        );
726
        assert!(
727
            bc.breadcrumb_state.on_navigate.as_ref().is_none(),
728
            "self must not keep a dangling reference to the moved-out callback"
729
        );
730
    }
731

            
732
    #[test]
733
    fn swap_with_default_is_stable_when_repeated() {
734
        let mut bc = Breadcrumb::create(labels(&["a"]));
735
        let _ = bc.swap_with_default();
736
        // Now `bc` is already a default — swapping again must keep returning
737
        // defaults, not panic or corrupt state.
738
        for _ in 0..100 {
739
            let out = bc.swap_with_default();
740
            assert_eq!(out, Breadcrumb::default());
741
            assert_eq!(bc, Breadcrumb::default());
742
        }
743
    }
744

            
745
    #[test]
746
    fn swap_with_default_preserves_a_customised_state() {
747
        let mut bc = Breadcrumb::create(labels(&["a", "b"]));
748
        bc.breadcrumb_state.inner.selected_index = usize::MAX;
749

            
750
        let old = bc.swap_with_default();
751
        assert_eq!(
752
            old.breadcrumb_state.inner.selected_index,
753
            usize::MAX,
754
            "an out-of-range index must move out untouched (no clamping/rewrite)"
755
        );
756
        assert_eq!(bc.breadcrumb_state.inner.selected_index, 0);
757
    }
758

            
759
    // ------------------------------------------------------------------
760
    // Breadcrumb::set_on_navigate / with_on_navigate
761
    // ------------------------------------------------------------------
762

            
763
    #[test]
764
    fn with_on_navigate_sets_the_callback_and_touches_nothing_else() {
765
        let before = Breadcrumb::create(labels(&["Home", "Docs"]));
766
        let after = Breadcrumb::create(labels(&["Home", "Docs"]))
767
            .with_on_navigate(RefAny::new(NavLog { seen: Vec::new() }), nav_cb(record_nav));
768

            
769
        assert_eq!(
770
            after.labels, before.labels,
771
            "installing a callback must not disturb the labels"
772
        );
773
        assert_eq!(
774
            after.resolved_container_style(),
775
            before.resolved_container_style(),
776
            "installing a callback must not disturb the container style"
777
        );
778
        assert_eq!(after.breadcrumb_state.inner.selected_index, 0);
779

            
780
        let installed = after
781
            .breadcrumb_state
782
            .on_navigate
783
            .as_ref()
784
            .expect("with_on_navigate must install Some(..)");
785
        assert_eq!(installed.callback.cb as usize, record_nav as usize);
786
    }
787

            
788
    #[test]
789
    fn set_on_navigate_overwrites_the_previous_callback_and_data() {
790
        let mut bc = Breadcrumb::create(labels(&["a", "b"]));
791
        bc.set_on_navigate(RefAny::new(NavLog { seen: Vec::new() }), nav_cb(record_nav));
792
        bc.set_on_navigate(RefAny::new(42u32), nav_cb(nav_do_nothing));
793

            
794
        let installed = bc
795
            .breadcrumb_state
796
            .on_navigate
797
            .as_mut()
798
            .expect("still Some after the overwrite");
799
        assert_eq!(
800
            installed.callback.cb as usize, nav_do_nothing as usize,
801
            "the last set_on_navigate must win"
802
        );
803
        assert_eq!(
804
            installed.refany.downcast_ref::<u32>().map(|v| *v),
805
            Some(42),
806
            "the payload must be replaced along with the fn pointer"
807
        );
808
        assert!(
809
            installed.refany.downcast_ref::<NavLog>().is_none(),
810
            "the stale payload must be gone"
811
        );
812
    }
813

            
814
    #[test]
815
    fn set_on_navigate_accepts_a_generic_callback_without_corrupting_the_fn_pointer() {
816
        // The FFI path (`From<Callback>`) transmutes the fn pointer. The value
817
        // must round-trip bit-for-bit — a corrupted pointer would be an
818
        // unconditional jump into garbage at click time. (Never invoked here.)
819
        let raw = record_nav as usize;
820
        let generic = Callback {
821
            cb: unsafe { core::mem::transmute::<usize, crate::callbacks::CallbackType>(raw) },
822
            ctx: OptionRefAny::None,
823
        };
824
        let converted: BreadcrumbOnNavigateCallback = generic.into();
825
        assert_eq!(converted.cb as usize, raw);
826
    }
827

            
828
    #[test]
829
    fn with_on_navigate_on_an_empty_breadcrumb_yields_a_dom_with_no_callbacks() {
830
        // 0 labels => no crumbs => the installed callback is simply never wired up.
831
        let dom = Breadcrumb::create(StringVec::from_const_slice(&[]))
832
            .with_on_navigate(RefAny::new(NavLog { seen: Vec::new() }), nav_cb(record_nav))
833
            .dom();
834

            
835
        assert!(dom.children.as_ref().is_empty());
836
        assert!(dom.root.get_callbacks().as_ref().is_empty());
837
    }
838

            
839
    // ------------------------------------------------------------------
840
    // Breadcrumb::dom
841
    // ------------------------------------------------------------------
842

            
843
    #[test]
844
    fn dom_of_no_labels_is_an_empty_container() {
845
        let dom = Breadcrumb::create(StringVec::from_const_slice(&[])).dom();
846

            
847
        assert!(
848
            dom.children.as_ref().is_empty(),
849
            "no labels => no crumbs and no separators"
850
        );
851
        assert_eq!(dom.estimated_total_children, 0);
852
        assert!(dom.root.has_class("__azul-native-breadcrumb"));
853
    }
854

            
855
    #[test]
856
    fn dom_of_a_single_label_has_no_separator_and_no_clickable_crumb() {
857
        let dom = Breadcrumb::create(labels(&["Home"])).dom();
858
        let children = dom.children.as_ref();
859

            
860
        assert_eq!(
861
            children.len(),
862
            1,
863
            "a lone label is the current page, nothing else"
864
        );
865
        assert_eq!(text_of(&children[0]), Some("Home"));
866
        assert!(children[0]
867
            .root
868
            .has_class("__azul-native-breadcrumb-current"));
869
        assert!(
870
            children[0].root.get_callbacks().as_ref().is_empty(),
871
            "the current page must not be clickable"
872
        );
873
        assert_eq!(children[0].root.get_tab_index(), None);
874
    }
875

            
876
    #[test]
877
    fn dom_alternates_crumb_separator_and_ends_on_the_current_page() {
878
        let case = ["Home", "Docs", "Widgets", "Breadcrumb"];
879
        let dom = Breadcrumb::create(labels(&case)).dom();
880
        let children = dom.children.as_ref();
881

            
882
        assert_eq!(
883
            children.len(),
884
            2 * case.len() - 1,
885
            "n crumbs + (n-1) separators"
886
        );
887

            
888
        for (pos, child) in children.iter().enumerate() {
889
            let is_last_child = pos + 1 == children.len();
890
            if pos % 2 == 1 {
891
                // separator
892
                assert_eq!(text_of(child), Some("/"), "odd positions are separators");
893
                assert!(child.root.has_class("__azul-native-breadcrumb-separator"));
894
                assert!(
895
                    child.root.get_callbacks().as_ref().is_empty(),
896
                    "separators must not be clickable"
897
                );
898
                assert_eq!(child.root.get_tab_index(), None);
899
            } else if is_last_child {
900
                // current page
901
                assert_eq!(text_of(child), Some(case[pos / 2]));
902
                assert!(child.root.has_class("__azul-native-breadcrumb-current"));
903
                assert!(
904
                    child.root.get_callbacks().as_ref().is_empty(),
905
                    "the current page must not be clickable"
906
                );
907
                assert_eq!(child.root.get_tab_index(), None);
908
            } else {
909
                // clickable crumb link
910
                assert_eq!(text_of(child), Some(case[pos / 2]));
911
                assert!(child.root.has_class("__azul-native-breadcrumb-item"));
912
                let cbs = child.root.get_callbacks();
913
                assert_eq!(cbs.as_ref().len(), 1, "one MouseUp handler per crumb");
914
                assert_eq!(
915
                    cbs.as_ref()[0].event,
916
                    EventFilter::Hover(HoverEventFilter::Click)
917
                );
918
                assert_eq!(cbs.as_ref()[0].callback.cb, on_crumb_click as usize);
919
                assert_eq!(
920
                    child.root.get_tab_index(),
921
                    Some(TabIndex::Auto),
922
                    "crumb links must be keyboard-reachable"
923
                );
924
            }
925
        }
926
    }
927

            
928
    #[test]
929
    fn dom_estimated_total_children_matches_the_real_descendant_count() {
930
        // `estimated_total_children` is a cached count; if it under-counts,
931
        // `convert_dom_into_compact_dom` under-allocates and panics.
932
        for n in [0usize, 1, 2, 3, 5, 64, 257] {
933
            let dom = Breadcrumb::create(n_labels(n)).dom();
934
            let children = if n == 0 { 0 } else { 2 * n - 1 };
935
            // Every child is a styled `<p>` wrapping its bare text leaf per
936
            // the label convention, so descendants = 2 x children.
937
            let expected = 2 * children;
938

            
939
            assert_eq!(
940
                dom.children.as_ref().len(),
941
                children,
942
                "child count for n={n}"
943
            );
944
            assert_eq!(
945
                dom.estimated_total_children,
946
                recursive_descendants(&dom),
947
                "cached descendant count desynced for n={n}"
948
            );
949
            assert_eq!(dom.estimated_total_children, expected, "for n={n}");
950
        }
951
    }
952

            
953
    #[test]
954
    fn dom_of_many_labels_flattens_without_panicking() {
955
        let n = 200;
956
        let styled = StyledDom::create_from_dom(Breadcrumb::create(n_labels(n)).dom());
957
        assert_eq!(
958
            styled.node_hierarchy.as_ref().len(),
959
            4 * n - 1,
960
            "root + (2n-1) children, each a <p> + its text leaf"
961
        );
962
    }
963

            
964
    #[test]
965
    fn dom_separator_is_told_apart_by_class_not_by_text() {
966
        // A label that is literally "/" must still be a crumb, not a separator.
967
        let dom = Breadcrumb::create(labels(&["/", "b"])).dom();
968
        let children = dom.children.as_ref();
969

            
970
        assert_eq!(text_of(&children[0]), Some("/"));
971
        assert!(children[0].root.has_class("__azul-native-breadcrumb-item"));
972
        assert!(!children[0]
973
            .root
974
            .has_class("__azul-native-breadcrumb-separator"));
975
        assert!(!children[0].root.get_callbacks().as_ref().is_empty());
976

            
977
        assert_eq!(text_of(&children[1]), Some("/"));
978
        assert!(children[1]
979
            .root
980
            .has_class("__azul-native-breadcrumb-separator"));
981
        assert!(children[1].root.get_callbacks().as_ref().is_empty());
982
    }
983

            
984
    #[test]
985
    fn dom_shares_one_state_refany_across_every_crumb() {
986
        let dom = Breadcrumb::create(labels(&["a", "b", "c", "d"])).dom();
987

            
988
        // Write through crumb 0's handle…
989
        let mut first = crumb_state(&dom, 0);
990
        {
991
            let mut w = first
992
                .downcast_mut::<BreadcrumbStateWrapper>()
993
                .expect("crumb state must be a BreadcrumbStateWrapper");
994
            w.inner.selected_index = 7;
995
        }
996
        // …and read it back through crumb 2's handle.
997
        let mut third = crumb_state(&dom, 2);
998
        assert_eq!(
999
            selected_index_of(&mut third),
            7,
            "every crumb must observe the same shared state"
        );
    }
    #[test]
    fn dom_gives_separate_breadcrumbs_separate_state() {
        let a = Breadcrumb::create(labels(&["a", "b"])).dom();
        let b = Breadcrumb::create(labels(&["a", "b"])).dom();
        let mut a0 = crumb_state(&a, 0);
        {
            let mut w = a0.downcast_mut::<BreadcrumbStateWrapper>().unwrap();
            w.inner.selected_index = 3;
        }
        let mut b0 = crumb_state(&b, 0);
        assert_eq!(
            selected_index_of(&mut b0),
            0,
            "two breadcrumbs must not alias one another's state"
        );
    }
    #[test]
    fn dom_carries_the_container_style_through() {
        let bc = Breadcrumb::create(labels(&["a", "b"]));
        assert_eq!(
            bc.resolved_container_style().as_ref(),
            BREADCRUMB_CONTAINER_STYLE
        );
        let dom = bc.dom();
        assert!(dom.root.has_class("__azul-native-breadcrumb"));
        assert!(
            dom.root.is_node_type(NodeType::Div),
            "the row container must be a div"
        );
    }
    // ------------------------------------------------------------------
    // Style constants (invariants the widget's look depends on)
    // ------------------------------------------------------------------
    #[test]
    fn crumb_styles_are_opaque_and_visually_distinct() {
        for (name, c) in [
            ("link", LINK_COLOR),
            ("current", CURRENT_COLOR),
            ("separator", SEPARATOR_COLOR),
        ] {
            assert_eq!(c.a, 255, "{name} colour must be fully opaque");
        }
        assert_ne!(
            LINK_COLOR, CURRENT_COLOR,
            "the current page must not look like a link"
        );
        assert_eq!(text_color(BREADCRUMB_ITEM_STYLE), Some(LINK_COLOR));
        assert_eq!(text_color(BREADCRUMB_CURRENT_STYLE), Some(CURRENT_COLOR));
        assert_eq!(
            text_color(BREADCRUMB_SEPARATOR_STYLE),
            Some(SEPARATOR_COLOR)
        );
    }
    #[test]
    fn only_the_clickable_crumb_style_declares_a_pointer_cursor() {
        assert!(has_property(
            BREADCRUMB_ITEM_STYLE,
            &CssProperty::const_cursor(StyleCursor::Pointer)
        ));
        assert!(
            !has_cursor(BREADCRUMB_CURRENT_STYLE),
            "the current page is not clickable, so it must not advertise a pointer"
        );
        assert!(
            !has_cursor(BREADCRUMB_SEPARATOR_STYLE),
            "separators are not clickable"
        );
    }
    #[test]
    fn separator_style_has_symmetric_horizontal_margins() {
        assert!(has_property(
            BREADCRUMB_SEPARATOR_STYLE,
            &CssProperty::const_margin_left(LayoutMarginLeft::const_px(8))
        ));
        assert!(has_property(
            BREADCRUMB_SEPARATOR_STYLE,
            &CssProperty::const_margin_right(LayoutMarginRight::const_px(8))
        ));
    }
    #[test]
    fn every_crumb_style_disables_text_selection_and_flex_growth() {
        for (name, style) in [
            ("item", BREADCRUMB_ITEM_STYLE),
            ("current", BREADCRUMB_CURRENT_STYLE),
            ("separator", BREADCRUMB_SEPARATOR_STYLE),
        ] {
            assert!(
                has_property(style, &CssProperty::user_select(StyleUserSelect::None)),
                "{name}: dragging across a breadcrumb must not select its text"
            );
            assert!(
                has_property(
                    style,
                    &CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))
                ),
                "{name}: crumbs must hug their content"
            );
        }
        assert!(has_property(
            BREADCRUMB_CURRENT_STYLE,
            &CssProperty::font_weight(StyleFontWeight::Bold)
        ));
        assert_eq!(SEPARATOR_GLYPH.as_str(), "/");
    }
    // ------------------------------------------------------------------
    // on_crumb_click
    // ------------------------------------------------------------------
    #[test]
    fn click_reports_the_index_of_each_crumb() {
        // Flat DFS with the label convention (<p> + text leaf per child):
        // crumb0(1) sep(3) crumb1(5) sep(7) crumb2(9) sep(11) current(13)
        let (styled, state) = flatten(Breadcrumb::create(labels(&["a", "b", "c", "d"])));
        assert_eq!(
            styled.node_hierarchy.as_ref().len(),
            15,
            "fixture must flatten to root + 7 children + their 7 text leaves"
        );
        for (hit, expected) in [(1usize, 0usize), (5, 1), (9, 2)] {
            let mut state = state.clone();
            let (update, changes) = run_click(Some(styled.clone()), hit, state.clone());
            assert_eq!(
                update,
                Update::DoNothing,
                "with no on_navigate installed the handler reports nothing to redraw"
            );
            assert_eq!(
                selected_index_of(&mut state),
                expected,
                "node {hit} sits at sibling position {} => index {expected}",
                (hit - 1) / 2
            );
            assert!(
                changes.is_empty(),
                "the handler must not live-restyle (navigation rebuilds the page)"
            );
        }
    }
    #[test]
    fn click_invokes_the_user_callback_with_the_clicked_index() {
        let mut log = RefAny::new(NavLog { seen: Vec::new() });
        let bc = Breadcrumb::create(labels(&["a", "b", "c", "d"]))
            .with_on_navigate(log.clone(), nav_cb(record_nav));
        let (styled, state) = flatten(bc);
        let (update, _) = run_click(Some(styled.clone()), 9, state.clone());
        assert_eq!(
            update,
            Update::RefreshDom,
            "the user's Update must propagate"
        );
        assert_eq!(log_indices(&mut log), vec![2]);
        // A second click updates the shared state again — the index is not sticky.
        let (_, _) = run_click(Some(styled), 1, state.clone());
        assert_eq!(log_indices(&mut log), vec![2, 0]);
        let mut state = state;
        assert_eq!(
            selected_index_of(&mut state),
            0,
            "the state must hold the *last* clicked index"
        );
    }
    #[test]
    fn click_propagates_every_update_variant_unchanged() {
        for (cb, expected) in [
            (nav_cb(nav_do_nothing), Update::DoNothing),
            (nav_cb(nav_refresh_all), Update::RefreshDomAllWindows),
        ] {
            let bc = Breadcrumb::create(labels(&["a", "b"])).with_on_navigate(RefAny::new(0u8), cb);
            let (styled, state) = flatten(bc);
            let (update, _) = run_click(Some(styled), 1, state);
            assert_eq!(update, expected);
        }
    }
    #[test]
    fn click_on_the_root_node_does_nothing() {
        // The root has no parent -> the handler must bail, not index into nothing.
        let (styled, state) = flatten(Breadcrumb::create(labels(&["a", "b"])));
        let mut state2 = state.clone();
        let (update, changes) = run_click(Some(styled), 0, state);
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(selected_index_of(&mut state2), 0, "state must be untouched");
    }
    #[test]
    fn click_on_an_out_of_range_node_does_nothing() {
        let (styled, state) = flatten(Breadcrumb::create(labels(&["a", "b"])));
        let (update, changes) = run_click(Some(styled), 9999, state);
        assert_eq!(
            update,
            Update::DoNothing,
            "a hit node that isn't in the tree must not panic"
        );
        assert!(changes.is_empty());
    }
    #[test]
    fn click_with_no_layout_result_does_nothing() {
        let bc = Breadcrumb::create(labels(&["a", "b"]));
        let dom = bc.dom();
        let state = crumb_state(&dom, 0);
        let (update, changes) = run_click(None, 1, state);
        assert_eq!(
            update,
            Update::DoNothing,
            "an empty LayoutWindow must be handled, not unwrapped"
        );
        assert!(changes.is_empty());
    }
    #[test]
    fn click_with_a_foreign_payload_does_nothing() {
        let (styled, _) = flatten(Breadcrumb::create(labels(&["a", "b"])));
        // Wrong type in the RefAny: downcast fails, handler must bail cleanly.
        let (update, changes) = run_click(Some(styled), 1, RefAny::new(0u32));
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn click_with_the_state_already_borrowed_does_nothing() {
        let (styled, state) = flatten(Breadcrumb::create(labels(&["a", "b"])));
        // A live mutable borrow on a sibling clone: `downcast_mut` inside the
        // handler must fail (returning DoNothing) instead of aliasing `&mut`.
        let mut held = state.clone();
        let guard = held
            .downcast_mut::<BreadcrumbStateWrapper>()
            .expect("first borrow succeeds");
        let (update, changes) = run_click(Some(styled), 1, state);
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        drop(guard);
    }
    #[test]
    fn click_on_a_separator_or_the_current_page_maps_to_pos_over_two() {
        // Neither carries a callback, so this is unreachable in practice — but
        // the documented `index = position / 2` must still hold (and not panic)
        // if the handler is ever invoked on one.
        let (styled, state) = flatten(Breadcrumb::create(labels(&["a", "b", "c", "d"])));
        for (hit, expected) in [(3usize, 0usize), (7, 1), (11, 2), (13, 3)] {
            let mut state = state.clone();
            let (update, _) = run_click(Some(styled.clone()), hit, state.clone());
            assert_eq!(update, Update::DoNothing);
            assert_eq!(
                selected_index_of(&mut state),
                expected,
                "node {hit} => position {} => index {expected}",
                (hit - 1) / 2
            );
        }
    }
    #[test]
    fn click_indices_stay_in_range_for_a_long_trail() {
        let n = 64;
        let (styled, state) = flatten(Breadcrumb::create(n_labels(n)));
        assert_eq!(styled.node_hierarchy.as_ref().len(), 4 * n - 1);
        // Last clickable crumb: index n-2, at child position 2*(n-2); flat id
        // of the child at position p is 1 + 2p (each earlier child is a <p>
        // plus its text leaf) => node 4n-7.
        let hit = 4 * n - 7;
        let mut state = state;
        let (_, _) = run_click(Some(styled), hit, state.clone());
        let idx = selected_index_of(&mut state);
        assert_eq!(idx, n - 2);
        assert!(
            idx < n,
            "the reported index must always address a real label"
        );
    }
}