1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod audit_tests {
5
    use super::*;
6

            
7
    #[test]
8
1
    fn node_count_matches_recompute() {
9
        // root + [A(+grandchild), B] = 3 descendants, node_count 4.
10
1
        let dom = Dom::create_div()
11
1
            .with_child(Dom::create_div().with_child(Dom::create_div()))
12
1
            .with_child(Dom::create_div());
13
1
        assert_eq!(
14
            dom.estimated_total_children,
15
1
            dom.recompute_estimated_total_children()
16
        );
17
1
        assert_eq!(dom.estimated_total_children, 3);
18
1
        assert_eq!(dom.node_count(), 4);
19
1
    }
20

            
21
    #[test]
22
1
    fn single_node_dom_node_count() {
23
1
        let dom = Dom::create_div();
24
1
        assert_eq!(dom.estimated_total_children, 0);
25
1
        assert_eq!(dom.node_count(), 1);
26
1
        assert_eq!(dom.recompute_estimated_total_children(), 0);
27
1
    }
28

            
29
    #[test]
30
1
    fn fixup_repairs_desynced_estimate() {
31
1
        let mut dom = Dom::create_div().with_child(Dom::create_div());
32
        // Corrupt the public cached field directly.
33
1
        dom.estimated_total_children = 999;
34
1
        let repaired = dom.fixup_children_estimated();
35
1
        assert_eq!(repaired, 1);
36
1
        assert_eq!(
37
            dom.estimated_total_children,
38
1
            dom.recompute_estimated_total_children()
39
        );
40
1
    }
41

            
42
    // The debug_assert only fires with debug_assertions enabled.
43
    #[cfg(debug_assertions)]
44
    #[test]
45
    #[should_panic(expected = "desynced")]
46
    fn add_child_with_stale_estimate_panics_in_debug() {
47
        let mut child = Dom::create_div().with_child(Dom::create_div());
48
        child.estimated_total_children = 0; // corrupt: should be 1
49
        let mut parent = Dom::create_div();
50
        parent.add_child(child);
51
    }
52

            
53
    // NodeData carries a manual `unsafe impl Send`. This is a compile-time
54
    // assertion that the marker holds (fails to build if a non-Send field is
55
    // ever added), documenting the invariant the unsafe impl relies on.
56
    #[test]
57
1
    fn node_data_is_send() {
58
1
        fn assert_send<T: Send>() {}
59
1
        assert_send::<NodeData>();
60
1
    }
61

            
62
    // Exercises the `core::ptr::write` unsafe path in `copy_special_moving_complex`:
63
    // the boxed Text `node_type` must be MOVED bitwise into the copy (box pointer
64
    // preserved, string intact), `self.node_type` must be left as `Div`, and the
65
    // moved-out `style`/`extra` must land on the copy. Small heap-only tree, so
66
    // Miri can validate the raw write / box ownership transfer for UB.
67
    #[test]
68
1
    fn copy_special_moving_complex_moves_text_node_type() {
69
1
        let mut nd = NodeData::create_text_do_not_use_without_block_level_wrapper("hello")
70
1
            .with_css("color: red;");
71
1
        assert!(!nd.style.rules.is_empty(), "precondition: style set");
72

            
73
1
        let copy = nd.copy_special_moving_complex();
74

            
75
        // The Text box was transferred to the copy with its string intact.
76
1
        match copy.get_node_type() {
77
1
            NodeType::Text(s) => assert_eq!(s.as_ref().as_str(), "hello"),
78
            other => panic!("expected Text node_type on copy, got {other:?}"),
79
        }
80
        // The source's node_type was replaced with the heap-free Div placeholder.
81
1
        assert!(matches!(nd.get_node_type(), NodeType::Div));
82
        // `style` was moved out of `self` onto the copy.
83
1
        assert!(nd.style.rules.is_empty());
84
1
        assert!(!copy.style.rules.is_empty());
85
1
    }
86

            
87
    // A non-boxed (Div) node_type must also survive the ptr::write path unchanged.
88
    #[test]
89
1
    fn copy_special_moving_complex_moves_div_node_type() {
90
1
        let mut nd = NodeData::create_div();
91
1
        let copy = nd.copy_special_moving_complex();
92
1
        assert!(matches!(copy.get_node_type(), NodeType::Div));
93
1
        assert!(matches!(nd.get_node_type(), NodeType::Div));
94
1
    }
95
}
96

            
97
#[cfg(test)]
98
#[allow(clippy::cast_possible_wrap, clippy::too_many_lines)]
99
mod autotest_generated {
100
    use super::*;
101

            
102
    // ---------------------------------------------------------------------
103
    // upsert_inline_css_property
104
    // ---------------------------------------------------------------------
105

            
106
    /// The runtime-patch upsert must REPLACE the unconditional declaration of
107
    /// the same type, KEEP every other inline property (the content
108
    /// chokepoint used to wipe the whole inline style, so a patched panel
109
    /// lost its `position: absolute`), KEEP conditional declarations, and
110
    /// stay bounded under repeated toggles.
111
    #[test]
112
    fn upsert_inline_css_property_replaces_only_the_unconditional_same_type() {
113
        use azul_css::{
114
            dynamic_selector::{CssPropertyWithConditions, DynamicSelector, PseudoStateType},
115
            props::{
116
                layout::{display::LayoutDisplay, position::LayoutPosition},
117
                property::{CssProperty, CssPropertyType},
118
            },
119
        };
120

            
121
        let mut node = NodeData::create_div();
122
        node.set_css_props(
123
            vec![
124
                CssPropertyWithConditions::simple(CssProperty::const_position(
125
                    LayoutPosition::Absolute,
126
                )),
127
                CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::None)),
128
                // A conditional (hover) display declaration must survive.
129
                CssPropertyWithConditions {
130
                    property: CssProperty::const_display(LayoutDisplay::Block),
131
                    apply_if: vec![DynamicSelector::PseudoState(PseudoStateType::Hover)].into(),
132
                },
133
            ]
134
            .into(),
135
        );
136

            
137
        node.upsert_inline_css_property(CssProperty::const_display(LayoutDisplay::Flex));
138

            
139
        let collect = |node: &NodeData| -> Vec<(CssProperty, bool)> {
140
            node.style
141
                .iter_inline_properties()
142
                .map(|(p, conds)| (p.clone(), conds.as_ref().is_empty()))
143
                .collect()
144
        };
145

            
146
        let props = collect(&node);
147
        let unconditional_displays: Vec<&CssProperty> = props
148
            .iter()
149
            .filter(|(p, uncond)| *uncond && p.get_type() == CssPropertyType::Display)
150
            .map(|(p, _)| p)
151
            .collect();
152
        assert_eq!(
153
            unconditional_displays,
154
            vec![&CssProperty::const_display(LayoutDisplay::Flex)],
155
            "exactly ONE unconditional display remains: the patched value"
156
        );
157
        assert!(
158
            props.iter().any(|(p, uncond)| *uncond
159
                && *p == CssProperty::const_position(LayoutPosition::Absolute)),
160
            "unrelated inline properties must survive the patch"
161
        );
162
        assert!(
163
            props
164
                .iter()
165
                .any(|(p, uncond)| !*uncond
166
                    && *p == CssProperty::const_display(LayoutDisplay::Block)),
167
            "conditional (hover) declarations must survive the patch"
168
        );
169

            
170
        // Toggle many times: the style must not grow without bound.
171
        let len_before = node.style.rules.as_ref().len();
172
        for i in 0..20 {
173
            let v = if i % 2 == 0 {
174
                LayoutDisplay::None
175
            } else {
176
                LayoutDisplay::Flex
177
            };
178
            node.upsert_inline_css_property(CssProperty::const_display(v));
179
        }
180
        assert_eq!(
181
            node.style.rules.as_ref().len(),
182
            len_before,
183
            "repeated upserts of the same type must not grow the inline style"
184
        );
185
    }
186

            
187
    // ---------------------------------------------------------------------
188
    // helpers
189
    // ---------------------------------------------------------------------
190

            
191
    fn hash_of<T: Hash>(t: &T) -> u64 {
192
        let mut h = crate::hash::DefaultHasher::new();
193
        t.hash(&mut h);
194
        h.finish()
195
    }
196

            
197
    extern "C" fn merge_cb_a(new_data: RefAny, _old: RefAny) -> RefAny {
198
        new_data
199
    }
200

            
201
    extern "C" fn merge_cb_b(_new: RefAny, old_data: RefAny) -> RefAny {
202
        old_data
203
    }
204

            
205
    /// A `VirtualViewCallbackType`-shaped stub. Never invoked — the tests only need
206
    /// a well-typed callback to hang off a `NodeType::VirtualView` node.
207
    extern "C" fn virtual_view_cb(
208
        _data: RefAny,
209
        _info: crate::callbacks::VirtualViewCallbackInfo,
210
    ) -> crate::callbacks::VirtualViewReturn {
211
        unreachable!("virtual view callback is never invoked by these tests")
212
    }
213

            
214
    fn virtual_view_callback() -> VirtualViewCallback {
215
        VirtualViewCallback {
216
            cb: virtual_view_cb,
217
            ctx: OptionRefAny::None,
218
        }
219
    }
220

            
221
    /// A ~100k-char string with multi-byte codepoints, for "huge input" cases.
222
    fn huge_unicode_string() -> String {
223
        "ä🎉本".repeat(25_000)
224
    }
225

            
226
    /// Every `AttributeType` variant, so invariant sweeps can't silently miss one.
227
    fn all_attribute_variants() -> Vec<AttributeType> {
228
        let nv = || AttributeNameValue {
229
            attr_name: "data-x".into(),
230
            value: "v".into(),
231
        };
232
        vec![
233
            AttributeType::Id("i".into()),
234
            AttributeType::Class("c".into()),
235
            AttributeType::AriaLabel("l".into()),
236
            AttributeType::AriaLabelledBy("lb".into()),
237
            AttributeType::AriaDescribedBy("db".into()),
238
            AttributeType::AriaRole("r".into()),
239
            AttributeType::AriaState(nv()),
240
            AttributeType::AriaProperty(nv()),
241
            AttributeType::Href("h".into()),
242
            AttributeType::Rel("rel".into()),
243
            AttributeType::Target("t".into()),
244
            AttributeType::Src("s".into()),
245
            AttributeType::Alt("a".into()),
246
            AttributeType::Title("ti".into()),
247
            AttributeType::Name("n".into()),
248
            AttributeType::Value("v".into()),
249
            AttributeType::InputType("text".into()),
250
            AttributeType::Placeholder("p".into()),
251
            AttributeType::Required,
252
            AttributeType::Disabled,
253
            AttributeType::Readonly,
254
            AttributeType::CheckedTrue,
255
            AttributeType::CheckedFalse,
256
            AttributeType::Selected,
257
            AttributeType::Max("10".into()),
258
            AttributeType::Min("0".into()),
259
            AttributeType::Step("1".into()),
260
            AttributeType::Pattern(".*".into()),
261
            AttributeType::MinLength(i32::MIN),
262
            AttributeType::MaxLength(i32::MAX),
263
            AttributeType::Autocomplete("off".into()),
264
            AttributeType::Scope("row".into()),
265
            AttributeType::ColSpan(-1),
266
            AttributeType::RowSpan(0),
267
            AttributeType::TabIndex(i32::MIN),
268
            AttributeType::Focusable,
269
            AttributeType::Lang("en".into()),
270
            AttributeType::Dir("rtl".into()),
271
            AttributeType::ContentEditable(true),
272
            AttributeType::Draggable(false),
273
            AttributeType::Hidden,
274
            AttributeType::Data(nv()),
275
            AttributeType::Custom(nv()),
276
        ]
277
    }
278

            
279
    /// A spread of `NodeType`s, including every payload-carrying variant.
280
    fn representative_node_types() -> Vec<NodeType> {
281
        vec![
282
            NodeType::Html,
283
            NodeType::Body,
284
            NodeType::Div,
285
            NodeType::Br,
286
            NodeType::Button,
287
            NodeType::Input,
288
            NodeType::TextArea,
289
            NodeType::Select,
290
            NodeType::A,
291
            NodeType::H1,
292
            NodeType::H6,
293
            NodeType::Table,
294
            NodeType::Td,
295
            NodeType::Svg,
296
            NodeType::SvgPath,
297
            NodeType::SvgText("svg text".into()),
298
            NodeType::SvgImage(ImageRef::null_image(
299
                1,
300
                1,
301
                crate::resources::RawImageFormat::R8,
302
                Vec::new(),
303
            )),
304
            NodeType::Before,
305
            NodeType::After,
306
            NodeType::Marker,
307
            NodeType::Placeholder,
308
            NodeType::Text(BoxOrStatic::heap(AzString::from("hello"))),
309
            NodeType::Image(BoxOrStatic::heap(ImageRef::null_image(
310
                2,
311
                2,
312
                crate::resources::RawImageFormat::RGBA8,
313
                Vec::new(),
314
            ))),
315
            NodeType::VirtualView,
316
            NodeType::Icon(BoxOrStatic::heap(AzString::from("home"))),
317
            NodeType::GeolocationProbe(crate::geolocation::GeolocationProbeConfig::default()),
318
        ]
319
    }
320

            
321
    // =====================================================================
322
    // NodeFlags — bit-packing round-trips, boundaries, field independence
323
    // =====================================================================
324

            
325
    #[test]
326
    fn node_flags_new_is_empty_and_matches_default() {
327
        let f = NodeFlags::new();
328
        assert_eq!(f.inner, 0);
329
        assert_eq!(f, NodeFlags::default());
330
        assert!(!f.is_contenteditable());
331
        assert!(!f.is_anonymous());
332
        assert_eq!(f.get_tab_index(), None);
333
    }
334

            
335
    #[test]
336
    fn node_flags_tab_index_round_trips_for_all_variants() {
337
        for ti in [
338
            None,
339
            Some(TabIndex::Auto),
340
            Some(TabIndex::NoKeyboardFocus),
341
            Some(TabIndex::OverrideInParent(0)),
342
            Some(TabIndex::OverrideInParent(1)),
343
            Some(TabIndex::OverrideInParent(1_000)),
344
        ] {
345
            let mut f = NodeFlags::new();
346
            f.set_tab_index(ti);
347
            assert_eq!(f.get_tab_index(), ti, "round-trip failed for {ti:?}");
348
        }
349
    }
350

            
351
    #[test]
352
    fn node_flags_tab_index_round_trips_at_the_28_bit_boundary() {
353
        // The value field is bits [27:0], so 2^28 - 1 is the largest exactly
354
        // representable OverrideInParent value.
355
        const MAX_EXACT: u32 = (1 << 28) - 1;
356
        let mut f = NodeFlags::new();
357
        f.set_tab_index(Some(TabIndex::OverrideInParent(MAX_EXACT)));
358
        assert_eq!(
359
            f.get_tab_index(),
360
            Some(TabIndex::OverrideInParent(MAX_EXACT))
361
        );
362
    }
363

            
364
    #[test]
365
    fn node_flags_tab_index_above_28_bits_truncates_without_corrupting_other_flags() {
366
        // AUDIT: `set_tab_index` masks the value with TAB_VALUE_MASK ((1 << 28) - 1),
367
        // so any OverrideInParent >= 2^28 is SILENTLY TRUNCATED rather than rejected
368
        // or saturated. That is lossy, but the safety-critical property is that the
369
        // overflowing bits must not bleed into the anonymous / contenteditable /
370
        // tab-variant bits. Pin both facts.
371
        const OVERFLOW: u32 = 1 << 28;
372
        let mut f = NodeFlags::new();
373
        f.set_tab_index(Some(TabIndex::OverrideInParent(OVERFLOW)));
374
        assert_eq!(
375
            f.get_tab_index(),
376
            Some(TabIndex::OverrideInParent(0)),
377
            "2^28 truncates to 0 (documented lossiness)"
378
        );
379
        assert!(!f.is_anonymous(), "overflow bit must not set ANONYMOUS");
380
        assert!(!f.is_contenteditable());
381

            
382
        let mut f = NodeFlags::new();
383
        f.set_tab_index(Some(TabIndex::OverrideInParent(u32::MAX)));
384
        assert_eq!(
385
            f.get_tab_index(),
386
            Some(TabIndex::OverrideInParent((1 << 28) - 1)),
387
            "u32::MAX truncates to the 28-bit mask"
388
        );
389
        assert!(!f.is_anonymous(), "u32::MAX must not set ANONYMOUS");
390
        assert!(
391
            !f.is_contenteditable(),
392
            "u32::MAX must not set CONTENTEDITABLE"
393
        );
394
    }
395

            
396
    #[test]
397
    fn node_flags_set_tab_index_preserves_contenteditable_and_anonymous() {
398
        let mut f = NodeFlags::new();
399
        f.set_contenteditable_mut(true);
400
        f.set_anonymous(true);
401

            
402
        for ti in [
403
            None,
404
            Some(TabIndex::Auto),
405
            Some(TabIndex::NoKeyboardFocus),
406
            // NodeFlags packs the override into a documented 28-bit field
407
            // (TAB_VALUE_MASK), so u32::MAX would truncate to (1<<28)-1 and not
408
            // round-trip. (1<<28)-1 IS the largest encodable value -- still the
409
            // boundary case, but one this API can actually represent.
410
            Some(TabIndex::OverrideInParent((1 << 28) - 1)),
411
            Some(TabIndex::OverrideInParent(7)),
412
        ] {
413
            f.set_tab_index(ti);
414
            assert!(f.is_contenteditable(), "contenteditable lost for {ti:?}");
415
            assert!(f.is_anonymous(), "anonymous lost for {ti:?}");
416
            assert_eq!(f.get_tab_index(), ti);
417
        }
418
    }
419

            
420
    #[test]
421
    fn node_flags_set_contenteditable_preserves_tab_index_and_anonymous() {
422
        let mut f = NodeFlags::new();
423
        f.set_anonymous(true);
424
        f.set_tab_index(Some(TabIndex::OverrideInParent(12_345)));
425

            
426
        f.set_contenteditable_mut(true);
427
        assert!(f.is_contenteditable());
428
        assert!(f.is_anonymous());
429
        assert_eq!(f.get_tab_index(), Some(TabIndex::OverrideInParent(12_345)));
430

            
431
        f.set_contenteditable_mut(false);
432
        assert!(!f.is_contenteditable());
433
        assert!(f.is_anonymous());
434
        assert_eq!(f.get_tab_index(), Some(TabIndex::OverrideInParent(12_345)));
435
    }
436

            
437
    #[test]
438
    fn node_flags_set_anonymous_preserves_tab_index_and_contenteditable() {
439
        let mut f = NodeFlags::new();
440
        f.set_contenteditable_mut(true);
441
        f.set_tab_index(Some(TabIndex::NoKeyboardFocus));
442

            
443
        f.set_anonymous(true);
444
        assert!(f.is_anonymous());
445
        assert!(f.is_contenteditable());
446
        assert_eq!(f.get_tab_index(), Some(TabIndex::NoKeyboardFocus));
447

            
448
        f.set_anonymous(false);
449
        assert!(!f.is_anonymous());
450
        assert!(f.is_contenteditable());
451
        assert_eq!(f.get_tab_index(), Some(TabIndex::NoKeyboardFocus));
452
    }
453

            
454
    #[test]
455
    fn node_flags_consecutive_set_contenteditable_is_idempotent() {
456
        let mut f = NodeFlags::new();
457
        f.set_contenteditable_mut(true);
458
        let once = f;
459
        f.set_contenteditable_mut(true);
460
        assert_eq!(f, once, "setting twice must not toggle");
461
    }
462

            
463
    #[test]
464
    fn node_flags_builder_and_mut_setter_agree() {
465
        for v in [true, false] {
466
            let builder = NodeFlags::new().set_contenteditable(v);
467
            let mut mutated = NodeFlags::new();
468
            mutated.set_contenteditable_mut(v);
469
            assert_eq!(builder, mutated, "builder/mut disagree for {v}");
470
        }
471
    }
472

            
473
    #[test]
474
    fn node_flags_all_bits_set_decodes_without_panicking() {
475
        // Adversarial: a NodeFlags whose `inner` was never produced by the setters
476
        // (e.g. deserialized from a hostile FFI caller). Every getter must still
477
        // return a deterministic value instead of panicking.
478
        let f = NodeFlags { inner: u32::MAX };
479
        assert!(f.is_contenteditable());
480
        assert!(f.is_anonymous());
481
        // bits [30:29] == 0b11 == TAB_NO_KEYBOARD
482
        assert_eq!(f.get_tab_index(), Some(TabIndex::NoKeyboardFocus));
483
    }
484

            
485
    #[test]
486
    fn node_flags_get_tab_index_is_total_over_the_tag_bits() {
487
        // The `_ => None` arm of get_tab_index is unreachable (2 bits => 4 patterns,
488
        // all matched). Prove every tag pattern decodes to Some/None deterministically.
489
        for tag in 0u32..4 {
490
            for extra in [0u32, u32::MAX] {
491
                let inner = (tag << 29) | (extra & !(0b11 << 29));
492
                let f = NodeFlags { inner };
493
                let decoded = f.get_tab_index();
494
                match tag {
495
                    0 => assert_eq!(decoded, None),
496
                    1 => assert_eq!(decoded, Some(TabIndex::Auto)),
497
                    2 => assert!(matches!(decoded, Some(TabIndex::OverrideInParent(_)))),
498
                    _ => assert_eq!(decoded, Some(TabIndex::NoKeyboardFocus)),
499
                }
500
            }
501
        }
502
    }
503

            
504
    // =====================================================================
505
    // TabIndex — numeric limits
506
    // =====================================================================
507

            
508
    #[test]
509
    fn tab_index_default_is_auto_with_index_zero() {
510
        assert_eq!(TabIndex::default(), TabIndex::Auto);
511
        assert_eq!(TabIndex::default().get_index(), 0);
512
    }
513

            
514
    #[test]
515
    fn tab_index_get_index_at_numeric_limits() {
516
        assert_eq!(TabIndex::Auto.get_index(), 0);
517
        assert_eq!(TabIndex::NoKeyboardFocus.get_index(), -1);
518
        assert_eq!(TabIndex::OverrideInParent(0).get_index(), 0);
519
        // u32 -> isize must widen, never wrap negative (isize is >= 32 bits on all
520
        // supported targets, so u32::MAX stays positive).
521
        let max = TabIndex::OverrideInParent(u32::MAX).get_index();
522
        assert_eq!(max, u32::MAX as isize);
523
        assert!(max > 0, "u32::MAX must not wrap to a negative isize");
524
    }
525

            
526
    #[test]
527
    fn get_effective_tabindex_saturates_into_i32() {
528
        // Reached through NodeFlags, OverrideInParent is capped at 2^28 - 1, which
529
        // always fits i32 — so the i32::MAX saturation arm is not reachable via a
530
        // NodeData. Pin what IS reachable.
531
        let nd = NodeData::create_div().with_tab_index(TabIndex::OverrideInParent(u32::MAX));
532
        assert_eq!(nd.get_effective_tabindex(), Some((1 << 28) - 1));
533

            
534
        assert_eq!(
535
            NodeData::create_div()
536
                .with_tab_index(TabIndex::Auto)
537
                .get_effective_tabindex(),
538
            Some(0)
539
        );
540
        assert_eq!(
541
            NodeData::create_div()
542
                .with_tab_index(TabIndex::NoKeyboardFocus)
543
                .get_effective_tabindex(),
544
            Some(-1)
545
        );
546
        assert_eq!(NodeData::create_div().get_effective_tabindex(), None);
547
    }
548

            
549
    #[test]
550
    fn get_effective_tabindex_falls_back_to_zero_for_focus_callbacks() {
551
        let nd = NodeData::create_div().with_callback(
552
            EventFilter::Focus(FocusEventFilter::MouseDown),
553
            RefAny::new(0u32),
554
            0usize,
555
        );
556
        assert_eq!(nd.get_effective_tabindex(), Some(0));
557
    }
558

            
559
    // =====================================================================
560
    // TagId / ScrollTagId
561
    // =====================================================================
562

            
563
    #[test]
564
    fn tag_id_unique_never_returns_zero_and_never_repeats() {
565
        // 0 is reserved for "no tag". Other tests in this binary also allocate tags,
566
        // so assert distinctness rather than a specific starting value.
567
        let ids: Vec<TagId> = (0..512).map(|_| TagId::unique()).collect();
568
        for id in &ids {
569
            assert_ne!(id.inner, 0, "TagId 0 is reserved for 'no tag'");
570
        }
571
        let mut sorted: Vec<u64> = ids.iter().map(|t| t.inner).collect();
572
        sorted.sort_unstable();
573
        sorted.dedup();
574
        assert_eq!(sorted.len(), 512, "TagId::unique() handed out a duplicate");
575
    }
576

            
577
    #[test]
578
    fn tag_id_crate_internal_conversions_are_identity_at_limits() {
579
        for inner in [0u64, 1, u64::MAX, u64::MAX - 1] {
580
            let t = TagId { inner };
581
            assert_eq!(t.into_crate_internal(), t);
582
            assert_eq!(TagId::from_crate_internal(t), t);
583
            // Round-trip through both directions.
584
            assert_eq!(
585
                TagId::from_crate_internal(t.into_crate_internal()).inner,
586
                inner
587
            );
588
        }
589
    }
590

            
591
    #[test]
592
    fn tag_id_display_is_non_empty_at_numeric_limits() {
593
        for inner in [0u64, 1, u64::MAX] {
594
            let s = format!("{}", TagId { inner });
595
            assert!(!s.is_empty());
596
            assert!(s.contains(&inner.to_string()), "{s} should contain {inner}");
597
        }
598
    }
599

            
600
    #[test]
601
    fn scroll_tag_id_unique_is_distinct_and_debug_matches_display() {
602
        let a = ScrollTagId::unique();
603
        let b = ScrollTagId::unique();
604
        assert_ne!(a, b);
605
        assert_ne!(a.inner.inner, 0);
606

            
607
        let s = ScrollTagId {
608
            inner: TagId { inner: u64::MAX },
609
        };
610
        assert_eq!(format!("{s:?}"), format!("{s}"));
611
        assert!(!format!("{s}").is_empty());
612
    }
613

            
614
    // =====================================================================
615
    // AttributeType — getters / predicates / serializer invariants
616
    // =====================================================================
617

            
618
    #[test]
619
    fn attribute_boolean_attrs_always_have_an_empty_value() {
620
        // Invariant: is_boolean() means "present == true", so there is nothing to
621
        // serialize on the right-hand side.
622
        for attr in all_attribute_variants() {
623
            if attr.is_boolean() {
624
                assert_eq!(
625
                    attr.value().as_str(),
626
                    "",
627
                    "boolean attr {} must have an empty value",
628
                    attr.name()
629
                );
630
            }
631
        }
632
    }
633

            
634
    #[test]
635
    fn attribute_name_and_value_never_panic_for_any_variant() {
636
        for attr in all_attribute_variants() {
637
            let name = attr.name();
638
            let value = attr.value();
639
            // Every built-in variant has a non-empty name; only a Custom/Data
640
            // attribute can carry a caller-supplied empty name (see next test).
641
            assert!(!name.is_empty(), "empty name for {attr:?}");
642
            let _ = value.as_str();
643
        }
644
    }
645

            
646
    #[test]
647
    fn attribute_custom_with_empty_name_returns_empty_name_without_panicking() {
648
        let attr = AttributeType::Custom(AttributeNameValue {
649
            attr_name: "".into(),
650
            value: "".into(),
651
        });
652
        assert_eq!(attr.name(), "");
653
        assert_eq!(attr.value().as_str(), "");
654
        assert!(!attr.is_boolean());
655
    }
656

            
657
    #[test]
658
    fn attribute_as_id_and_as_class_are_mutually_exclusive() {
659
        for attr in all_attribute_variants() {
660
            match &attr {
661
                AttributeType::Id(s) => {
662
                    assert_eq!(attr.as_id(), Some(s.as_str()));
663
                    assert_eq!(attr.as_class(), None);
664
                }
665
                AttributeType::Class(s) => {
666
                    assert_eq!(attr.as_class(), Some(s.as_str()));
667
                    assert_eq!(attr.as_id(), None);
668
                }
669
                _ => {
670
                    assert_eq!(attr.as_id(), None, "as_id must be None for {attr:?}");
671
                    assert_eq!(attr.as_class(), None, "as_class must be None for {attr:?}");
672
                }
673
            }
674
        }
675
    }
676

            
677
    #[test]
678
    fn attribute_numeric_values_serialize_at_i32_limits() {
679
        assert_eq!(
680
            AttributeType::MinLength(i32::MIN).value().as_str(),
681
            "-2147483648"
682
        );
683
        assert_eq!(
684
            AttributeType::MaxLength(i32::MAX).value().as_str(),
685
            "2147483647"
686
        );
687
        assert_eq!(AttributeType::ColSpan(0).value().as_str(), "0");
688
        assert_eq!(AttributeType::RowSpan(-1).value().as_str(), "-1");
689
        assert_eq!(
690
            AttributeType::TabIndex(i32::MIN).value().as_str(),
691
            "-2147483648"
692
        );
693
    }
694

            
695
    #[test]
696
    fn attribute_focusable_is_tabindex_zero_and_not_boolean() {
697
        // Boundary: `Focusable` shares the "tabindex" name with TabIndex(i32) but,
698
        // unlike the boolean attrs, serializes a value ("0").
699
        let f = AttributeType::Focusable;
700
        assert_eq!(f.name(), "tabindex");
701
        assert_eq!(f.value().as_str(), "0");
702
        assert!(!f.is_boolean());
703
        assert_eq!(AttributeType::TabIndex(0).name(), "tabindex");
704
    }
705

            
706
    #[test]
707
    fn attribute_checked_true_and_false_are_both_boolean_and_share_a_name() {
708
        // AUDIT: CheckedFalse is_boolean() == true and value() == "", so a serializer
709
        // that emits boolean attrs as bare names would render `checked` for the
710
        // *unchecked* state. Pinning current behaviour — see report.
711
        assert!(AttributeType::CheckedTrue.is_boolean());
712
        assert!(AttributeType::CheckedFalse.is_boolean());
713
        assert_eq!(AttributeType::CheckedTrue.name(), "checked");
714
        assert_eq!(AttributeType::CheckedFalse.name(), "checked");
715
        assert_eq!(AttributeType::CheckedFalse.value().as_str(), "");
716
        // The two are still distinguishable as values.
717
        assert_ne!(AttributeType::CheckedTrue, AttributeType::CheckedFalse);
718
    }
719

            
720
    #[test]
721
    fn attribute_content_editable_and_draggable_stringify_bools() {
722
        assert_eq!(
723
            AttributeType::ContentEditable(true).value().as_str(),
724
            "true"
725
        );
726
        assert_eq!(
727
            AttributeType::ContentEditable(false).value().as_str(),
728
            "false"
729
        );
730
        assert_eq!(AttributeType::Draggable(true).value().as_str(), "true");
731
        assert_eq!(AttributeType::Draggable(false).value().as_str(), "false");
732
        assert!(!AttributeType::ContentEditable(false).is_boolean());
733
    }
734

            
735
    #[test]
736
    fn attribute_round_trips_huge_unicode_values() {
737
        let big = huge_unicode_string();
738
        let attr = AttributeType::Value(big.clone().into());
739
        assert_eq!(attr.value().as_str(), big.as_str());
740
        assert_eq!(attr.name(), "value");
741

            
742
        let id = AttributeType::Id(big.clone().into());
743
        assert_eq!(id.as_id(), Some(big.as_str()));
744
    }
745

            
746
    #[test]
747
    fn id_or_class_accessors_are_mutually_exclusive() {
748
        let id = IdOrClass::Id("my-id".into());
749
        let class = IdOrClass::Class("my-class".into());
750
        assert_eq!(id.as_id(), Some("my-id"));
751
        assert_eq!(id.as_class(), None);
752
        assert_eq!(class.as_class(), Some("my-class"));
753
        assert_eq!(class.as_id(), None);
754

            
755
        // Empty strings are legal and round-trip as Some("").
756
        assert_eq!(IdOrClass::Id("".into()).as_id(), Some(""));
757
        assert_eq!(IdOrClass::Class("".into()).as_class(), Some(""));
758
    }
759

            
760
    // =====================================================================
761
    // InputType
762
    // =====================================================================
763

            
764
    #[test]
765
    fn input_type_as_str_is_non_empty_and_unique_per_variant() {
766
        let all = [
767
            InputType::Text,
768
            InputType::Button,
769
            InputType::Checkbox,
770
            InputType::Color,
771
            InputType::Date,
772
            InputType::Datetime,
773
            InputType::DatetimeLocal,
774
            InputType::Email,
775
            InputType::File,
776
            InputType::Hidden,
777
            InputType::Image,
778
            InputType::Month,
779
            InputType::Number,
780
            InputType::Password,
781
            InputType::Radio,
782
            InputType::Range,
783
            InputType::Reset,
784
            InputType::Search,
785
            InputType::Submit,
786
            InputType::Tel,
787
            InputType::Time,
788
            InputType::Url,
789
            InputType::Week,
790
        ];
791
        let mut seen: Vec<&str> = all.iter().map(InputType::as_str).collect();
792
        for s in &seen {
793
            assert!(!s.is_empty());
794
            assert!(
795
                !s.contains(char::is_whitespace),
796
                "{s} is not a valid HTML attribute value"
797
            );
798
        }
799
        let len = seen.len();
800
        seen.sort_unstable();
801
        seen.dedup();
802
        assert_eq!(seen.len(), len, "two InputType variants share an as_str()");
803

            
804
        assert_eq!(InputType::DatetimeLocal.as_str(), "datetime-local");
805
        assert_eq!(InputType::Text.as_str(), "text");
806
    }
807

            
808
    // =====================================================================
809
    // NodeType
810
    // =====================================================================
811

            
812
    #[test]
813
    fn node_type_to_library_owned_round_trips_every_variant() {
814
        // encode == decode: the deep-copy must be value-equal to the original,
815
        // including the payload-carrying (boxed) variants.
816
        for nt in representative_node_types() {
817
            let owned = nt.to_library_owned_nodetype();
818
            assert_eq!(owned, nt, "to_library_owned_nodetype lost data for {nt:?}");
819
            assert_eq!(owned.get_path(), nt.get_path());
820
        }
821
    }
822

            
823
    #[test]
824
    fn node_type_get_path_and_format_never_panic() {
825
        for nt in representative_node_types() {
826
            let _tag = nt.get_path();
827
            let _fmt = nt.format();
828
            let _semantic = nt.is_semantic_for_accessibility();
829
        }
830
    }
831

            
832
    #[test]
833
    fn node_type_format_returns_content_only_for_content_variants() {
834
        assert_eq!(NodeType::Div.format(), None);
835
        assert_eq!(NodeType::Br.format(), None);
836
        assert_eq!(NodeType::Button.format(), None);
837

            
838
        assert_eq!(
839
            NodeType::Text(BoxOrStatic::heap(AzString::from("hi"))).format(),
840
            Some("hi".to_string())
841
        );
842
        assert_eq!(
843
            NodeType::VirtualView.format(),
844
            Some("virtualized-view".to_string())
845
        );
846
        assert_eq!(
847
            NodeType::Icon(BoxOrStatic::heap(AzString::from("home"))).format(),
848
            Some("icon(home)".to_string())
849
        );
850
    }
851

            
852
    #[test]
853
    fn node_type_format_handles_empty_and_unicode_text() {
854
        assert_eq!(
855
            NodeType::Text(BoxOrStatic::heap(AzString::from(""))).format(),
856
            Some(String::new())
857
        );
858
        let unicode = "日本語 🎉 ünïcødé";
859
        assert_eq!(
860
            NodeType::Text(BoxOrStatic::heap(AzString::from(unicode))).format(),
861
            Some(unicode.to_string())
862
        );
863
    }
864

            
865
    #[test]
866
    fn node_type_format_of_geolocation_probe_survives_nan_and_infinity() {
867
        // Adversarial floats: the probe config is formatted with `{}`, which must
868
        // print NaN/inf rather than panicking.
869
        for max_accuracy_m in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.0, f32::MAX] {
870
            let cfg = crate::geolocation::GeolocationProbeConfig {
871
                high_accuracy: true,
872
                background: true,
873
                max_accuracy_m,
874
                min_interval_ms: u32::MAX,
875
            };
876
            let out = NodeType::GeolocationProbe(cfg)
877
                .format()
878
                .expect("GeolocationProbe always formats");
879
            assert!(out.starts_with("geolocation-probe("));
880
            assert!(
881
                out.contains("4294967295"),
882
                "min_interval_ms must be printed"
883
            );
884
        }
885
    }
886

            
887
    #[test]
888
    fn geolocation_probe_nan_is_self_equal_and_hash_consistent() {
889
        // GeolocationProbeConfig gives f32 a total order via to_bits, so (unlike raw
890
        // f32) NaN == NaN. Eq and Hash must agree, or NodeType breaks as a HashMap key.
891
        let cfg = crate::geolocation::GeolocationProbeConfig {
892
            max_accuracy_m: f32::NAN,
893
            ..Default::default()
894
        };
895
        let a = NodeType::GeolocationProbe(cfg);
896
        let b = NodeType::GeolocationProbe(cfg);
897
        assert_eq!(a, b, "bitwise-NaN configs must compare equal");
898
        assert_eq!(
899
            hash_of(&a),
900
            hash_of(&b),
901
            "Eq == true but hashes differ: violates the Hash/Eq contract"
902
        );
903
        assert_eq!(a.cmp(&b), core::cmp::Ordering::Equal);
904
    }
905

            
906
    #[test]
907
    fn node_type_is_semantic_for_accessibility_known_true_and_false() {
908
        for nt in [
909
            NodeType::Button,
910
            NodeType::Input,
911
            NodeType::TextArea,
912
            NodeType::Select,
913
            NodeType::A,
914
            NodeType::H1,
915
            NodeType::H6,
916
            NodeType::Article,
917
            NodeType::Nav,
918
            NodeType::Main,
919
        ] {
920
            assert!(
921
                nt.is_semantic_for_accessibility(),
922
                "{nt:?} should be semantic"
923
            );
924
        }
925
        for nt in [
926
            NodeType::Div,
927
            NodeType::Span,
928
            NodeType::Br,
929
            NodeType::VirtualView,
930
            NodeType::Text(BoxOrStatic::heap(AzString::from("x"))),
931
        ] {
932
            assert!(
933
                !nt.is_semantic_for_accessibility(),
934
                "{nt:?} should not be semantic"
935
            );
936
        }
937
    }
938

            
939
    #[test]
940
    fn node_type_text_variants_are_content_sensitive() {
941
        let a = NodeType::Text(BoxOrStatic::heap(AzString::from("a")));
942
        let b = NodeType::Text(BoxOrStatic::heap(AzString::from("b")));
943
        assert_ne!(a, b);
944
        assert_eq!(a.get_path(), b.get_path(), "same tag, different content");
945
    }
946

            
947
    // =====================================================================
948
    // NodeData — attributes, ids, classes
949
    // =====================================================================
950

            
951
    #[test]
952
    fn node_data_default_has_no_attributes_and_no_extra_state() {
953
        let nd = NodeData::default();
954
        assert!(nd.is_node_type(NodeType::Div));
955
        assert!(nd.attributes().as_ref().is_empty());
956
        assert!(nd.get_ids_and_classes().as_ref().is_empty());
957
        assert!(nd.get_dataset().is_none());
958
        assert!(nd.get_key().is_none());
959
        assert!(nd.get_menu_bar().is_none());
960
        assert!(nd.get_context_menu().is_none());
961
        assert!(nd.get_svg_data().is_none());
962
        assert!(nd.get_image_clip_mask().is_none());
963
        assert!(nd.get_accessibility_info().is_none());
964
        assert!(nd.get_merge_callback().is_none());
965
        assert!(nd.get_component_origin().is_none());
966
        assert!(!nd.has_context_menu());
967
        assert!(!nd.is_contenteditable());
968
        assert!(!nd.is_anonymous());
969
        assert_eq!(nd.get_tab_index(), None);
970
    }
971

            
972
    #[test]
973
    fn attributes_mut_lazily_allocates_but_stays_empty() {
974
        let mut nd = NodeData::create_div();
975
        assert!(nd.attributes().as_ref().is_empty());
976
        let _ = nd.attributes_mut(); // allocates NodeDataExt
977
        assert!(
978
            nd.attributes().as_ref().is_empty(),
979
            "lazy alloc must not invent attributes"
980
        );
981
        nd.add_id("x".into());
982
        assert_eq!(nd.attributes().as_ref().len(), 1);
983
    }
984

            
985
    #[test]
986
    fn has_id_and_has_class_match_exactly_not_by_prefix() {
987
        let mut nd = NodeData::create_div();
988
        nd.add_id("header".into());
989
        nd.add_class("btn".into());
990

            
991
        assert!(nd.has_id("header"));
992
        assert!(nd.has_class("btn"));
993
        // No prefix/substring matching.
994
        assert!(!nd.has_id("head"));
995
        assert!(!nd.has_id("header2"));
996
        assert!(!nd.has_class("bt"));
997
        assert!(!nd.has_class(""));
998
        // Ids and classes must not cross over.
999
        assert!(!nd.has_class("header"));
        assert!(!nd.has_id("btn"));
    }
    #[test]
    fn has_id_matches_the_empty_string_id() {
        let mut nd = NodeData::create_div();
        assert!(!nd.has_id(""), "no ids at all => empty id must not match");
        nd.add_id("".into());
        assert!(nd.has_id(""), "an explicitly-added empty id must match");
        assert!(!nd.has_id("x"));
    }
    #[test]
    fn has_id_and_has_class_handle_unicode_and_huge_strings() {
        let unicode = "日本語-🎉-ünïcødé";
        let big = huge_unicode_string();
        let mut nd = NodeData::create_div();
        nd.add_id(unicode.into());
        nd.add_class(big.clone().into());
        assert!(nd.has_id(unicode));
        assert!(nd.has_class(big.as_str()));
        // A truncated-at-a-codepoint-boundary prefix must not match.
        assert!(!nd.has_id("日本語"));
    }
    #[test]
    fn duplicate_ids_are_kept_and_still_match() {
        let mut nd = NodeData::create_div();
        nd.add_id("dup".into());
        nd.add_id("dup".into());
        assert!(nd.has_id("dup"));
        assert_eq!(
            nd.get_ids_and_classes().as_ref().len(),
            2,
            "add_id does not deduplicate"
        );
    }
    #[test]
    fn get_ids_and_classes_preserves_insertion_order_and_kind() {
        let mut nd = NodeData::create_div();
        nd.add_id("i1".into());
        nd.add_class("c1".into());
        nd.add_id("i2".into());
        let v = nd.get_ids_and_classes();
        let v = v.as_ref();
        assert_eq!(v.len(), 3);
        assert_eq!(v[0], IdOrClass::Id("i1".into()));
        assert_eq!(v[1], IdOrClass::Class("c1".into()));
        assert_eq!(v[2], IdOrClass::Id("i2".into()));
    }
    #[test]
    fn get_ids_and_classes_ignores_non_id_class_attributes() {
        let mut nd = NodeData::create_div();
        nd.set_attributes(
            vec![
                AttributeType::Href("/x".into()),
                AttributeType::Id("i".into()),
                AttributeType::Disabled,
                AttributeType::Class("c".into()),
            ]
            .into(),
        );
        let v = nd.get_ids_and_classes();
        assert_eq!(v.as_ref().len(), 2);
    }
    #[test]
    fn set_ids_and_classes_replaces_ids_but_preserves_other_attributes() {
        // The dangerous part of set_ids_and_classes: it rebuilds the attribute vec.
        // Non-Id/Class attributes must survive.
        let mut nd = NodeData::create_div();
        nd.set_attributes(
            vec![
                AttributeType::Href("/old".into()),
                AttributeType::Id("old-id".into()),
                AttributeType::Class("old-class".into()),
                AttributeType::Disabled,
            ]
            .into(),
        );
        nd.set_ids_and_classes(vec![IdOrClass::Class("new-class".into())].into());
        assert!(!nd.has_id("old-id"), "old id must be dropped");
        assert!(!nd.has_class("old-class"), "old class must be dropped");
        assert!(nd.has_class("new-class"));
        // Href / Disabled must NOT have been collateral damage.
        let attrs = nd.attributes().as_ref();
        assert!(attrs.contains(&AttributeType::Href("/old".into())));
        assert!(attrs.contains(&AttributeType::Disabled));
        assert_eq!(attrs.len(), 3);
    }
    #[test]
    fn set_ids_and_classes_with_an_empty_vec_clears_all_ids_and_classes() {
        let mut nd = NodeData::create_div();
        nd.add_id("i".into());
        nd.add_class("c".into());
        nd.set_ids_and_classes(Vec::new().into());
        assert!(nd.get_ids_and_classes().as_ref().is_empty());
        assert!(!nd.has_id("i"));
        assert!(!nd.has_class("c"));
    }
    #[test]
    fn set_ids_and_classes_is_idempotent_when_reapplied() {
        let mut nd = NodeData::create_div();
        let ids: IdOrClassVec =
            vec![IdOrClass::Id("i".into()), IdOrClass::Class("c".into())].into();
        nd.set_ids_and_classes(ids.clone());
        let after_first = nd.attributes().clone();
        nd.set_ids_and_classes(ids);
        assert_eq!(
            nd.attributes().as_ref(),
            after_first.as_ref(),
            "re-applying the same ids/classes must not duplicate them"
        );
    }
    #[test]
    fn with_attribute_appends_without_dropping_existing_attributes() {
        // `with_attribute` is private, so this can only be exercised from an inline
        // test module.
        let nd = NodeData::create_div()
            .with_attribute(AttributeType::Href("/a".into()))
            .with_attribute(AttributeType::Alt("alt".into()));
        let attrs = nd.attributes().as_ref();
        assert_eq!(attrs.len(), 2);
        assert_eq!(attrs[0], AttributeType::Href("/a".into()));
        assert_eq!(attrs[1], AttributeType::Alt("alt".into()));
    }
    // =====================================================================
    // NodeData — constructors
    // =====================================================================
    #[test]
    fn create_node_shorthands_produce_the_right_node_type() {
        assert!(NodeData::create_body().is_node_type(NodeType::Body));
        assert!(NodeData::create_div().is_node_type(NodeType::Div));
        assert!(NodeData::create_br().is_node_type(NodeType::Br));
        assert!(NodeData::create_button_no_a11y().is_node_type(NodeType::Button));
        assert!(NodeData::create_table_no_a11y().is_node_type(NodeType::Table));
    }
    #[test]
    fn create_text_accepts_empty_unicode_and_huge_input() {
        for s in ["", "x", "日本語 🎉"] {
            let nd = NodeData::create_text_do_not_use_without_block_level_wrapper(s);
            assert!(nd.is_text_node());
            assert_eq!(nd.get_node_type().format(), Some(s.to_string()));
        }
        let big = huge_unicode_string();
        let nd = NodeData::create_text_do_not_use_without_block_level_wrapper(big.clone());
        assert!(nd.is_text_node());
        assert_eq!(nd.get_node_type().format(), Some(big));
    }
    #[test]
    fn create_a_stores_href_and_accessibility_name() {
        let nd = NodeData::create_a("/home".into(), SmallAriaInfo::label("Home"));
        assert!(nd.is_node_type(NodeType::A));
        assert!(nd
            .attributes()
            .as_ref()
            .contains(&AttributeType::Href("/home".into())));
        let info = nd
            .get_accessibility_info()
            .expect("create_a must set accessibility info");
        assert_eq!(info.accessibility_name, OptionString::Some("Home".into()));
    }
    #[test]
    fn create_a_no_a11y_has_href_but_no_accessibility_info() {
        let nd = NodeData::create_a_no_a11y("/x".into());
        assert!(nd
            .attributes()
            .as_ref()
            .contains(&AttributeType::Href("/x".into())));
        assert!(nd.get_accessibility_info().is_none());
    }
    #[test]
    fn create_a_accepts_an_empty_href() {
        let nd = NodeData::create_a_no_a11y("".into());
        assert_eq!(
            nd.attributes().as_ref()[0],
            AttributeType::Href("".into()),
            "empty href is stored verbatim, not dropped"
        );
    }
    #[test]
    fn create_input_stores_all_three_attributes_in_order() {
        let nd = NodeData::create_input_no_a11y("text".into(), "user".into(), "Username".into());
        assert!(nd.is_node_type(NodeType::Input));
        let attrs = nd.attributes().as_ref();
        assert_eq!(attrs.len(), 3);
        assert_eq!(attrs[0], AttributeType::InputType("text".into()));
        assert_eq!(attrs[1], AttributeType::Name("user".into()));
        assert_eq!(attrs[2], AttributeType::AriaLabel("Username".into()));
    }
    #[test]
    fn create_input_with_a11y_sets_both_attributes_and_accessibility_info() {
        let nd = NodeData::create_input(
            "password".into(),
            "pw".into(),
            "Password".into(),
            SmallAriaInfo::label("Password").with_role(AccessibilityRole::Text),
        );
        assert_eq!(nd.attributes().as_ref().len(), 3);
        let info = nd.get_accessibility_info().expect("a11y info");
        assert_eq!(info.role, AccessibilityRole::Text);
    }
    #[test]
    fn create_textarea_and_select_store_name_and_label() {
        let ta = NodeData::create_textarea_no_a11y("body".into(), "Body".into());
        assert!(ta.is_node_type(NodeType::TextArea));
        assert_eq!(ta.attributes().as_ref().len(), 2);
        let sel = NodeData::create_select_no_a11y("country".into(), "Country".into());
        assert!(sel.is_node_type(NodeType::Select));
        assert_eq!(
            sel.attributes().as_ref()[0],
            AttributeType::Name("country".into())
        );
    }
    #[test]
    fn create_label_uses_a_custom_for_attribute() {
        let nd = NodeData::create_label_no_a11y("email-input".into());
        assert!(nd.is_node_type(NodeType::Label));
        assert_eq!(
            nd.attributes().as_ref()[0],
            AttributeType::Custom(AttributeNameValue {
                attr_name: "for".into(),
                value: "email-input".into(),
            })
        );
        assert_eq!(nd.attributes().as_ref()[0].name(), "for");
        assert_eq!(nd.attributes().as_ref()[0].value().as_str(), "email-input");
    }
    #[test]
    fn create_button_and_table_with_aria_set_accessibility_info() {
        let btn = NodeData::create_button(
            SmallAriaInfo::label("Save").with_role(AccessibilityRole::PushButton),
        );
        let info = btn.get_accessibility_info().expect("a11y info");
        assert_eq!(info.role, AccessibilityRole::PushButton);
        assert_eq!(info.accessibility_name, OptionString::Some("Save".into()));
        let table = NodeData::create_table(SmallAriaInfo::label("Results"));
        assert!(table.is_node_type(NodeType::Table));
        assert!(table.get_accessibility_info().is_some());
    }
    #[test]
    fn a11y_constructors_accept_empty_aria_labels() {
        let btn = NodeData::create_button(SmallAriaInfo::label(""));
        let info = btn.get_accessibility_info().expect("a11y info");
        assert_eq!(info.accessibility_name, OptionString::Some("".into()));
        // An unset role degrades to Unknown rather than panicking.
        assert_eq!(info.role, AccessibilityRole::Unknown);
    }
    #[test]
    fn create_image_and_is_node_type_round_trip() {
        let img = ImageRef::null_image(4, 4, crate::resources::RawImageFormat::RGBA8, Vec::new());
        let nd = NodeData::create_image(img.clone());
        assert!(!nd.is_text_node());
        assert_eq!(nd.get_node_type().get_path(), NodeTypeTag::Img);
        assert!(nd.is_node_type(NodeType::Image(BoxOrStatic::heap(img))));
    }
    // =====================================================================
    // NodeData — predicates
    // =====================================================================
    #[test]
    fn is_node_type_is_content_sensitive_for_text() {
        let nd = NodeData::create_text_do_not_use_without_block_level_wrapper("a");
        assert!(nd.is_node_type(NodeType::Text(BoxOrStatic::heap(AzString::from("a")))));
        assert!(
            !nd.is_node_type(NodeType::Text(BoxOrStatic::heap(AzString::from("b")))),
            "is_node_type compares payloads, not just the discriminant"
        );
        assert!(!nd.is_node_type(NodeType::Div));
    }
    #[test]
    fn is_text_node_and_is_virtual_view_node() {
        assert!(NodeData::create_text_do_not_use_without_block_level_wrapper("x").is_text_node());
        assert!(!NodeData::create_div().is_text_node());
        let vv = NodeData::create_virtual_view(RefAny::new(1u32), virtual_view_callback());
        assert!(vv.is_virtual_view_node());
        assert!(!vv.is_text_node());
        assert!(vv.get_virtual_view_node_ref().is_some());
        assert!(!NodeData::create_div().is_virtual_view_node());
        assert!(NodeData::create_div().get_virtual_view_node_ref().is_none());
    }
    #[test]
    fn has_context_menu_flips_only_after_set_context_menu() {
        let mut nd = NodeData::create_div();
        assert!(!nd.has_context_menu());
        // A menu bar is a different slot and must not be mistaken for a context menu.
        nd.set_menu_bar(Menu::create(Vec::new().into()));
        assert!(
            !nd.has_context_menu(),
            "menu_bar must not satisfy has_context_menu"
        );
        assert!(nd.get_menu_bar().is_some());
        nd.set_context_menu(Menu::create(Vec::new().into()));
        assert!(nd.has_context_menu());
        assert!(nd.get_context_menu().is_some());
    }
    #[test]
    fn with_menu_bar_and_with_context_menu_are_independent_slots() {
        let nd = NodeData::create_div()
            .with_menu_bar(Menu::create(Vec::new().into()))
            .with_context_menu(Menu::create(Vec::new().into()));
        assert!(nd.get_menu_bar().is_some());
        assert!(nd.get_context_menu().is_some());
        assert!(nd.has_context_menu());
    }
    #[test]
    fn is_focusable_for_naturally_focusable_and_opted_in_nodes() {
        for nt in [
            NodeType::A,
            NodeType::Button,
            NodeType::Input,
            NodeType::Select,
            NodeType::TextArea,
        ] {
            assert!(
                NodeData::create_node(nt.clone()).is_focusable(),
                "{nt:?} is naturally focusable"
            );
        }
        assert!(!NodeData::create_div().is_focusable());
        assert!(NodeData::create_div()
            .with_contenteditable(true)
            .is_focusable());
        assert!(NodeData::create_div()
            .with_tab_index(TabIndex::NoKeyboardFocus)
            .is_focusable());
        assert!(NodeData::create_div()
            .with_callback(
                EventFilter::Focus(FocusEventFilter::MouseDown),
                RefAny::new(0u32),
                0usize,
            )
            .is_focusable());
        // A non-focus callback must NOT make a plain div focusable.
        assert!(!NodeData::create_div()
            .with_callback(
                EventFilter::Hover(HoverEventFilter::MouseOver),
                RefAny::new(0u32),
                0usize,
            )
            .is_focusable());
    }
    #[test]
    fn has_activation_behavior_for_elements_callbacks_and_roles() {
        assert!(NodeData::create_node(NodeType::A).has_activation_behavior());
        assert!(NodeData::create_button_no_a11y().has_activation_behavior());
        assert!(!NodeData::create_div().has_activation_behavior());
        for f in [HoverEventFilter::MouseUp, HoverEventFilter::LeftMouseUp] {
            assert!(NodeData::create_div()
                .with_callback(EventFilter::Hover(f), RefAny::new(0u32), 0usize)
                .has_activation_behavior());
        }
        // MouseDown is not a click.
        assert!(!NodeData::create_div()
            .with_callback(
                EventFilter::Hover(HoverEventFilter::MouseDown),
                RefAny::new(0u32),
                0usize,
            )
            .has_activation_behavior());
        let mut nd = NodeData::create_div();
        nd.set_accessibility_info(
            SmallAriaInfo::label("x")
                .with_role(AccessibilityRole::PushButton)
                .to_full_info(),
        );
        assert!(nd.has_activation_behavior(), "role=PushButton activates");
    }
    #[test]
    fn is_activatable_is_false_for_unavailable_elements() {
        let mut nd = NodeData::create_button_no_a11y();
        assert!(nd.is_activatable());
        let mut info = SmallAriaInfo::label("Save")
            .with_role(AccessibilityRole::PushButton)
            .to_full_info();
        info.states = vec![AccessibilityState::Unavailable].into();
        nd.set_accessibility_info(info);
        assert!(nd.has_activation_behavior());
        assert!(
            !nd.is_activatable(),
            "an Unavailable (disabled) button must not be activatable"
        );
        // Something with no activation behaviour at all is never activatable.
        assert!(!NodeData::create_div().is_activatable());
    }
    // =====================================================================
    // NodeData — accessible label / value / placeholder
    // =====================================================================
    #[test]
    fn get_accessible_label_prefers_aria_label_over_alt_and_title() {
        let mut nd = NodeData::create_div();
        nd.set_attributes(
            vec![
                AttributeType::Title("title".into()),
                AttributeType::Alt("alt".into()),
                AttributeType::AriaLabel("aria".into()),
            ]
            .into(),
        );
        assert_eq!(
            nd.get_accessible_label(),
            Some("aria"),
            "aria-label wins regardless of attribute order"
        );
    }
    #[test]
    fn get_accessible_label_alt_vs_title_is_order_dependent() {
        // AUDIT: the doc comment promises `aria-label > alt > title`, but the
        // implementation's second pass matches `Alt(s) | Title(s)` in a single arm,
        // so whichever appears FIRST in the attribute vec wins. With [Title, Alt]
        // that yields "title" — contradicting the documented priority. Pinned here
        // so a fix has to update this test deliberately. See report.
        let mut title_first = NodeData::create_div();
        title_first.set_attributes(
            vec![
                AttributeType::Title("title".into()),
                AttributeType::Alt("alt".into()),
            ]
            .into(),
        );
        assert_eq!(title_first.get_accessible_label(), Some("title"));
        let mut alt_first = NodeData::create_div();
        alt_first.set_attributes(
            vec![
                AttributeType::Alt("alt".into()),
                AttributeType::Title("title".into()),
            ]
            .into(),
        );
        assert_eq!(alt_first.get_accessible_label(), Some("alt"));
    }
    #[test]
    fn get_accessible_label_value_and_placeholder_default_to_none() {
        let nd = NodeData::create_div();
        assert_eq!(nd.get_accessible_label(), None);
        assert_eq!(nd.get_accessible_value(), None);
        assert_eq!(nd.get_placeholder(), None);
    }
    #[test]
    fn get_accessible_value_and_placeholder_return_the_first_match() {
        let mut nd = NodeData::create_div();
        nd.set_attributes(
            vec![
                AttributeType::Value("first".into()),
                AttributeType::Value("second".into()),
                AttributeType::Placeholder("ph".into()),
            ]
            .into(),
        );
        assert_eq!(nd.get_accessible_value(), Some("first"));
        assert_eq!(nd.get_placeholder(), Some("ph"));
    }
    #[test]
    fn get_accessible_label_returns_empty_string_not_none_for_empty_aria_label() {
        // Boundary: an empty aria-label is still "present" — Some("") not None.
        let mut nd = NodeData::create_div();
        nd.set_attributes(vec![AttributeType::AriaLabel("".into())].into());
        assert_eq!(nd.get_accessible_label(), Some(""));
    }
    // =====================================================================
    // NodeData — dataset / key / merge callback / component origin
    // =====================================================================
    #[test]
    fn dataset_set_get_take_round_trip() {
        let mut nd = NodeData::create_div();
        assert!(nd.get_dataset().is_none());
        assert!(nd.take_dataset().is_none(), "take on empty must be None");
        nd.set_dataset(OptionRefAny::Some(RefAny::new(42u32)));
        assert!(nd.get_dataset().is_some());
        assert!(nd.get_dataset_mut().is_some());
        let mut taken = nd.take_dataset().expect("dataset was set");
        assert_eq!(taken.downcast_ref::<u32>().map(|r| *r), Some(42));
        assert!(nd.get_dataset().is_none(), "take must clear the slot");
        assert!(nd.take_dataset().is_none(), "double-take must be None");
    }
    #[test]
    fn set_dataset_none_clears_without_allocating_extra() {
        let mut nd = NodeData::create_div();
        // Setting None on a node that never had a dataset must be a no-op, not a panic.
        nd.set_dataset(OptionRefAny::None);
        assert!(nd.get_dataset().is_none());
        nd.set_dataset(OptionRefAny::Some(RefAny::new(1u8)));
        nd.set_dataset(OptionRefAny::None);
        assert!(nd.get_dataset().is_none());
    }
    #[test]
    fn set_key_is_deterministic_and_input_sensitive() {
        let mut a = NodeData::create_div();
        let mut b = NodeData::create_div();
        a.set_key("user-123");
        b.set_key("user-123");
        assert_eq!(a.get_key(), b.get_key(), "same key input => same hash");
        assert!(a.get_key().is_some());
        let mut c = NodeData::create_div();
        c.set_key("user-124");
        assert_ne!(
            a.get_key(),
            c.get_key(),
            "different inputs => different keys"
        );
    }
    #[test]
    fn set_key_hashes_str_and_string_identically() {
        let mut a = NodeData::create_div();
        let mut b = NodeData::create_div();
        a.set_key("x");
        b.set_key(String::from("x"));
        assert_eq!(
            a.get_key(),
            b.get_key(),
            "&str and String must hash the same (Hash for str)"
        );
    }
    #[test]
    fn set_key_accepts_extreme_inputs() {
        for nd in [
            NodeData::create_div().with_key(""),
            NodeData::create_div().with_key(u64::MAX),
            NodeData::create_div().with_key(i64::MIN),
            NodeData::create_div().with_key(huge_unicode_string()),
        ] {
            assert!(nd.get_key().is_some());
        }
    }
    #[test]
    fn set_key_overwrites_rather_than_accumulating() {
        let mut nd = NodeData::create_div();
        nd.set_key("a");
        let first = nd.get_key();
        nd.set_key("b");
        assert_ne!(nd.get_key(), first, "the last set_key wins");
    }
    #[test]
    fn merge_callback_round_trips_the_function_pointer() {
        let mut nd = NodeData::create_div();
        assert!(nd.get_merge_callback().is_none());
        nd.set_merge_callback(merge_cb_a as DatasetMergeCallbackType);
        let cb = nd.get_merge_callback().expect("merge callback was set");
        assert_eq!(cb.cb as usize, merge_cb_a as usize);
        assert_eq!(cb.callable, OptionRefAny::None);
        // Overwriting swaps the pointer.
        nd.set_merge_callback(merge_cb_b as DatasetMergeCallbackType);
        let cb = nd
            .get_merge_callback()
            .expect("merge callback was replaced");
        assert_eq!(cb.cb as usize, merge_cb_b as usize);
    }
    #[test]
    fn dataset_merge_callback_from_ptr_matches_the_from_impl() {
        let via_ptr = DatasetMergeCallback::from_ptr(merge_cb_a);
        let via_from = DatasetMergeCallback::from(merge_cb_a as DatasetMergeCallbackType);
        assert_eq!(via_ptr, via_from);
        assert_eq!(via_ptr.cb as usize, merge_cb_a as usize);
        assert_eq!(via_ptr.callable, OptionRefAny::None);
        // Distinct functions must not compare equal.
        assert_ne!(via_ptr, DatasetMergeCallback::from_ptr(merge_cb_b));
    }
    #[test]
    fn dataset_merge_callback_debug_is_non_empty_and_names_the_type() {
        let cb = DatasetMergeCallback::from_ptr(merge_cb_a);
        let s = format!("{cb:?}");
        assert!(s.contains("DatasetMergeCallback"));
        assert!(s.contains("cb"));
    }
    #[test]
    fn merge_callback_is_actually_callable_through_the_stored_pointer() {
        let cb = DatasetMergeCallback::from_ptr(merge_cb_b);
        let mut out = (cb.cb)(RefAny::new(1u32), RefAny::new(2u32));
        assert_eq!(
            out.downcast_ref::<u32>().map(|r| *r),
            Some(2),
            "merge_cb_b returns the OLD data"
        );
    }
    #[test]
    fn component_origin_round_trips_and_defaults_to_none() {
        let mut nd = NodeData::create_div();
        assert!(nd.get_component_origin().is_none());
        nd.set_component_origin(ComponentOrigin {
            component_id: "shadcn:card".into(),
            data_model_json: crate::json::Json::null(),
        });
        let origin = nd.get_component_origin().expect("origin was set");
        assert_eq!(origin.component_id.as_str(), "shadcn:card");
        // The Default impl is well-formed and hashable.
        let d = ComponentOrigin::default();
        assert_eq!(d.component_id.as_str(), "");
        assert_eq!(hash_of(&d), hash_of(&ComponentOrigin::default()));
    }
    // =====================================================================
    // NodeData — svg data / clip mask
    // =====================================================================
    #[test]
    fn get_image_clip_mask_returns_none_for_non_mask_svg_data() {
        let mut nd = NodeData::create_div();
        assert!(nd.get_image_clip_mask().is_none());
        nd.set_svg_data(SvgNodeData::Circle {
            cx: 1.0,
            cy: 2.0,
            r: 3.0,
        });
        assert!(nd.get_svg_data().is_some());
        assert!(
            nd.get_image_clip_mask().is_none(),
            "a Circle is not an ImageClipMask"
        );
    }
    #[test]
    fn set_clip_mask_is_readable_through_get_image_clip_mask() {
        let mask = ImageMask {
            image: ImageRef::null_image(2, 2, crate::resources::RawImageFormat::R8, Vec::new()),
            rect: crate::geom::LogicalRect::new(
                LogicalPosition { x: 0.0, y: 0.0 },
                crate::geom::LogicalSize {
                    width: 2.0,
                    height: 2.0,
                },
            ),
            repeat: false,
        };
        let mut nd = NodeData::create_div();
        nd.set_clip_mask(mask.clone());
        assert_eq!(nd.get_image_clip_mask(), Some(&mask));
        // set_clip_mask stores through the same slot as set_svg_data.
        assert!(matches!(
            nd.get_svg_data(),
            Some(SvgNodeData::ImageClipMask(_))
        ));
    }
    #[test]
    fn svg_node_data_with_nan_coords_is_self_equal_and_hash_consistent() {
        // SvgNodeData hashes f32 via to_bits and derives Eq, so a NaN-carrying shape
        // must be equal to (and hash like) itself, or NodeData's Hash/Eq contract
        // breaks for SVG nodes.
        let a = SvgNodeData::Rect {
            x: f32::NAN,
            y: f32::INFINITY,
            width: f32::NEG_INFINITY,
            height: -0.0,
            rx: 0.0,
            ry: f32::MAX,
        };
        let b = a.clone();
        assert_eq!(a, b);
        assert_eq!(hash_of(&a), hash_of(&b));
        assert_eq!(a.cmp(&b), core::cmp::Ordering::Equal);
    }
    #[test]
    fn svg_node_data_line_and_linear_gradient_are_distinct_despite_a_shared_hash_body() {
        // The Hash impl deliberately folds Line and LinearGradient into one arm, so
        // they can hash alike — but Eq must still tell them apart.
        let line = SvgNodeData::Line {
            x1: 1.0,
            y1: 2.0,
            x2: 3.0,
            y2: 4.0,
        };
        let grad = SvgNodeData::LinearGradient {
            x1: 1.0,
            y1: 2.0,
            x2: 3.0,
            y2: 4.0,
        };
        assert_ne!(line, grad, "same field values, different variants");
    }
    // =====================================================================
    // NodeData — hashing
    // =====================================================================
    #[test]
    fn calculate_node_data_hash_is_deterministic_and_equal_for_equal_nodes() {
        let a = NodeData::create_div()
            .with_key("k")
            .with_contenteditable(true);
        let b = a.clone();
        assert_eq!(a, b);
        assert_eq!(a.calculate_node_data_hash(), b.calculate_node_data_hash());
        assert_eq!(
            a.calculate_node_data_hash(),
            a.calculate_node_data_hash(),
            "hashing must not depend on call count"
        );
    }
    #[test]
    fn structural_hash_ignores_text_content_but_data_hash_does_not() {
        // Documented behaviour: Text("Hello") must match Text("Hello World") during
        // reconciliation so the cursor survives an edit.
        let a = NodeData::create_text_do_not_use_without_block_level_wrapper("Hello");
        let b = NodeData::create_text_do_not_use_without_block_level_wrapper("Hello World");
        assert_eq!(
            a.calculate_structural_hash(),
            b.calculate_structural_hash(),
            "structural hash must ignore text content"
        );
        assert_ne!(
            a.calculate_node_data_hash(),
            b.calculate_node_data_hash(),
            "the full data hash must NOT ignore text content"
        );
    }
    #[test]
    fn structural_hash_ignores_contenteditable_but_data_hash_does_not() {
        let plain = NodeData::create_div();
        let editable = NodeData::create_div().with_contenteditable(true);
        assert_eq!(
            plain.calculate_structural_hash(),
            editable.calculate_structural_hash(),
            "contenteditable flips with focus; it must not move the structural hash"
        );
        assert_ne!(
            plain.calculate_node_data_hash(),
            editable.calculate_node_data_hash(),
            "flags ARE part of the full data hash"
        );
    }
    #[test]
    fn structural_hash_is_sensitive_to_ids_classes_and_node_type() {
        let mut a = NodeData::create_div();
        a.add_id("a".into());
        let mut b = NodeData::create_div();
        b.add_id("b".into());
        assert_ne!(a.calculate_structural_hash(), b.calculate_structural_hash());
        let mut c = NodeData::create_div();
        c.add_class("a".into());
        assert_ne!(
            a.calculate_structural_hash(),
            c.calculate_structural_hash(),
            "id=\"a\" and class=\"a\" must not collide"
        );
        assert_ne!(
            NodeData::create_div().calculate_structural_hash(),
            NodeData::create_br().calculate_structural_hash()
        );
    }
    #[test]
    fn node_data_eq_implies_equal_hash_for_a_richly_populated_node() {
        let mut a = NodeData::create_div();
        a.add_id("id".into());
        a.add_class("cls".into());
        a.set_tab_index(TabIndex::OverrideInParent(9));
        a.set_contenteditable(true);
        a.set_anonymous(true);
        a.set_key("key");
        a.set_dataset(OptionRefAny::Some(RefAny::new(7u64)));
        a.set_svg_data(SvgNodeData::GradientStop { offset: 0.5 });
        a.set_context_menu(Menu::create(Vec::new().into()));
        a.set_merge_callback(merge_cb_a as DatasetMergeCallbackType);
        a.set_css("color: red;");
        let b = a.clone();
        assert_eq!(a, b, "clone must be value-equal");
        assert_eq!(
            hash_of(&a),
            hash_of(&b),
            "Eq == true but hashes differ: Hash/Eq contract violated"
        );
        assert_eq!(a.calculate_node_data_hash(), b.calculate_node_data_hash());
        // copy_special must agree with Clone.
        assert_eq!(a.copy_special(), b);
    }
    // =====================================================================
    // NodeData — Display / node_data_to_string (serializer)
    // =====================================================================
    #[test]
    fn node_data_to_string_is_empty_for_a_bare_node() {
        // Private fn — only reachable from an inline test module.
        assert_eq!(node_data_to_string(&NodeData::create_div()), "");
    }
    #[test]
    fn node_data_to_string_emits_ids_classes_and_tabindex() {
        let mut nd = NodeData::create_div();
        nd.add_id("i1".into());
        nd.add_id("i2".into());
        nd.add_class("c1".into());
        nd.set_tab_index(TabIndex::NoKeyboardFocus);
        let s = node_data_to_string(&nd);
        assert!(s.contains(r#"id="i1 i2""#), "ids are space-joined: {s}");
        assert!(s.contains(r#"class="c1""#), "{s}");
        assert!(s.contains(r#"tabindex="-1""#), "{s}");
    }
    #[test]
    fn node_data_display_is_self_closing_without_content() {
        let s = format!("{}", NodeData::create_div());
        assert!(s.starts_with('<'), "{s}");
        assert!(s.ends_with("/>"), "content-less nodes self-close: {s}");
    }
    #[test]
    fn node_data_display_wraps_text_content_in_a_tag_pair() {
        let s = format!(
            "{}",
            NodeData::create_text_do_not_use_without_block_level_wrapper("hello")
        );
        assert!(s.starts_with('<'));
        assert!(s.ends_with('>'));
        assert!(s.contains("hello"), "{s}");
        assert!(
            !s.ends_with("/>"),
            "a node with content must not self-close"
        );
    }
    #[test]
    fn node_data_display_does_not_panic_on_hostile_text() {
        // NOTE: Display is a debug/inspection aid and does NOT escape markup — a text
        // node containing `<script>` reproduces it verbatim. Assert only that it is
        // total (no panic) and round-trips the bytes; see report.
        for text in [
            "",
            "<script>alert(1)</script>",
            "\" onload=\"x",
            "日本語 🎉",
            "line\nbreak\ttab",
        ] {
            let s = format!(
                "{}",
                NodeData::create_text_do_not_use_without_block_level_wrapper(text)
            );
            assert!(s.contains(text), "Display dropped content for {text:?}");
        }
    }
    #[test]
    fn node_data_display_survives_a_huge_text_payload() {
        let big = huge_unicode_string();
        let s = format!(
            "{}",
            NodeData::create_text_do_not_use_without_block_level_wrapper(big.clone())
        );
        assert!(s.len() > big.len());
    }
    #[test]
    fn debug_print_end_matches_the_node_tag() {
        let s = NodeData::create_div().debug_print_end();
        assert!(s.starts_with("</"));
        assert!(s.ends_with('>'));
    }
    // =====================================================================
    // NodeData — setters / builders / swap
    // =====================================================================
    #[test]
    fn set_node_type_replaces_the_type_and_keeps_the_attributes() {
        let mut nd = NodeData::create_div();
        nd.add_id("keep".into());
        nd.set_node_type(NodeType::Span);
        assert!(nd.is_node_type(NodeType::Span));
        assert!(
            nd.has_id("keep"),
            "changing the tag must not drop attributes"
        );
    }
    #[test]
    fn add_callback_appends_and_get_callbacks_reflects_it() {
        let mut nd = NodeData::create_div();
        assert!(nd.get_callbacks().as_ref().is_empty());
        nd.add_callback(
            EventFilter::Hover(HoverEventFilter::MouseUp),
            RefAny::new(1u32),
            0usize,
        );
        nd.add_callback(
            EventFilter::Focus(FocusEventFilter::MouseDown),
            RefAny::new(2u32),
            1usize,
        );
        assert_eq!(nd.get_callbacks().as_ref().len(), 2);
        assert_eq!(
            nd.get_callbacks().as_ref()[0].event,
            EventFilter::Hover(HoverEventFilter::MouseUp)
        );
    }
    #[test]
    fn add_css_property_appends_an_inline_rule() {
        use azul_css::props::property::{CssProperty, CssPropertyType};
        let mut nd = NodeData::create_div();
        assert!(nd.get_style().rules.as_ref().is_empty());
        nd.add_css_property(CssPropertyWithConditions {
            property: CssProperty::const_none(CssPropertyType::Display),
            apply_if: Vec::new().into(),
        });
        assert_eq!(nd.get_style().rules.as_ref().len(), 1);
        nd.add_css_property(CssPropertyWithConditions {
            property: CssProperty::const_none(CssPropertyType::Display),
            apply_if: Vec::new().into(),
        });
        assert_eq!(
            nd.get_style().rules.as_ref().len(),
            2,
            "add_css_property appends, it does not replace"
        );
    }
    #[test]
    fn set_style_replaces_whereas_set_css_appends() {
        let mut nd = NodeData::create_div();
        nd.set_css("color: red;");
        let after_first = nd.get_style().rules.as_ref().len();
        assert!(after_first > 0);
        nd.set_css("color: blue;");
        assert!(
            nd.get_style().rules.as_ref().len() > after_first,
            "set_css appends to the existing inline style"
        );
        nd.set_style(azul_css::css::Css {
            rules: Vec::new().into(),
            keyframes: Vec::new().into(),
        });
        assert!(
            nd.get_style().rules.as_ref().is_empty(),
            "set_style replaces wholesale"
        );
    }
    #[test]
    fn set_css_with_empty_and_malformed_input_does_not_panic() {
        for style in [
            "",
            "   ",
            ";;;;",
            "color",
            "color:",
            ":",
            "}",
            "{",
            "color: ;",
            "not-a-property: not-a-value;",
            ":hover {",
            "@os {",
            "color: red",       // no trailing semicolon
            "\u{0}color: red;", // NUL byte
            "color: 日本語;",
        ] {
            let nd = NodeData::create_div().with_css(style);
            // The only contract for malformed input is "don't panic"; whether a rule
            // survives parsing is the CSS parser's business.
            let _ = nd.get_style().rules.as_ref().len();
        }
    }
    #[test]
    fn swap_with_default_returns_the_original_and_leaves_a_div() {
        let mut nd = NodeData::create_text_do_not_use_without_block_level_wrapper("payload");
        let taken = nd.swap_with_default();
        assert!(taken.is_text_node());
        assert!(
            nd.is_node_type(NodeType::Div),
            "the slot becomes a fresh div"
        );
        assert!(nd.attributes().as_ref().is_empty());
    }
    #[test]
    fn node_data_builders_are_equivalent_to_their_setters() {
        let built = NodeData::create_div()
            .with_tab_index(TabIndex::Auto)
            .with_contenteditable(true)
            .with_node_type(NodeType::Span);
        let mut set = NodeData::create_div();
        set.set_tab_index(TabIndex::Auto);
        set.set_contenteditable(true);
        set.set_node_type(NodeType::Span);
        assert_eq!(built, set);
    }
    // =====================================================================
    // NodeDataVec containers
    // =====================================================================
    #[test]
    fn node_data_vec_as_container_is_empty_for_an_empty_vec() {
        let v: NodeDataVec = Vec::new().into();
        assert_eq!(v.as_container().internal.len(), 0);
    }
    #[test]
    fn node_data_vec_containers_expose_and_mutate_the_backing_slice() {
        let mut v: NodeDataVec = vec![
            NodeData::create_div(),
            NodeData::create_br(),
            NodeData::create_text_do_not_use_without_block_level_wrapper("t"),
        ]
        .into();
        assert_eq!(v.as_container().internal.len(), 3);
        assert!(v.as_container().internal[2].is_text_node());
        v.as_container_mut().internal[0].set_node_type(NodeType::Span);
        assert!(v.as_container().internal[0].is_node_type(NodeType::Span));
    }
    // =====================================================================
    // Dom — child bookkeeping
    // =====================================================================
    #[test]
    fn dom_default_is_an_empty_body() {
        let d = Dom::default();
        assert!(d.root.is_node_type(NodeType::Body));
        assert_eq!(d.estimated_total_children, 0);
        assert_eq!(d.node_count(), 1);
    }
    #[test]
    fn dom_set_children_recomputes_the_estimate_from_scratch() {
        let child = Dom::create_div().with_child(Dom::create_div());
        let mut parent = Dom::create_div();
        parent.add_child(Dom::create_div());
        assert_eq!(parent.estimated_total_children, 1);
        // set_children REPLACES; the old child must not be counted twice.
        parent.set_children(vec![child].into());
        assert_eq!(parent.estimated_total_children, 2);
        assert_eq!(
            parent.estimated_total_children,
            parent.recompute_estimated_total_children()
        );
    }
    #[test]
    fn dom_set_children_with_an_empty_vec_zeroes_the_estimate() {
        let mut d = Dom::create_div().with_child(Dom::create_div().with_child(Dom::create_div()));
        assert_eq!(d.estimated_total_children, 2);
        d.set_children(Vec::new().into());
        assert_eq!(d.estimated_total_children, 0);
        assert_eq!(d.node_count(), 1);
    }
    #[test]
    fn dom_deeply_nested_chain_keeps_an_exact_estimate() {
        // 256-deep chain: every level adds exactly one descendant.
        const DEPTH: usize = 256;
        let mut d = Dom::create_div();
        for _ in 0..DEPTH {
            d = Dom::create_div().with_child(d);
        }
        assert_eq!(d.estimated_total_children, DEPTH);
        assert_eq!(d.node_count(), DEPTH + 1);
        assert_eq!(d.recompute_estimated_total_children(), DEPTH);
    }
    #[test]
    fn dom_very_wide_child_list_keeps_an_exact_estimate() {
        const WIDTH: usize = 5_000;
        let children: Vec<Dom> = (0..WIDTH).map(|_| Dom::create_div()).collect();
        let d = Dom::create_div().with_children(children.into());
        assert_eq!(d.estimated_total_children, WIDTH);
        assert_eq!(d.node_count(), WIDTH + 1);
    }
    #[test]
    fn dom_from_iterator_counts_nested_grandchildren() {
        let empty: Dom = Vec::new().into_iter().collect();
        assert_eq!(empty.estimated_total_children, 0);
        assert!(empty.root.is_node_type(NodeType::Div));
        // Two children, one of which has a child of its own => 3 descendants.
        let d: Dom = vec![
            Dom::create_div().with_child(Dom::create_div()),
            Dom::create_div(),
        ]
        .into_iter()
        .collect();
        assert_eq!(d.estimated_total_children, 3);
        assert_eq!(
            d.estimated_total_children,
            d.recompute_estimated_total_children()
        );
        assert_eq!(d.node_count(), 4);
    }
    #[test]
    fn dom_fixup_repairs_a_corrupted_estimate_at_every_depth() {
        let mut d = Dom::create_div()
            .with_child(Dom::create_div().with_child(Dom::create_div()))
            .with_child(Dom::create_div());
        // Corrupt the cached counter at BOTH levels (the public field makes this
        // reachable from safe code, which is what fixup exists to undo).
        d.estimated_total_children = 0;
        d.children.as_mut()[0].estimated_total_children = 99;
        let repaired = d.fixup_children_estimated();
        assert_eq!(repaired, 3);
        assert_eq!(d.children.as_ref()[0].estimated_total_children, 1);
        assert_eq!(
            d.estimated_total_children,
            d.recompute_estimated_total_children()
        );
    }
    #[test]
    fn dom_fixup_on_a_leaf_zeroes_a_bogus_estimate() {
        let mut d = Dom::create_div();
        d.estimated_total_children = usize::MAX;
        assert_eq!(d.fixup_children_estimated(), 0);
        assert_eq!(d.node_count(), 1, "node_count is safe again after fixup");
    }
    // `estimated_total_children` is a public field, so `usize::MAX` is
    // reachable. This used to be `#[cfg(debug_assertions)] #[should_panic]`,
    // pinning "panics in debug, wraps to 0 in release" — i.e. pinning a
    // divergence where the release answer was the dangerous one (0 reads as
    // "empty DOM"). `node_count` saturates now, so assert the SAME defined
    // answer in both configurations, and assert it is not the empty-DOM value.
    #[test]
    fn dom_node_count_saturates_on_a_corrupted_max_estimate() {
        let mut d = Dom::create_div();
        d.estimated_total_children = usize::MAX;
        assert_eq!(d.node_count(), usize::MAX);
        assert_ne!(
            d.node_count(),
            0,
            "wrapping to 0 would claim an empty DOM — the one answer callers act on without \
             checking"
        );
    }
    #[test]
    fn dom_swap_with_default_returns_the_original_tree() {
        let mut d = Dom::create_div().with_child(Dom::create_div());
        let taken = d.swap_with_default();
        assert_eq!(taken.estimated_total_children, 1);
        assert_eq!(d.estimated_total_children, 0, "the slot is reset");
        assert!(d.root.is_node_type(NodeType::Div));
    }
    // =====================================================================
    // Dom — builders
    // =====================================================================
    #[test]
    fn dom_with_id_and_with_class_apply_to_the_root() {
        let d = Dom::create_div()
            .with_id("root".into())
            .with_class("card".into());
        assert!(d.root.has_id("root"));
        assert!(d.root.has_class("card"));
    }
    #[test]
    fn dom_with_attribute_appends_and_with_attributes_replaces() {
        let d = Dom::create_div()
            .with_attribute(AttributeType::Href("/a".into()))
            .with_attribute(AttributeType::Alt("alt".into()));
        assert_eq!(d.root.attributes().as_ref().len(), 2);
        let d = d.with_attributes(vec![AttributeType::Disabled].into());
        assert_eq!(
            d.root.attributes().as_ref().len(),
            1,
            "with_attributes replaces wholesale"
        );
        assert_eq!(d.root.attributes().as_ref()[0], AttributeType::Disabled);
    }
    #[test]
    fn dom_add_component_css_stacks_stylesheets() {
        let mut d = Dom::create_div();
        assert!(d.css.as_ref().is_empty());
        d.set_css("color: red;");
        d.set_css("color: blue;");
        assert_eq!(d.css.as_ref().len(), 2, "each set_css pushes a stylesheet");
        d.set_component_css(Vec::new().into());
        assert!(d.css.as_ref().is_empty(), "set_component_css replaces");
    }
    #[test]
    fn dom_with_css_does_not_panic_on_malformed_input() {
        for style in ["", "}}}", "@os {", "color:", "\u{0}"] {
            let d = Dom::create_div().with_css(style);
            assert_eq!(
                d.css.as_ref().len(),
                1,
                "a Css is pushed even if it parses empty"
            );
        }
    }
    #[test]
    fn dom_text_helpers_produce_a_text_child() {
        let d = Dom::create_h1_with_text("Title");
        assert!(d.root.is_node_type(NodeType::H1));
        assert_eq!(d.estimated_total_children, 1);
        assert!(d.children.as_ref()[0].root.is_text_node());
    }
    #[test]
    fn dom_create_geolocation_probe_carries_its_config() {
        let cfg = crate::geolocation::GeolocationProbeConfig {
            high_accuracy: true,
            background: false,
            max_accuracy_m: 25.0,
            min_interval_ms: 1_000,
        };
        let d = Dom::create_geolocation_probe(cfg);
        match d.root.get_node_type() {
            NodeType::GeolocationProbe(c) => {
                assert!(c.high_accuracy);
                assert_eq!(c.min_interval_ms, 1_000);
            }
            other => panic!("expected GeolocationProbe, got {other:?}"),
        }
    }
    #[test]
    fn dom_clone_and_eq_agree_on_a_nested_tree() {
        let d = Dom::create_div()
            .with_id("r".into())
            .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("a"))
            .with_child(
                Dom::create_div()
                    .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("b")),
            );
        let c = d.clone();
        assert_eq!(d, c);
        assert_eq!(hash_of(&d), hash_of(&c));
        // text("a") + div + text("b") == 3 descendants.
        assert_eq!(c.estimated_total_children, 3);
        assert_eq!(c.node_count(), 4);
    }
    #[test]
    fn dom_debug_does_not_panic_on_a_nested_tree() {
        let d = Dom::create_div()
            .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                "日本語 🎉",
            ))
            .with_child(Dom::create_div().with_child(Dom::create_br()));
        let s = format!("{d:?}");
        assert!(s.contains("Dom"));
        assert!(s.contains("estimated_total_children"));
    }
    // =====================================================================
    // DomId / DomNodeId
    // =====================================================================
    #[test]
    fn dom_id_root_is_zero_and_is_the_default() {
        assert_eq!(DomId::ROOT_ID.inner, 0);
        assert_eq!(DomId::default(), DomId::ROOT_ID);
        assert_eq!(format!("{}", DomId::ROOT_ID), "0");
        assert_eq!(
            format!("{}", DomId { inner: usize::MAX }),
            usize::MAX.to_string()
        );
    }
    #[test]
    fn dom_node_id_root_points_at_the_root_dom_and_no_node() {
        assert_eq!(DomNodeId::ROOT.dom, DomId::ROOT_ID);
        assert_eq!(DomNodeId::ROOT.node, NodeHierarchyItemId::NONE);
    }
    /// `autofocus` is a boolean attribute, like HTML's: present means true,
    /// and it reports itself under that name so a serializer / inspector
    /// round-trips it.
    #[test]
    fn autofocus_is_a_boolean_attribute() {
        use crate::dom::{AttributeType, Dom, NodeData};
        let plain = NodeData::create_node(crate::dom::NodeType::Div);
        assert!(!plain.has_autofocus(), "absent means no autofocus");
        let dom = Dom::create_div().with_attribute(AttributeType::Autofocus);
        assert!(dom.root.has_autofocus(), "present means autofocus");
        assert_eq!(AttributeType::Autofocus.name(), "autofocus");
        assert_eq!(AttributeType::Autofocus.value().as_str(), "true");
    }
    // =====================================================================
    // Markers
    // =====================================================================
    /// USER ruling 2026-08-29: markers are minted FRESH (UUID strings) at
    /// every `layout()` and exist only to be resolved back to a node - they
    /// must never factor into equality or hashing, or every marked node
    /// would look "changed" to the DOM diff on every frame.
    #[test]
    fn markers_are_excluded_from_node_equality_and_hashing() {
        use core::hash::{Hash, Hasher};
        let a = NodeData::create_div().with_marker(Some("uuid-of-frame-1".into()).into());
        let b = NodeData::create_div().with_marker(Some("uuid-of-frame-2".into()).into());
        let none = NodeData::create_div();
        assert_eq!(a, b, "two nodes differing only in marker must be EQUAL");
        assert_eq!(a, none, "a marked node must equal its unmarked twin");
        assert_eq!(
            a.partial_cmp(&b),
            Some(core::cmp::Ordering::Equal),
            "ordering must ignore the marker too",
        );
        let hash_of = |nd: &NodeData| {
            let mut h = crate::hash::DefaultHasher::new();
            nd.hash(&mut h);
            h.finish()
        };
        assert_eq!(hash_of(&a), hash_of(&b), "hashes must ignore the marker");
        assert_eq!(hash_of(&a), hash_of(&none));
        // The marker is still THERE - excluded from identity, not dropped.
        assert_eq!(a.get_marker().map(|m| m.as_str()), Some("uuid-of-frame-1"));
        assert_eq!(none.get_marker(), None);
    }
}