1
//! Tooltip widget — wraps an arbitrary anchor [`Dom`] and shows a small text
2
//! popup near it while the pointer hovers, hiding it again on leave.
3
//!
4
//! ## Implementation note (CSS-based, see `TODO2` below)
5
//!
6
//! The drop-down popup path (`open_menu_for_hit_node` / `MenuPopupPosition`) is
7
//! built for *menus* — a list of clickable `MenuItem`s — not arbitrary text
8
//! shown next to an anchor, and it would also require a live window/hit-test to
9
//! verify. This widget therefore takes the simpler, fully-compilable and
10
//! self-contained CSS route the recipe allows: the tip is an absolutely-
11
//! positioned child of a `position: relative` wrapper, hidden by default
12
//! (`opacity: 0`) and revealed on `MouseEnter` / hidden on `MouseLeave` via
13
//! `set_css_property`. No user callbacks are needed — the show/hide handlers are
14
//! internal.
15
//!
16
//! TODO2: this is a CSS simplification of a "real" floating popover. The tip is
17
//! placed at a fixed offset below the anchor (it does not measure the anchor's
18
//! height, flip when near a screen edge, or escape an `overflow: hidden`
19
//! ancestor). A future revision could route through the window-popup / menu
20
//! popup path for true screen-anchored positioning once that is runtime-
21
//! verifiable.
22
//!
23
//! Key types: [`Tooltip`].
24

            
25
use azul_core::{
26
    callbacks::{CoreCallback, CoreCallbackData, Update},
27
    dom::{Dom, EventFilter, HoverEventFilter, IdOrClass, IdOrClass::Class, IdOrClassVec},
28
    refany::{OptionRefAny, RefAny},
29
};
30
use azul_css::{
31
    dynamic_selector::{
32
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
33
    },
34
    props::{
35
        basic::{color::ColorU, StyleFontSize},
36
        layout::{
37
            LayoutDisplay, LayoutFlexGrow, LayoutLeft, LayoutPaddingBottom, LayoutPaddingLeft,
38
            LayoutPaddingRight, LayoutPaddingTop, LayoutPosition, LayoutTop,
39
        },
40
        property::{CssProperty, StyleWhiteSpaceValue},
41
        style::{
42
            StyleBackgroundContent, StyleBackgroundContentVec, StyleBorderBottomLeftRadius,
43
            StyleBorderBottomRightRadius, StyleBorderTopLeftRadius, StyleBorderTopRightRadius,
44
            StyleOpacity, StyleTextColor, StyleWhiteSpace,
45
        },
46
    },
47
    AzString,
48
};
49

            
50
use crate::callbacks::CallbackInfo;
51

            
52
static TOOLTIP_WRAPPER_CLASS: &[IdOrClass] =
53
    &[Class(AzString::from_const_str("__azul-native-tooltip"))];
54
static TOOLTIP_TIP_CLASS: &[IdOrClass] =
55
    &[Class(AzString::from_const_str("__azul-native-tooltip-tip"))];
56

            
57
// ---- layout (logical px) ----
58
/// Fixed vertical offset of the tip below the wrapper's top edge. A
59
/// simplification — see the module-level `TODO2`.
60
const TIP_OFFSET_Y: isize = 22;
61
const TIP_RADIUS: isize = 4;
62

            
63
// ---- colours ----
64
/// Tip background (#333333, dark).
65
const TIP_BG_COLOR: ColorU = ColorU {
66
    r: 51,
67
    g: 51,
68
    b: 51,
69
    a: 240,
70
};
71
/// Tip text colour (white).
72
const TIP_TEXT_COLOR: ColorU = ColorU {
73
    r: 255,
74
    g: 255,
75
    b: 255,
76
    a: 255,
77
};
78

            
79
const TIP_BG_ITEMS: &[StyleBackgroundContent] = &[StyleBackgroundContent::Color(TIP_BG_COLOR)];
80
const TIP_BG: StyleBackgroundContentVec = StyleBackgroundContentVec::from_const_slice(TIP_BG_ITEMS);
81

            
82
/// Wrapper around the anchor: an inline-block positioning context so the
83
/// absolutely-positioned tip is placed relative to it.
84
static TOOLTIP_WRAPPER_STYLE: &[CssPropertyWithConditions] = &[
85
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::InlineBlock)),
86
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Relative)),
87
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
88
];
89

            
90
/// The tip itself: absolutely positioned, hidden by default (`opacity: 0`).
91
static TOOLTIP_TIP_STYLE: &[CssPropertyWithConditions] = &[
92
    CssPropertyWithConditions::simple(CssProperty::const_position(LayoutPosition::Absolute)),
93
    CssPropertyWithConditions::simple(CssProperty::const_top(LayoutTop::const_px(TIP_OFFSET_Y))),
94
    CssPropertyWithConditions::simple(CssProperty::const_left(LayoutLeft::const_px(0))),
95
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
96
        LayoutPaddingLeft::const_px(8),
97
    )),
98
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
99
        LayoutPaddingRight::const_px(8),
100
    )),
101
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
102
        4,
103
    ))),
104
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
105
        LayoutPaddingBottom::const_px(4),
106
    )),
107
    CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
108
        StyleBorderTopLeftRadius::const_px(TIP_RADIUS),
109
    )),
110
    CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
111
        StyleBorderTopRightRadius::const_px(TIP_RADIUS),
112
    )),
113
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
114
        StyleBorderBottomLeftRadius::const_px(TIP_RADIUS),
115
    )),
116
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
117
        StyleBorderBottomRightRadius::const_px(TIP_RADIUS),
118
    )),
119
    CssPropertyWithConditions::simple(CssProperty::const_background_content(TIP_BG)),
120
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
121
        inner: TIP_TEXT_COLOR,
122
    })),
123
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(12))),
124
    // Preserve the tip on one line so it does not wrap into the anchor's width.
125
    CssPropertyWithConditions::simple(CssProperty::WhiteSpace(StyleWhiteSpaceValue::Exact(
126
        StyleWhiteSpace::Nowrap,
127
    ))),
128
    // Hidden until hovered.
129
    CssPropertyWithConditions::simple(CssProperty::const_opacity(StyleOpacity::const_new(0))),
130
];
131

            
132
/// A tooltip: an anchor [`Dom`] plus the text shown on hover.
133
#[derive(Debug, Clone, PartialEq, Eq)]
134
#[repr(C)]
135
pub struct Tooltip {
136
    /// The element the tooltip is attached to.
137
    pub anchor: Dom,
138
    /// The text shown in the tip popup.
139
    pub text: AzString,
140
    /// Style for the positioning wrapper, or `None` for "no opinion" — in which
141
    /// case the widget's default applies.
142
    ///
143
    /// `None` and `Some(empty)` are different answers: the first means the
144
    /// widget picks, the second means the caller asked for no properties at all
145
    /// and gets none.
146
    pub wrapper_style: OptionCssPropertyWithConditionsVec,
147
    /// Style of the tip popup.
148
    pub tip_style: OptionCssPropertyWithConditionsVec,
149
}
150

            
151
impl Default for Tooltip {
152
46
    fn default() -> Self {
153
46
        Self::new(Dom::default(), AzString::from_const_str(""))
154
46
    }
155
}
156

            
157
impl Tooltip {
158
    /// The wrapper CSS this tooltip renders with.
159
    ///
160
    /// `None` means no opinion, so the built-in wrapper style applies. Named so
161
    /// the tests can ask what is rendered rather than reading the field, which
162
    /// is `None` until a caller sets one.
163
    #[must_use]
164
74
    pub fn resolved_wrapper_style(&self) -> CssPropertyWithConditionsVec {
165
74
        self.wrapper_style.clone().into_option().unwrap_or_else(|| {
166
74
            CssPropertyWithConditionsVec::from_const_slice(TOOLTIP_WRAPPER_STYLE)
167
74
        })
168
74
    }
169

            
170
    /// The tip CSS this tooltip renders with.
171
    ///
172
    /// `None` means no opinion, so the widget's default applies — the same
173
    /// answer both themes give, asked in one place so they cannot drift.
174
    #[must_use]
175
76
    pub fn resolved_tip_style(&self) -> CssPropertyWithConditionsVec {
176
76
        self.tip_style
177
76
            .clone()
178
76
            .into_option()
179
76
            .unwrap_or_else(|| CssPropertyWithConditionsVec::from_const_slice(TOOLTIP_TIP_STYLE))
180
76
    }
181

            
182
    /// Creates a tooltip wrapping `anchor` that shows `text` on hover.
183
    #[must_use]
184
121
    pub const fn new(anchor: Dom, text: AzString) -> Self {
185
121
        Self {
186
121
            anchor,
187
121
            text,
188
121
            wrapper_style: OptionCssPropertyWithConditionsVec::None,
189
121
            tip_style: OptionCssPropertyWithConditionsVec::None,
190
121
        }
191
121
    }
192

            
193
    /// Sets the tip text.
194
    #[inline]
195
36
    pub fn set_text(&mut self, text: AzString) {
196
36
        self.text = text;
197
36
    }
198

            
199
    /// Builder-style setter for the tip text.
200
    #[inline]
201
    #[must_use]
202
18
    pub fn with_text(mut self, text: AzString) -> Self {
203
18
        self.set_text(text);
204
18
        self
205
18
    }
206

            
207
    /// Overrides the tip popup style.
208
    #[inline]
209
9
    pub fn set_tip_style(&mut self, style: CssPropertyWithConditionsVec) {
210
9
        self.tip_style = OptionCssPropertyWithConditionsVec::Some(style);
211
9
    }
212

            
213
    /// Builder-style setter for the tip popup style.
214
    #[inline]
215
    #[must_use]
216
7
    pub fn with_tip_style(mut self, style: CssPropertyWithConditionsVec) -> Self {
217
7
        self.set_tip_style(style);
218
7
        self
219
7
    }
220

            
221
    #[inline]
222
    #[must_use]
223
13
    pub fn swap_with_default(&mut self) -> Self {
224
13
        let mut s = Self::default();
225
13
        core::mem::swap(&mut s, self);
226
13
        s
227
13
    }
228

            
229
    #[must_use]
230
38
    pub fn dom(self) -> Dom {
231
        // The hover handlers only navigate the DOM (the tip is found relative to
232
        // the hovered wrapper), so no per-tooltip state is needed.
233
38
        let marker = RefAny::new(());
234

            
235
        // Resolved before `self.text` is moved out below.
236
38
        let tip_css = self.resolved_tip_style();
237
38
        let wrapper_css = self.resolved_wrapper_style();
238
38
        let tip = crate::widgets::widget_p_with_text(self.text)
239
38
            .with_ids_and_classes(IdOrClassVec::from_const_slice(TOOLTIP_TIP_CLASS))
240
38
            .with_css_props(tip_css);
241

            
242
38
        Dom::create_div()
243
38
            .with_ids_and_classes(IdOrClassVec::from_const_slice(TOOLTIP_WRAPPER_CLASS))
244
38
            .with_css_props(wrapper_css)
245
38
            .with_callbacks(
246
38
                vec![
247
38
                    CoreCallbackData {
248
38
                        event: EventFilter::Hover(HoverEventFilter::MouseEnter),
249
38
                        callback: CoreCallback {
250
38
                            cb: on_tooltip_enter as usize,
251
38
                            ctx: OptionRefAny::None,
252
38
                        },
253
38
                        refany: marker.clone(),
254
38
                    },
255
38
                    CoreCallbackData {
256
38
                        event: EventFilter::Hover(HoverEventFilter::MouseLeave),
257
38
                        callback: CoreCallback {
258
38
                            cb: on_tooltip_leave as usize,
259
38
                            ctx: OptionRefAny::None,
260
38
                        },
261
38
                        refany: marker,
262
38
                    },
263
                ]
264
38
                .into(),
265
            )
266
            // children: [anchor, tip] — the tip is the anchor's next sibling.
267
38
            .with_children(vec![self.anchor, tip].into())
268
38
    }
269
}
270

            
271
/// Returns the tip node (the second child) of the hovered wrapper.
272
96
fn tip_of_wrapper(info: &CallbackInfo) -> Option<azul_core::dom::DomNodeId> {
273
96
    let wrapper = info.get_hit_node();
274
96
    let anchor = info.get_first_child(wrapper)?;
275
82
    info.get_next_sibling(anchor)
276
96
}
277

            
278
/// Pointer entered the wrapper → reveal the tip.
279
77
extern "C" fn on_tooltip_enter(_data: RefAny, mut info: CallbackInfo) -> Update {
280
77
    if let Some(tip) = tip_of_wrapper(&info) {
281
71
        info.set_css_property(
282
71
            tip,
283
71
            CssProperty::const_opacity(StyleOpacity::const_new(100)),
284
71
        );
285
71
    }
286
77
    Update::DoNothing
287
77
}
288

            
289
/// Pointer left the wrapper → hide the tip.
290
10
extern "C" fn on_tooltip_leave(_data: RefAny, mut info: CallbackInfo) -> Update {
291
10
    if let Some(tip) = tip_of_wrapper(&info) {
292
5
        info.set_css_property(tip, CssProperty::const_opacity(StyleOpacity::const_new(0)));
293
5
    }
294
10
    Update::DoNothing
295
10
}
296

            
297
impl From<Tooltip> for Dom {
298
1
    fn from(t: Tooltip) -> Self {
299
1
        t.dom()
300
1
    }
301
}
302

            
303
#[cfg(test)]
304
// `assertions_on_constants`: these are deliberate invariant guards over sibling
305
// `const`s in this module. They are const-foldable *today*, which is exactly the
306
// point — they must go red the moment someone edits one of those constants into an
307
// inconsistent value. Deleting them (clippy's suggestion) would delete the check.
308
#[allow(clippy::assertions_on_constants)]
309
mod autotest_generated {
310
    use std::{
311
        collections::{BTreeMap, HashMap},
312
        sync::{Arc, Mutex},
313
    };
314

            
315
    use azul_core::{
316
        dom::{DomId, DomNodeId, NodeId, NodeType},
317
        geom::{LogicalRect, OptionLogicalPosition},
318
        gl::OptionGlContextPtr,
319
        hit_test::ScrollPosition,
320
        resources::RendererResources,
321
        styled_dom::{NodeHierarchyItemId, StyledDom},
322
        window::{MonitorVec, RawWindowHandle},
323
    };
324
    use azul_css::{props::property::CssPropertyType, system::SystemStyle};
325
    use rust_fontconfig::FcFontCache;
326

            
327
    use super::*;
328
    #[cfg(feature = "icu")]
329
    use crate::icu::IcuLocalizerHandle;
330
    use crate::{
331
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
332
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
333
        window::{DomLayoutResult, LayoutWindow},
334
        window_state::FullWindowState,
335
    };
336

            
337
    // ------------------------------------------------------------------
338
    // Helpers — DOM inspection
339
    // ------------------------------------------------------------------
340

            
341
    const WRAPPER_CLASS_NAME: &str = "__azul-native-tooltip";
342
    const TIP_CLASS_NAME: &str = "__azul-native-tooltip-tip";
343

            
344
    /// True if `node` carries the CSS class `name`.
345
    fn has_class(node: &Dom, name: &str) -> bool {
346
        node.root
347
            .get_ids_and_classes()
348
            .as_ref()
349
            .iter()
350
            .any(|c| matches!(c, Class(s) if s.as_str() == name))
351
    }
352

            
353
    /// The text of a text node, looking through the `<p>` block wrapper the
354
    /// label convention mandates (`p > text`).
355
    fn text_of(node: &Dom) -> Option<&str> {
356
        match node.root.get_node_type() {
357
            NodeType::Text(s) => Some(s.as_ref().as_str()),
358
            NodeType::P => match node.children.as_ref() {
359
                [only] => match only.root.get_node_type() {
360
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
361
                    _ => None,
362
                },
363
                _ => None,
364
            },
365
            _ => None,
366
        }
367
    }
368

            
369
    /// The *inline* properties a rendered node carries, in declaration order.
370
    fn inline_properties(node: &Dom) -> Vec<CssProperty> {
371
        node.root
372
            .style
373
            .iter_inline_properties()
374
            .map(|(p, _)| p.clone())
375
            .collect()
376
    }
377

            
378
    /// The property *types* of a style vec, in declaration order.
379
    fn prop_types(style: &CssPropertyWithConditionsVec) -> Vec<CssPropertyType> {
380
        style
381
            .as_ref()
382
            .iter()
383
            .map(|p| p.property.get_type())
384
            .collect()
385
    }
386

            
387
    /// *Every* opacity declared in a style vec, normalized to `0.0..=1.0`, in
388
    /// declaration order. More than one entry means the later one silently
389
    /// shadows the earlier — the tip would then not be hidden by default.
390
    fn declared_opacities(style: &CssPropertyWithConditionsVec) -> Vec<f32> {
391
        style
392
            .as_ref()
393
            .iter()
394
            .filter_map(|p| match &p.property {
395
                CssProperty::Opacity(v) => v.get_property().map(|o| o.inner.normalized()),
396
                _ => None,
397
            })
398
            .collect()
399
    }
400

            
401
    fn declared_positions(style: &CssPropertyWithConditionsVec) -> Vec<LayoutPosition> {
402
        style
403
            .as_ref()
404
            .iter()
405
            .filter_map(|p| match &p.property {
406
                CssProperty::Position(v) => v.get_property().copied(),
407
                _ => None,
408
            })
409
            .collect()
410
    }
411

            
412
    fn declared_displays(style: &CssPropertyWithConditionsVec) -> Vec<LayoutDisplay> {
413
        style
414
            .as_ref()
415
            .iter()
416
            .filter_map(|p| match &p.property {
417
                CssProperty::Display(v) => v.get_property().copied(),
418
                _ => None,
419
            })
420
            .collect()
421
    }
422

            
423
    /// The `CssPropertyType` of `opacity`, without hard-coding the enum variant.
424
    fn opacity_ty() -> CssPropertyType {
425
        CssProperty::const_opacity(StyleOpacity::const_new(0)).get_type()
426
    }
427

            
428
    /// A style vec built from an owned `Vec` (the shape a *user* override has).
429
    fn style_of(props: Vec<CssProperty>) -> CssPropertyWithConditionsVec {
430
        props
431
            .into_iter()
432
            .map(CssPropertyWithConditions::simple)
433
            .collect::<Vec<_>>()
434
            .into()
435
    }
436

            
437
    /// A `Dom` nested `depth` levels deep — a stress input for the recursive
438
    /// child bookkeeping `dom()` relies on.
439
    fn nested_anchor(depth: usize) -> Dom {
440
        let mut d = Dom::create_div().with_child(
441
            Dom::create_text_do_not_use_without_block_level_wrapper("leaf"),
442
        );
443
        for _ in 0..depth {
444
            d = Dom::create_div().with_child(d);
445
        }
446
        d
447
    }
448

            
449
    /// Inputs chosen to break text handling: empty, whitespace-only, interior
450
    /// NULs, control characters, astral-plane emoji, ZWJ sequences, stacked
451
    /// combining marks, a bidi override, a BOM, and two very large strings.
452
    fn adversarial_texts() -> Vec<String> {
453
        vec![
454
            String::new(),
455
            " ".to_string(),
456
            "\0".to_string(),
457
            "a\0b\0".to_string(),
458
            "\n\r\t\u{0b}\u{0c}".to_string(),
459
            "🦀".to_string(),
460
            "👨‍👩‍👧‍👦".to_string(),
461
            "e\u{0301}\u{0301}\u{0301}\u{0301}".to_string(),
462
            "\u{202e}gnirts detrevni".to_string(),
463
            "\u{feff}bom-prefixed".to_string(),
464
            "fullwidth".to_string(),
465
            "\u{fdfa}".to_string(),
466
            "line\nbreak".to_string(),
467
            "a".repeat(100_000),
468
            "🦀".repeat(50_000),
469
        ]
470
    }
471

            
472
    // ------------------------------------------------------------------
473
    // Helpers — callback harness
474
    // ------------------------------------------------------------------
475

            
476
    /// A `DomLayoutResult` with an *empty* layout tree: the hover handlers only
477
    /// walk `styled_dom.node_hierarchy`, so no real layout (and no font) is
478
    /// needed.
479
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
480
        DomLayoutResult {
481
            styled_dom,
482
            layout_tree: LayoutTree {
483
                nodes: Vec::new(),
484
                warm: Vec::new(),
485
                cold: Vec::new(),
486
                root: 0,
487
                dom_to_layout: BTreeMap::new(),
488
                children_arena: Vec::new(),
489
                children_offsets: Vec::new(),
490
                subtree_needs_intrinsic: Vec::new(),
491
            },
492
            calculated_positions: Vec::new(),
493
            viewport: LogicalRect::zero(),
494
            display_list: Arc::new(DisplayList::default()),
495
            scroll_ids: HashMap::new(),
496
            scroll_id_to_node_id: HashMap::new(),
497
        }
498
    }
499

            
500
    fn node(index: usize) -> NodeHierarchyItemId {
501
        NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(index)))
502
    }
503

            
504
    /// Runs `f` against a `CallbackInfo` whose hit node is `hit`, backed by a
505
    /// `LayoutWindow` holding `styled` (or holding nothing at all, when `styled`
506
    /// is `None`). Returns `f`'s result plus every recorded `CallbackChange`.
507
    fn with_info<R>(
508
        styled: Option<StyledDom>,
509
        hit: NodeHierarchyItemId,
510
        f: impl FnOnce(CallbackInfo) -> R,
511
    ) -> (R, Vec<CallbackChange>) {
512
        let mut layout_window =
513
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
514
        if let Some(sd) = styled {
515
            layout_window
516
                .layout_results
517
                .insert(DomId::ROOT_ID, layout_result(sd));
518
        }
519

            
520
        let renderer_resources = RendererResources::default();
521
        let previous_window_state: Option<FullWindowState> = None;
522
        let current_window_state = FullWindowState::default();
523
        let gl_context = OptionGlContextPtr::None;
524
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
525
            BTreeMap::new();
526
        let window_handle = RawWindowHandle::Unsupported;
527
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
528

            
529
        let ref_data = CallbackInfoRefData {
530
            layout_window: &layout_window,
531
            renderer_resources: &renderer_resources,
532
            previous_window_state: &previous_window_state,
533
            current_window_state: &current_window_state,
534
            gl_context: &gl_context,
535
            current_scroll_manager: &scroll_states,
536
            current_window_handle: &window_handle,
537
            system_callbacks: &system_callbacks,
538
            system_style: Arc::new(SystemStyle::default()),
539
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
540
            #[cfg(feature = "icu")]
541
            icu_localizer: IcuLocalizerHandle::default(),
542
            ctx: OptionRefAny::None,
543
        };
544

            
545
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
546

            
547
        let info = CallbackInfo::new(
548
            &ref_data,
549
            &changes,
550
            DomNodeId {
551
                dom: DomId::ROOT_ID,
552
                node: hit,
553
            },
554
            OptionLogicalPosition::None,
555
            OptionLogicalPosition::None,
556
        );
557

            
558
        let out = f(info);
559
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
560
        (out, recorded)
561
    }
562

            
563
    /// Every recorded CSS write, as `(node index, properties)`.
564
    fn css_writes(changes: &[CallbackChange]) -> Vec<(usize, Vec<CssProperty>)> {
565
        changes
566
            .iter()
567
            .filter_map(|c| match c {
568
                CallbackChange::ChangeNodeCssProperties {
569
                    node_id,
570
                    properties,
571
                    ..
572
                } => Some((node_id.index(), properties.as_ref().to_vec())),
573
                _ => None,
574
            })
575
            .collect()
576
    }
577

            
578
    /// Every recorded opacity write, as `(node index, normalized opacity)`.
579
    fn opacity_writes(changes: &[CallbackChange]) -> Vec<(usize, f32)> {
580
        let mut out = Vec::new();
581
        for (idx, props) in css_writes(changes) {
582
            for p in &props {
583
                if let CssProperty::Opacity(v) = p {
584
                    if let Some(o) = v.get_property() {
585
                        out.push((idx, o.inner.normalized()));
586
                    }
587
                }
588
            }
589
        }
590
        out
591
    }
592

            
593
    /// Index of the first node carrying `class` in a flattened `StyledDom`.
594
    fn index_of_class(styled: &StyledDom, class: &str) -> Option<usize> {
595
        styled.node_data.as_ref().iter().position(|nd| {
596
            nd.get_ids_and_classes()
597
                .as_ref()
598
                .iter()
599
                .any(|c| matches!(c, Class(s) if s.as_str() == class))
600
        })
601
    }
602

            
603
    /// A three-node styled DOM — `root(0)` with children `anchor(1)` and
604
    /// `tip(2)` — i.e. the exact hierarchy `tip_of_wrapper` walks.
605
    fn anchor_tip_dom() -> StyledDom {
606
        let styled = StyledDom::create_from_dom(
607
            Dom::create_div()
608
                .with_child(Dom::create_div())
609
                .with_child(Dom::create_div()),
610
        );
611
        assert_eq!(
612
            styled.node_hierarchy.as_ref().len(),
613
            3,
614
            "fixture must flatten to exactly wrapper/anchor/tip"
615
        );
616
        styled
617
    }
618

            
619
    // ------------------------------------------------------------------
620
    // Tooltip::new / Default
621
    // ------------------------------------------------------------------
622

            
623
    #[test]
624
    fn new_stores_anchor_and_text_verbatim() {
625
        let anchor = Dom::create_div().with_child(
626
            Dom::create_text_do_not_use_without_block_level_wrapper("anchor"),
627
        );
628
        let text = AzString::from("tip".to_string());
629
        let t = Tooltip::new(anchor.clone(), text.clone());
630

            
631
        assert_eq!(t.anchor, anchor, "the anchor must be stored unmodified");
632
        assert_eq!(t.text, text, "the text must be stored unmodified");
633
    }
634

            
635
    #[test]
636
    fn new_uses_the_static_style_tables() {
637
        let t = Tooltip::new(Dom::create_div(), AzString::from_const_str("x"));
638

            
639
        assert_eq!(
640
            t.resolved_wrapper_style(),
641
            CssPropertyWithConditionsVec::from_const_slice(TOOLTIP_WRAPPER_STYLE)
642
        );
643
        assert_eq!(
644
            t.resolved_tip_style(),
645
            CssPropertyWithConditionsVec::from_const_slice(TOOLTIP_TIP_STYLE)
646
        );
647
        assert_eq!(
648
            t.resolved_wrapper_style().len(),
649
            TOOLTIP_WRAPPER_STYLE.len()
650
        );
651
        assert_eq!(
652
            t.resolved_tip_style().as_slice().len(),
653
            TOOLTIP_TIP_STYLE.len()
654
        );
655
    }
656

            
657
    #[test]
658
    fn new_is_pure_and_independent_of_the_arguments() {
659
        // The style tables must not vary with the anchor/text — a widget whose
660
        // styling depended on its content would be unstyleable.
661
        let a = Tooltip::new(Dom::create_div(), AzString::from_const_str(""));
662
        let b = Tooltip::new(nested_anchor(8), AzString::from("🦀".repeat(1000)));
663

            
664
        assert_eq!(a.resolved_wrapper_style(), b.resolved_wrapper_style());
665
        assert_eq!(a.resolved_tip_style(), b.resolved_tip_style());
666
    }
667

            
668
    #[test]
669
    fn new_survives_adversarial_text() {
670
        for s in adversarial_texts() {
671
            let t = Tooltip::new(Dom::create_div(), AzString::from(s.clone()));
672
            assert_eq!(
673
                t.text.as_str(),
674
                s.as_str(),
675
                "text must round-trip byte-for-byte through AzString"
676
            );
677
            assert_eq!(
678
                t.text.as_str().len(),
679
                s.len(),
680
                "byte length must be preserved (no re-encoding / truncation at NUL)"
681
            );
682
        }
683
    }
684

            
685
    #[test]
686
    fn new_with_a_deeply_nested_anchor_keeps_the_child_count_consistent() {
687
        let anchor = nested_anchor(64);
688
        let expected = anchor.estimated_total_children;
689
        let t = Tooltip::new(anchor.clone(), AzString::from_const_str("deep"));
690

            
691
        assert_eq!(t.anchor, anchor);
692
        assert_eq!(
693
            t.anchor.estimated_total_children, expected,
694
            "the constructor must not disturb the anchor's cached descendant count"
695
        );
696
    }
697

            
698
    #[test]
699
    fn new_with_a_very_wide_anchor_does_not_panic() {
700
        let anchor = Dom::create_div().with_children(
701
            (0..2000)
702
                .map(|_| Dom::create_div())
703
                .collect::<Vec<_>>()
704
                .into(),
705
        );
706
        let t = Tooltip::new(anchor, AzString::from_const_str("wide"));
707

            
708
        assert_eq!(t.anchor.children.as_ref().len(), 2000);
709
    }
710

            
711
    #[test]
712
    fn default_is_an_empty_body_anchor_with_empty_text() {
713
        let d = Tooltip::default();
714

            
715
        assert_eq!(d.text.as_str(), "");
716
        assert_eq!(d.anchor, Dom::default());
717
        assert_eq!(
718
            d,
719
            Tooltip::new(Dom::default(), AzString::from_const_str("")),
720
            "Default must agree with the documented constructor call"
721
        );
722
    }
723

            
724
    // ------------------------------------------------------------------
725
    // set_text / with_text
726
    // ------------------------------------------------------------------
727

            
728
    #[test]
729
    fn set_text_and_with_text_agree_and_touch_nothing_else() {
730
        for s in adversarial_texts() {
731
            let base = Tooltip::new(
732
                Dom::create_div()
733
                    .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("a")),
734
                AzString::from_const_str("initial"),
735
            );
736

            
737
            let mut mutated = base.clone();
738
            mutated.set_text(AzString::from(s.clone()));
739
            let built = base.clone().with_text(AzString::from(s.clone()));
740

            
741
            assert_eq!(mutated, built, "with_text must be set_text + self");
742
            assert_eq!(mutated.text.as_str(), s.as_str());
743
            assert_eq!(mutated.anchor, base.anchor, "the anchor must be untouched");
744
            assert_eq!(
745
                mutated.resolved_wrapper_style(),
746
                base.resolved_wrapper_style()
747
            );
748
            assert_eq!(mutated.resolved_tip_style(), base.resolved_tip_style());
749
        }
750
    }
751

            
752
    #[test]
753
    fn set_text_is_last_write_wins() {
754
        let mut t = Tooltip::default();
755
        let huge = "x".repeat(200_000);
756

            
757
        t.set_text(AzString::from(huge.clone()));
758
        assert_eq!(t.text.as_str().len(), huge.len());
759

            
760
        t.set_text(AzString::from_const_str(""));
761
        assert_eq!(t.text.as_str(), "", "a later empty write must win");
762

            
763
        t.set_text(AzString::from("🦀".to_string()));
764
        assert_eq!(t.text.as_str(), "🦀");
765
    }
766

            
767
    #[test]
768
    fn text_and_tip_style_setters_commute() {
769
        let style = style_of(vec![CssProperty::const_opacity(StyleOpacity::const_new(
770
            42,
771
        ))]);
772
        let text = AzString::from("both".to_string());
773

            
774
        let a = Tooltip::default()
775
            .with_text(text.clone())
776
            .with_tip_style(style.clone());
777
        let b = Tooltip::default().with_tip_style(style).with_text(text);
778

            
779
        assert_eq!(a, b, "the two builder setters must be independent");
780
    }
781

            
782
    // ------------------------------------------------------------------
783
    // set_tip_style / with_tip_style
784
    // ------------------------------------------------------------------
785

            
786
    #[test]
787
    fn set_tip_style_and_with_tip_style_agree() {
788
        let style = style_of(vec![
789
            CssProperty::const_position(LayoutPosition::Fixed),
790
            CssProperty::const_opacity(StyleOpacity::const_new(100)),
791
        ]);
792

            
793
        let mut mutated = Tooltip::default();
794
        mutated.set_tip_style(style.clone());
795
        let built = Tooltip::default().with_tip_style(style.clone());
796

            
797
        assert_eq!(mutated, built);
798
        assert_eq!(
799
            mutated.resolved_tip_style(),
800
            style,
801
            "the style must be stored verbatim"
802
        );
803
    }
804

            
805
    #[test]
806
    fn set_tip_style_does_not_touch_the_wrapper_style() {
807
        // The wrapper carries `position: relative`; losing it would make the
808
        // absolutely-positioned tip escape to the nearest positioned ancestor.
809
        let base = Tooltip::default();
810
        let mut t = base.clone();
811
        t.set_tip_style(CssPropertyWithConditionsVec::from_const_slice(&[]));
812

            
813
        assert_eq!(t.resolved_wrapper_style(), base.resolved_wrapper_style());
814
        assert_eq!(t.text, base.text);
815
        assert_eq!(t.anchor, base.anchor);
816
    }
817

            
818
    #[test]
819
    fn tip_style_can_be_emptied_and_the_widget_still_builds() {
820
        let t = Tooltip::new(Dom::create_div(), AzString::from_const_str("naked"))
821
            .with_tip_style(CssPropertyWithConditionsVec::from_const_slice(&[]));
822
        assert_eq!(t.resolved_tip_style().as_slice().len(), 0);
823

            
824
        let dom = t.dom();
825
        let tip = &dom.children.as_ref()[1];
826
        assert!(
827
            inline_properties(tip).is_empty(),
828
            "an empty override must produce an unstyled tip, not the default table"
829
        );
830
        assert_eq!(text_of(tip), Some("naked"));
831
    }
832

            
833
    #[test]
834
    fn a_huge_tip_style_is_stored_verbatim() {
835
        let props: Vec<CssProperty> = (0..10_000)
836
            .map(|i| CssProperty::const_opacity(StyleOpacity::const_new(i % 101)))
837
            .collect();
838
        let style = style_of(props);
839

            
840
        let t = Tooltip::default().with_tip_style(style.clone());
841
        assert_eq!(t.resolved_tip_style().as_slice().len(), 10_000);
842
        assert_eq!(t.resolved_tip_style(), style);
843

            
844
        let dom = t.dom();
845
        assert_eq!(
846
            inline_properties(&dom.children.as_ref()[1]).len(),
847
            10_000,
848
            "every declaration must survive the DOM build"
849
        );
850
    }
851

            
852
    // ------------------------------------------------------------------
853
    // swap_with_default
854
    // ------------------------------------------------------------------
855

            
856
    #[test]
857
    fn swap_with_default_returns_the_old_value_and_leaves_a_default() {
858
        let original = Tooltip::new(
859
            Dom::create_div().with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
860
                "anchor",
861
            )),
862
            AzString::from("tip".to_string()),
863
        )
864
        .with_tip_style(style_of(vec![CssProperty::const_opacity(
865
            StyleOpacity::const_new(7),
866
        )]));
867

            
868
        let mut t = original.clone();
869
        let taken = t.swap_with_default();
870

            
871
        assert_eq!(taken, original, "the previous value must be handed back");
872
        assert_eq!(t, Tooltip::default(), "self must be left as a default");
873
    }
874

            
875
    #[test]
876
    fn swap_with_default_is_stable_under_repetition() {
877
        let mut t = Tooltip::default().with_text(AzString::from("a".repeat(50_000)));
878

            
879
        let first = t.swap_with_default();
880
        assert_eq!(first.text.as_str().len(), 50_000);
881

            
882
        for _ in 0..10 {
883
            let again = t.swap_with_default();
884
            assert_eq!(again, Tooltip::default());
885
            assert_eq!(t, Tooltip::default());
886
        }
887
    }
888

            
889
    #[test]
890
    fn swap_with_default_on_a_default_is_an_identity() {
891
        let mut t = Tooltip::default();
892
        let taken = t.swap_with_default();
893

            
894
        assert_eq!(taken, Tooltip::default());
895
        assert_eq!(t, Tooltip::default());
896
    }
897

            
898
    // ------------------------------------------------------------------
899
    // Static style tables
900
    // ------------------------------------------------------------------
901

            
902
    #[test]
903
    fn tip_style_starts_hidden_with_exactly_one_opacity_declaration() {
904
        // Two opacity declarations would make the last one win and could leave
905
        // the tip permanently visible.
906
        assert_eq!(
907
            declared_opacities(&CssPropertyWithConditionsVec::from_const_slice(
908
                TOOLTIP_TIP_STYLE
909
            )),
910
            vec![0.0],
911
            "the tip must be hidden by default via a single opacity declaration"
912
        );
913
    }
914

            
915
    #[test]
916
    fn tip_style_is_absolutely_positioned_and_does_not_wrap() {
917
        let style = CssPropertyWithConditionsVec::from_const_slice(TOOLTIP_TIP_STYLE);
918

            
919
        assert_eq!(declared_positions(&style), vec![LayoutPosition::Absolute]);
920
        assert!(
921
            style
922
                .as_ref()
923
                .contains(&CssPropertyWithConditions::simple(CssProperty::const_top(
924
                    LayoutTop::const_px(TIP_OFFSET_Y)
925
                ))),
926
            "the documented vertical offset must be declared"
927
        );
928
        assert!(
929
            style
930
                .as_ref()
931
                .contains(&CssPropertyWithConditions::simple(CssProperty::WhiteSpace(
932
                    StyleWhiteSpaceValue::Exact(StyleWhiteSpace::Nowrap)
933
                ))),
934
            "the tip must stay on one line"
935
        );
936
    }
937

            
938
    #[test]
939
    fn wrapper_style_is_an_inline_block_positioning_context() {
940
        let style = CssPropertyWithConditionsVec::from_const_slice(TOOLTIP_WRAPPER_STYLE);
941

            
942
        assert_eq!(declared_displays(&style), vec![LayoutDisplay::InlineBlock]);
943
        assert_eq!(
944
            declared_positions(&style),
945
            vec![LayoutPosition::Relative],
946
            "without `position: relative` the tip would anchor to some ancestor"
947
        );
948
        assert!(
949
            style.as_ref().contains(&CssPropertyWithConditions::simple(
950
                CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))
951
            )),
952
            "the wrapper must not grow past the anchor"
953
        );
954
    }
955

            
956
    #[test]
957
    fn neither_style_table_declares_a_property_type_twice() {
958
        for (name, table) in [
959
            ("wrapper", TOOLTIP_WRAPPER_STYLE),
960
            ("tip", TOOLTIP_TIP_STYLE),
961
        ] {
962
            let style = CssPropertyWithConditionsVec::from_const_slice(table);
963
            let mut types = prop_types(&style);
964
            let declared = types.len();
965
            assert!(declared > 0, "{name} style must not be empty");
966
            types.sort_unstable();
967
            types.dedup();
968
            assert_eq!(
969
                types.len(),
970
                declared,
971
                "{name}: a duplicated property type would make the later declaration silently win"
972
            );
973
        }
974
    }
975

            
976
    #[test]
977
    fn both_style_tables_apply_unconditionally() {
978
        for table in [TOOLTIP_WRAPPER_STYLE, TOOLTIP_TIP_STYLE] {
979
            assert!(
980
                table.iter().all(|p| p.apply_if.as_ref().is_empty()),
981
                "a stray condition would leave the tooltip unstyled"
982
            );
983
        }
984
    }
985

            
986
    #[test]
987
    fn tip_colours_are_opaque_enough_to_read() {
988
        assert!(
989
            TIP_BG_COLOR.a > 200,
990
            "a near-transparent tip background would be unreadable"
991
        );
992
        assert_eq!(TIP_TEXT_COLOR.a, 255);
993
        assert!(TIP_RADIUS >= 0 && TIP_OFFSET_Y > 0);
994
    }
995

            
996
    // ------------------------------------------------------------------
997
    // Tooltip::dom
998
    // ------------------------------------------------------------------
999

            
    #[test]
    fn dom_builds_a_wrapper_with_the_anchor_then_the_tip() {
        let anchor = Dom::create_div().with_child(
            Dom::create_text_do_not_use_without_block_level_wrapper("anchor"),
        );
        let dom = Tooltip::new(anchor.clone(), AzString::from_const_str("tip")).dom();
        assert!(has_class(&dom, WRAPPER_CLASS_NAME));
        assert_eq!(dom.root.get_node_type(), &NodeType::Div);
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 2, "children must be exactly [anchor, tip]");
        assert_eq!(children[0], anchor, "child 0 must be the anchor, verbatim");
        assert!(
            has_class(&children[1], TIP_CLASS_NAME),
            "child 1 must be the tip"
        );
        assert_eq!(text_of(&children[1]), Some("tip"));
        assert_eq!(
            inline_properties(&children[1]).len(),
            TOOLTIP_TIP_STYLE.len(),
            "the tip must carry the full tip style"
        );
        assert_eq!(
            inline_properties(&dom).len(),
            TOOLTIP_WRAPPER_STYLE.len(),
            "the wrapper must carry the full wrapper style"
        );
    }
    #[test]
    fn dom_preserves_adversarial_text_byte_for_byte() {
        for s in adversarial_texts() {
            let dom = Tooltip::new(Dom::create_div(), AzString::from(s.clone())).dom();
            let tip = &dom.children.as_ref()[1];
            assert_eq!(
                text_of(tip),
                Some(s.as_str()),
                "the tip text must survive the DOM build unchanged"
            );
        }
    }
    #[test]
    fn dom_applies_a_custom_tip_style_to_the_tip_only() {
        let custom = style_of(vec![CssProperty::const_opacity(StyleOpacity::const_new(
            100,
        ))]);
        let dom = Tooltip::new(Dom::create_div(), AzString::from_const_str("t"))
            .with_tip_style(custom.clone())
            .dom();
        assert_eq!(
            inline_properties(&dom.children.as_ref()[1]),
            vec![CssProperty::const_opacity(StyleOpacity::const_new(100))],
            "the override must replace the default tip table"
        );
        assert_eq!(
            inline_properties(&dom).len(),
            TOOLTIP_WRAPPER_STYLE.len(),
            "the wrapper must keep its own style"
        );
    }
    #[test]
    fn dom_binds_exactly_mouse_enter_and_mouse_leave_on_the_wrapper() {
        let dom = Tooltip::new(Dom::create_div(), AzString::from_const_str("t")).dom();
        let callbacks = dom.root.callbacks.as_ref();
        assert_eq!(
            callbacks.len(),
            2,
            "exactly two hover handlers are expected"
        );
        assert_eq!(
            callbacks[0].event,
            EventFilter::Hover(HoverEventFilter::MouseEnter)
        );
        assert_eq!(
            callbacks[1].event,
            EventFilter::Hover(HoverEventFilter::MouseLeave)
        );
        assert_eq!(callbacks[0].callback.cb, on_tooltip_enter as usize);
        assert_eq!(callbacks[1].callback.cb, on_tooltip_leave as usize);
        assert!(matches!(callbacks[0].callback.ctx, OptionRefAny::None));
        assert!(matches!(callbacks[1].callback.ctx, OptionRefAny::None));
        assert_eq!(
            callbacks[0].refany, callbacks[1].refany,
            "both handlers must share one marker RefAny (they are stateless)"
        );
    }
    #[test]
    fn dom_binds_no_callbacks_on_the_anchor_or_the_tip() {
        let dom = Tooltip::new(
            Dom::create_div()
                .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("a")),
            AzString::from_const_str("t"),
        )
        .dom();
        for (i, child) in dom.children.as_ref().iter().enumerate() {
            assert!(
                child.root.callbacks.as_ref().is_empty(),
                "child {i} must not carry hover handlers of its own"
            );
        }
    }
    #[test]
    fn from_impl_matches_dom_structurally() {
        // `dom()` mints a fresh marker `RefAny` per call, so the two DOMs are
        // deliberately compared field-by-field rather than with `==`.
        let make = || {
            Tooltip::new(
                Dom::create_div()
                    .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("a")),
                AzString::from_const_str("tip"),
            )
        };
        let via_from = Dom::from(make());
        let via_dom = make().dom();
        assert_eq!(via_from.root.get_node_type(), via_dom.root.get_node_type());
        assert_eq!(
            via_from.root.get_ids_and_classes().as_ref(),
            via_dom.root.get_ids_and_classes().as_ref()
        );
        assert_eq!(via_from.root.style, via_dom.root.style);
        assert_eq!(via_from.children.as_ref(), via_dom.children.as_ref());
        assert_eq!(
            via_from.estimated_total_children,
            via_dom.estimated_total_children
        );
        let (a, b) = (
            via_from.root.callbacks.as_ref(),
            via_dom.root.callbacks.as_ref(),
        );
        assert_eq!(a.len(), b.len());
        for (x, y) in a.iter().zip(b.iter()) {
            assert_eq!(x.event, y.event);
            assert_eq!(x.callback.cb, y.callback.cb);
        }
    }
    #[test]
    fn dom_keeps_the_estimated_child_count_consistent_with_the_flattened_tree() {
        // A too-small `estimated_total_children` makes the arena conversion
        // under-allocate and panic on out-of-bounds writes.
        for depth in [0, 1, 8, 64] {
            let dom = Tooltip::new(nested_anchor(depth), AzString::from_const_str("t")).dom();
            let estimated = dom.estimated_total_children;
            let flattened = StyledDom::create_from_dom(dom)
                .node_hierarchy
                .as_ref()
                .len();
            assert_eq!(
                flattened,
                estimated + 1,
                "depth {depth}: the cached descendant count disagrees with the flattened tree"
            );
        }
    }
    #[test]
    fn dom_of_a_very_wide_anchor_flattens_without_panicking() {
        let anchor = Dom::create_div().with_children(
            (0..2000)
                .map(|_| Dom::create_div())
                .collect::<Vec<_>>()
                .into(),
        );
        let dom = Tooltip::new(anchor, AzString::from_const_str("wide")).dom();
        let styled = StyledDom::create_from_dom(dom);
        assert_eq!(
            styled.node_hierarchy.as_ref().len(),
            1 + 1 + 2000 + 2,
            "wrapper + anchor + 2000 grandchildren + tip <p> + tip text"
        );
    }
    #[test]
    fn dom_of_nested_tooltips_keeps_each_tip_as_the_second_child() {
        let inner = Tooltip::new(Dom::create_div(), AzString::from_const_str("inner")).dom();
        let outer = Tooltip::new(inner, AzString::from_const_str("outer")).dom();
        let outer_children = outer.children.as_ref();
        assert_eq!(outer_children.len(), 2);
        assert_eq!(text_of(&outer_children[1]), Some("outer"));
        let inner_children = outer_children[0].children.as_ref();
        assert_eq!(inner_children.len(), 2);
        assert_eq!(text_of(&inner_children[1]), Some("inner"));
    }
    // ------------------------------------------------------------------
    // tip_of_wrapper
    // ------------------------------------------------------------------
    #[test]
    fn tip_of_wrapper_without_a_layout_result_is_none() {
        let (tip, changes) = with_info(None, node(0), |info| tip_of_wrapper(&info));
        assert_eq!(tip, None);
        assert!(changes.is_empty());
    }
    #[test]
    fn tip_of_wrapper_with_a_stale_hit_node_is_none() {
        for stale in [3usize, 999, usize::MAX / 2] {
            let (tip, _) = with_info(Some(anchor_tip_dom()), node(stale), |info| {
                tip_of_wrapper(&info)
            });
            assert_eq!(
                tip, None,
                "node {stale} does not exist in the 3-node fixture"
            );
        }
    }
    #[test]
    fn tip_of_wrapper_with_a_none_hit_node_is_none() {
        let (tip, _) = with_info(Some(anchor_tip_dom()), NodeHierarchyItemId::NONE, |info| {
            tip_of_wrapper(&info)
        });
        assert_eq!(tip, None, "an unset hit node must not resolve to a tip");
    }
    #[test]
    fn tip_of_wrapper_on_a_childless_node_is_none() {
        // node 1 is a leaf -> no first child -> no tip.
        let (tip, _) = with_info(Some(anchor_tip_dom()), node(1), |info| {
            tip_of_wrapper(&info)
        });
        assert_eq!(tip, None);
    }
    #[test]
    fn tip_of_wrapper_without_a_second_child_is_none() {
        let styled = StyledDom::create_from_dom(Dom::create_div().with_child(Dom::create_div()));
        let (tip, _) = with_info(Some(styled), node(0), |info| tip_of_wrapper(&info));
        assert_eq!(
            tip, None,
            "a wrapper with a single child has no tip to reveal"
        );
    }
    #[test]
    fn tip_of_wrapper_returns_the_second_child() {
        let (tip, _) = with_info(Some(anchor_tip_dom()), node(0), |info| {
            tip_of_wrapper(&info)
        });
        assert_eq!(
            tip.and_then(|t| t.node.into_crate_internal())
                .map(|n| n.index()),
            Some(2)
        );
    }
    #[test]
    fn tip_of_wrapper_finds_the_tip_of_a_real_tooltip_dom() {
        // The anchor has a subtree of its own, so the tip is *not* simply
        // `hit + 1` — the handler must walk first-child -> next-sibling.
        let dom = Tooltip::new(nested_anchor(3), AzString::from_const_str("tip")).dom();
        let styled = StyledDom::create_from_dom(dom);
        let wrapper = index_of_class(&styled, WRAPPER_CLASS_NAME).expect("wrapper class missing");
        let expected = index_of_class(&styled, TIP_CLASS_NAME).expect("tip class missing");
        assert!(
            expected > wrapper + 1,
            "fixture must have a non-trivial anchor subtree between wrapper and tip"
        );
        let (tip, _) = with_info(Some(styled), node(wrapper), |info| tip_of_wrapper(&info));
        assert_eq!(
            tip.and_then(|t| t.node.into_crate_internal())
                .map(|n| n.index()),
            Some(expected)
        );
    }
    // ------------------------------------------------------------------
    // on_tooltip_enter / on_tooltip_leave
    // ------------------------------------------------------------------
    #[test]
    fn enter_reveals_and_leave_hides_exactly_the_tip() {
        for (name, handler, expected) in [
            (
                "enter",
                on_tooltip_enter as extern "C" fn(RefAny, CallbackInfo) -> Update,
                1.0_f32,
            ),
            (
                "leave",
                on_tooltip_leave as extern "C" fn(RefAny, CallbackInfo) -> Update,
                0.0_f32,
            ),
        ] {
            let (update, changes) = with_info(Some(anchor_tip_dom()), node(0), |info| {
                handler(RefAny::new(()), info)
            });
            assert_eq!(update, Update::DoNothing, "{name} must not relayout");
            assert_eq!(
                opacity_writes(&changes),
                vec![(2, expected)],
                "{name} must write exactly one opacity, on the tip node"
            );
            let writes = css_writes(&changes);
            assert_eq!(
                writes.len(),
                changes.len(),
                "{name} must only record CSS writes"
            );
            assert_eq!(writes[0].1.len(), 1, "{name} must write a single property");
        }
    }
    #[test]
    fn leave_restores_the_opacity_declared_in_the_static_tip_style() {
        // Round-trip: what the handler writes on leave must be exactly what the
        // stylesheet declares, otherwise the tip would not return to its
        // initial rendering.
        let declared = declared_opacities(&CssPropertyWithConditionsVec::from_const_slice(
            TOOLTIP_TIP_STYLE,
        ));
        let (_, changes) = with_info(Some(anchor_tip_dom()), node(0), |info| {
            on_tooltip_leave(RefAny::new(()), info)
        });
        assert_eq!(
            opacity_writes(&changes)
                .iter()
                .map(|(_, o)| *o)
                .collect::<Vec<_>>(),
            declared
        );
    }
    #[test]
    fn enter_then_leave_is_a_round_trip() {
        let enter = with_info(Some(anchor_tip_dom()), node(0), |info| {
            on_tooltip_enter(RefAny::new(()), info)
        })
        .1;
        let leave = with_info(Some(anchor_tip_dom()), node(0), |info| {
            on_tooltip_leave(RefAny::new(()), info)
        })
        .1;
        let (e, l) = (opacity_writes(&enter), opacity_writes(&leave));
        assert_eq!(e.len(), 1);
        assert_eq!(l.len(), 1);
        assert_eq!(e[0].0, l[0].0, "both must target the same node");
        assert!(
            e[0].1 > l[0].1,
            "enter must make the tip more visible than leave ({} vs {})",
            e[0].1,
            l[0].1
        );
        assert_eq!((e[0].1, l[0].1), (1.0, 0.0));
    }
    #[test]
    fn handlers_are_noops_when_there_is_no_tip() {
        let fixtures: Vec<(&str, Option<StyledDom>, NodeHierarchyItemId)> = vec![
            ("no layout result", None, node(0)),
            ("stale hit node", Some(anchor_tip_dom()), node(999)),
            (
                "none hit node",
                Some(anchor_tip_dom()),
                NodeHierarchyItemId::NONE,
            ),
            ("leaf hit node", Some(anchor_tip_dom()), node(1)),
            (
                "single child",
                Some(StyledDom::create_from_dom(
                    Dom::create_div().with_child(Dom::create_div()),
                )),
                node(0),
            ),
        ];
        for (name, styled, hit) in fixtures {
            for handler in [
                on_tooltip_enter as extern "C" fn(RefAny, CallbackInfo) -> Update,
                on_tooltip_leave as extern "C" fn(RefAny, CallbackInfo) -> Update,
            ] {
                let (update, changes) =
                    with_info(styled.clone(), hit, |info| handler(RefAny::new(()), info));
                assert_eq!(update, Update::DoNothing, "{name}");
                assert!(
                    changes.is_empty(),
                    "{name}: nothing may be restyled without a tip"
                );
            }
        }
    }
    #[test]
    fn handlers_ignore_their_payload() {
        // The handlers are stateless — a foreign (or even empty) payload must
        // not change what they do.
        for data in [
            RefAny::new(()),
            RefAny::new(0xdead_beef_u64),
            RefAny::new(()),
        ] {
            let (update, changes) = with_info(Some(anchor_tip_dom()), node(0), |info| {
                on_tooltip_enter(data.clone(), info)
            });
            assert_eq!(update, Update::DoNothing);
            assert_eq!(opacity_writes(&changes), vec![(2, 1.0)]);
        }
    }
    #[test]
    fn repeated_enter_is_idempotent() {
        let mut all = Vec::new();
        for _ in 0..64 {
            let (update, changes) = with_info(Some(anchor_tip_dom()), node(0), |info| {
                on_tooltip_enter(RefAny::new(()), info)
            });
            assert_eq!(update, Update::DoNothing);
            all.push(opacity_writes(&changes));
        }
        assert!(
            all.iter().all(|w| *w == vec![(2, 1.0)]),
            "repeated hovers must keep producing the same single write"
        );
    }
    #[test]
    fn handlers_never_restyle_the_wrapper_or_the_anchor() {
        let dom = Tooltip::new(nested_anchor(2), AzString::from_const_str("tip")).dom();
        let styled = StyledDom::create_from_dom(dom);
        let wrapper = index_of_class(&styled, WRAPPER_CLASS_NAME).expect("wrapper class missing");
        let tip = index_of_class(&styled, TIP_CLASS_NAME).expect("tip class missing");
        for handler in [
            on_tooltip_enter as extern "C" fn(RefAny, CallbackInfo) -> Update,
            on_tooltip_leave as extern "C" fn(RefAny, CallbackInfo) -> Update,
        ] {
            let (_, changes) = with_info(Some(styled.clone()), node(wrapper), |info| {
                handler(RefAny::new(()), info)
            });
            let touched: Vec<usize> = css_writes(&changes).into_iter().map(|(i, _)| i).collect();
            assert_eq!(
                touched,
                vec![tip],
                "only the tip may be restyled, never the wrapper or the anchor subtree"
            );
        }
    }
    #[test]
    fn hovering_the_tip_itself_does_nothing() {
        let dom = Tooltip::new(Dom::create_div(), AzString::from_const_str("tip")).dom();
        let styled = StyledDom::create_from_dom(dom);
        let tip = index_of_class(&styled, TIP_CLASS_NAME).expect("tip class missing");
        let (update, changes) = with_info(Some(styled), node(tip), |info| {
            on_tooltip_enter(RefAny::new(()), info)
        });
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "the tip is a leaf text node — it has no tip of its own"
        );
    }
    #[test]
    fn every_written_property_is_an_opacity() {
        for handler in [
            on_tooltip_enter as extern "C" fn(RefAny, CallbackInfo) -> Update,
            on_tooltip_leave as extern "C" fn(RefAny, CallbackInfo) -> Update,
        ] {
            let (_, changes) = with_info(Some(anchor_tip_dom()), node(0), |info| {
                handler(RefAny::new(()), info)
            });
            for (_, props) in css_writes(&changes) {
                for p in props {
                    assert_eq!(
                        p.get_type(),
                        opacity_ty(),
                        "the hover handlers must only toggle opacity"
                    );
                }
            }
        }
    }
}