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

            
8
2
    fn node_map(from: usize, to: usize) -> alloc::collections::BTreeMap<NodeId, NodeId> {
9
2
        let mut m = alloc::collections::BTreeMap::new();
10
2
        m.insert(NodeId::new(from), NodeId::new(to));
11
2
        m
12
2
    }
13

            
14
2
    fn dnid(dom: usize, node: usize) -> DomNodeId {
15
2
        DomNodeId {
16
2
            dom: DomId { inner: dom },
17
2
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(node))),
18
2
        }
19
2
    }
20

            
21
    #[test]
22
1
    fn scrollbar_remap_scoped_to_dom() {
23
1
        let mut ctx = DragContext::scrollbar_thumb(
24
1
            DomId { inner: 0 },
25
1
            NodeId::new(3),
26
1
            ScrollbarAxis::Vertical,
27
1
            LogicalPosition::zero(),
28
            0.0,
29
            100.0,
30
            300.0,
31
            100.0,
32
            1,
33
        );
34
        // Reconciling a *different* DOM (id 1) must not touch our node id.
35
1
        let ok = ctx.remap_node_ids(DomId { inner: 1 }, &node_map(3, 99));
36
1
        assert!(ok);
37
1
        assert_eq!(
38
1
            ctx.as_scrollbar_thumb().unwrap().scroll_container_node,
39
1
            NodeId::new(3)
40
        );
41

            
42
        // Reconciling our own DOM (id 0) remaps it.
43
1
        let ok2 = ctx.remap_node_ids(DomId { inner: 0 }, &node_map(3, 99));
44
1
        assert!(ok2);
45
1
        assert_eq!(
46
1
            ctx.as_scrollbar_thumb().unwrap().scroll_container_node,
47
1
            NodeId::new(99)
48
        );
49
1
    }
50

            
51
    #[test]
52
1
    fn node_drag_remaps_previous_drop_target() {
53
1
        let mut ctx = DragContext::node_drag(
54
1
            DomId { inner: 0 },
55
1
            NodeId::new(1),
56
1
            LogicalPosition::zero(),
57
1
            DragData::new(),
58
            2,
59
        );
60
1
        {
61
1
            let nd = ctx.as_node_drag_mut().unwrap();
62
1
            nd.current_drop_target = Some(dnid(0, 5)).into();
63
1
            nd.previous_drop_target = Some(dnid(0, 6)).into();
64
1
        }
65
        // Map: dragged node 1->1, drop targets 5->50, 6->60.
66
1
        let mut m = alloc::collections::BTreeMap::new();
67
1
        m.insert(NodeId::new(1), NodeId::new(1));
68
1
        m.insert(NodeId::new(5), NodeId::new(50));
69
1
        m.insert(NodeId::new(6), NodeId::new(60));
70
1
        assert!(ctx.remap_node_ids(DomId { inner: 0 }, &m));
71

            
72
1
        let nd = ctx.as_node_drag().unwrap();
73
1
        let cur = nd
74
1
            .current_drop_target
75
1
            .into_option()
76
1
            .unwrap()
77
1
            .node
78
1
            .into_crate_internal()
79
1
            .unwrap();
80
1
        let prev = nd
81
1
            .previous_drop_target
82
1
            .into_option()
83
1
            .unwrap()
84
1
            .node
85
1
            .into_crate_internal()
86
1
            .unwrap();
87
1
        assert_eq!(cur, NodeId::new(50));
88
1
        assert_eq!(prev, NodeId::new(60)); // previously left stale (bug)
89
1
    }
90
}
91

            
92
#[cfg(test)]
93
mod autotest_generated {
94
    use alloc::{
95
        collections::BTreeMap,
96
        string::{String, ToString},
97
    };
98

            
99
    use super::*;
100
    use crate::{geom::PhysicalPosition, styled_dom::NodeHierarchyItemId};
101

            
102
    // ---------------------------------------------------------------- helpers
103

            
104
    fn dom(i: usize) -> DomId {
105
        DomId { inner: i }
106
    }
107

            
108
    fn dnid(dom_idx: usize, node: usize) -> DomNodeId {
109
        DomNodeId {
110
            dom: dom(dom_idx),
111
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(node))),
112
        }
113
    }
114

            
115
    /// A drop target that points at a DOM but carries *no* node id (the `None`
116
    /// encoding of `NodeHierarchyItemId`).
117
    fn dnid_no_node(dom_idx: usize) -> DomNodeId {
118
        DomNodeId {
119
            dom: dom(dom_idx),
120
            node: NodeHierarchyItemId::from_crate_internal(None),
121
        }
122
    }
123

            
124
    fn nid_map(pairs: &[(usize, usize)]) -> BTreeMap<NodeId, NodeId> {
125
        let mut m = BTreeMap::new();
126
        for (from, to) in pairs {
127
            m.insert(NodeId::new(*from), NodeId::new(*to));
128
        }
129
        m
130
    }
131

            
132
    /// Vertical scrollbar drag anchored at (0, 0), no mouse movement yet.
133
    fn vscroll(
134
        start_scroll_offset: f32,
135
        track_length_px: f32,
136
        content_length_px: f32,
137
        viewport_length_px: f32,
138
    ) -> DragContext {
139
        DragContext::scrollbar_thumb(
140
            dom(0),
141
            NodeId::new(1),
142
            ScrollbarAxis::Vertical,
143
            LogicalPosition::zero(),
144
            start_scroll_offset,
145
            track_length_px,
146
            content_length_px,
147
            viewport_length_px,
148
            7,
149
        )
150
    }
151

            
152
    fn resize_ctx() -> DragContext {
153
        DragContext::new(
154
            ActiveDragType::WindowResize(WindowResizeDrag {
155
                edge: WindowResizeEdge::BottomRight,
156
                start_position: LogicalPosition::new(1.0, 2.0),
157
                current_position: LogicalPosition::new(1.0, 2.0),
158
                initial_width: u32::MAX,
159
                initial_height: 0,
160
            }),
161
            u64::MAX,
162
        )
163
    }
164

            
165
    // ============================================================ DragData
166
    // parser-ish surface: get_data / set_data / set_text / get_text
167

            
168
    #[test]
169
    fn dragdata_new_is_empty_and_matches_default() {
170
        let d = DragData::new();
171
        assert_eq!(d.data.len(), 0);
172
        assert!(d.data.is_empty());
173
        assert_eq!(d.effect_allowed, DragEffect::Uninitialized);
174
        assert_eq!(d, DragData::default());
175
        assert!(d.get_data("text/plain").is_none());
176
        assert!(d.get_text().is_none());
177
    }
178

            
179
    #[test]
180
    fn get_data_valid_minimal_positive_control() {
181
        let mut d = DragData::new();
182
        d.set_data("text/plain", b"hi".to_vec());
183
        assert_eq!(d.get_data("text/plain"), Some(&b"hi"[..]));
184
    }
185

            
186
    #[test]
187
    fn get_data_empty_key_on_empty_and_populated_returns_none() {
188
        let empty = DragData::new();
189
        assert!(empty.get_data("").is_none());
190

            
191
        let mut d = DragData::new();
192
        d.set_data("text/plain", b"x".to_vec());
193
        assert!(d.get_data("").is_none());
194
    }
195

            
196
    #[test]
197
    fn get_data_empty_key_is_a_real_key_when_stored() {
198
        // "" is not special-cased: it is a perfectly good (if silly) map key.
199
        let mut d = DragData::new();
200
        d.set_data("", b"empty-key".to_vec());
201
        assert_eq!(d.get_data(""), Some(&b"empty-key"[..]));
202
        assert!(d.get_data("text/plain").is_none());
203
    }
204

            
205
    #[test]
206
    fn get_data_whitespace_only_keys_return_none() {
207
        let mut d = DragData::new();
208
        d.set_data("text/plain", b"x".to_vec());
209
        for k in ["   ", "\t\n", "\r\n", "\u{a0}", "\u{2028}"] {
210
            assert!(d.get_data(k).is_none(), "whitespace key {k:?} matched");
211
        }
212
    }
213

            
214
    #[test]
215
    fn get_data_garbage_bytes_return_none_without_panicking() {
216
        let mut d = DragData::new();
217
        d.set_data("text/plain", b"x".to_vec());
218
        for k in [
219
            "\u{0}",
220
            "\u{0}\u{1}\u{2}\u{7f}",
221
            "\u{feff}",
222
            "%%%;;;///",
223
            "text/plain\u{0}",
224
            "\u{0}text/plain",
225
        ] {
226
            assert!(d.get_data(k).is_none(), "garbage key {k:?} matched");
227
        }
228
    }
229

            
230
    #[test]
231
    fn get_data_leading_trailing_junk_is_not_trimmed() {
232
        let mut d = DragData::new();
233
        d.set_data("text/plain", b"x".to_vec());
234
        // Lookup is an exact byte-for-byte match: no trimming, no tolerance.
235
        assert!(d.get_data("  text/plain  ").is_none());
236
        assert!(d.get_data("text/plain;garbage").is_none());
237
        assert!(d.get_data("text/plain ").is_none());
238
        assert!(d.get_data(" text/plain").is_none());
239
        assert_eq!(d.get_data("text/plain"), Some(&b"x"[..]));
240
    }
241

            
242
    #[test]
243
    fn get_data_is_case_sensitive() {
244
        // MIME types are case-insensitive per RFC 2045, but this map is not.
245
        let mut d = DragData::new();
246
        d.set_data("text/plain", b"x".to_vec());
247
        assert!(d.get_data("TEXT/PLAIN").is_none());
248
        assert!(d.get_data("Text/Plain").is_none());
249
    }
250

            
251
    #[test]
252
    fn get_data_boundary_number_strings_return_none() {
253
        let mut d = DragData::new();
254
        d.set_data("text/plain", b"x".to_vec());
255
        for k in [
256
            "0",
257
            "-0",
258
            "9223372036854775807",  // i64::MAX
259
            "-9223372036854775808", // i64::MIN
260
            "18446744073709551615", // u64::MAX
261
            "1e400",
262
            "NaN",
263
            "inf",
264
            "-inf",
265
            "1.7976931348623157e308",
266
            "5e-324",
267
        ] {
268
            assert!(d.get_data(k).is_none(), "numeric key {k:?} matched");
269
        }
270
    }
271

            
272
    #[test]
273
    fn get_data_unicode_keys_round_trip() {
274
        let mut d = DragData::new();
275
        let emoji = "application/x-\u{1F600};charset=utf-8";
276
        let combining = "text/e\u{0301}"; // e + combining acute
277
        d.set_data(emoji, b"grin".to_vec());
278
        d.set_data(combining, b"acute".to_vec());
279

            
280
        assert_eq!(d.get_data(emoji), Some(&b"grin"[..]));
281
        assert_eq!(d.get_data(combining), Some(&b"acute"[..]));
282
        // NFC-equivalent but byte-distinct key must NOT match (no normalization).
283
        assert!(d.get_data("text/\u{e9}").is_none());
284
        assert_eq!(d.data.len(), 2);
285
    }
286

            
287
    #[test]
288
    fn get_data_extremely_long_key_does_not_panic_or_hang() {
289
        let huge: String = "a".repeat(1_000_000);
290
        let mut d = DragData::new();
291
        d.set_data("text/plain", b"x".to_vec());
292
        // Miss against a 1M-char key.
293
        assert!(d.get_data(&huge).is_none());
294
        // Round-trip the 1M-char key itself.
295
        d.set_data(huge.as_str(), b"huge-key".to_vec());
296
        assert_eq!(d.get_data(&huge), Some(&b"huge-key"[..]));
297
        // A 1M-char key that differs only in the last byte must miss.
298
        let mut nearly = huge.clone();
299
        let _ = nearly.pop();
300
        nearly.push('b');
301
        assert!(d.get_data(&nearly).is_none());
302
    }
303

            
304
    #[test]
305
    fn get_data_deeply_nested_brackets_do_not_stack_overflow() {
306
        // The lookup is a linear scan, not a recursive-descent parse: 10k
307
        // nested brackets must be inert.
308
        let nested: String = "[".repeat(10_000);
309
        let mut d = DragData::new();
310
        assert!(d.get_data(&nested).is_none());
311
        d.set_data(nested.as_str(), b"nested".to_vec());
312
        assert_eq!(d.get_data(&nested), Some(&b"nested"[..]));
313
    }
314

            
315
    #[test]
316
    fn set_data_replaces_existing_entry_for_same_mime() {
317
        let mut d = DragData::new();
318
        d.set_data("text/plain", b"first".to_vec());
319
        d.set_data("text/plain", b"second".to_vec());
320
        assert_eq!(d.data.len(), 1, "duplicate MIME key was appended");
321
        assert_eq!(d.get_data("text/plain"), Some(&b"second"[..]));
322
    }
323

            
324
    #[test]
325
    fn set_data_empty_payload_is_some_empty_not_none() {
326
        let mut d = DragData::new();
327
        d.set_data("application/octet-stream", Vec::new());
328
        // Presence and emptiness are distinguishable.
329
        assert_eq!(d.get_data("application/octet-stream"), Some(&b""[..]));
330
        assert!(d.get_data("application/octet-stream").is_some());
331
    }
332

            
333
    #[test]
334
    fn set_data_huge_payload_round_trips() {
335
        let mut d = DragData::new();
336
        let payload = alloc::vec![0xABu8; 1 << 20]; // 1 MiB
337
        d.set_data("application/octet-stream", payload);
338
        let got = d.get_data("application/octet-stream").unwrap();
339
        assert_eq!(got.len(), 1 << 20);
340
        assert!(got.iter().all(|b| *b == 0xAB));
341
    }
342

            
343
    #[test]
344
    fn set_data_binary_payload_is_not_utf8_validated() {
345
        let mut d = DragData::new();
346
        d.set_data("application/octet-stream", alloc::vec![0xFF, 0x00, 0xFE]);
347
        assert_eq!(
348
            d.get_data("application/octet-stream"),
349
            Some(&[0xFFu8, 0x00, 0xFE][..])
350
        );
351
    }
352

            
353
    #[test]
354
    fn set_data_many_distinct_mime_types_all_retrievable() {
355
        let mut d = DragData::new();
356
        for i in 0..1_000usize {
357
            let mut key = String::from("application/x-");
358
            key.push_str(&i.to_string());
359
            d.set_data(key.as_str(), alloc::vec![(i % 251) as u8]);
360
        }
361
        assert_eq!(d.data.len(), 1_000);
362
        assert_eq!(d.get_data("application/x-0"), Some(&[0u8][..]));
363
        assert_eq!(
364
            d.get_data("application/x-999"),
365
            Some(&[(999 % 251) as u8][..])
366
        );
367
        assert!(d.get_data("application/x-1000").is_none());
368
    }
369

            
370
    #[test]
371
    fn set_text_get_text_round_trip_unicode() {
372
        for s in [
373
            "hello",
374
            "",
375
            "\u{1F600}\u{1F4A9}",
376
            "e\u{0301}\u{0300}\u{0308}", // stacked combining marks
377
            "\u{200B}zero-width",
378
            "line1\nline2\r\n\ttab",
379
            "\u{0}interior nul\u{0}",
380
        ] {
381
            let mut d = DragData::new();
382
            d.set_text(s);
383
            let got = d.get_text().expect("text/plain must be present");
384
            assert_eq!(got.as_str(), s, "round-trip failed for {s:?}");
385
        }
386
    }
387

            
388
    #[test]
389
    fn set_text_empty_is_some_not_none() {
390
        let mut d = DragData::new();
391
        d.set_text("");
392
        assert!(d.get_text().is_some());
393
        assert_eq!(d.get_text().unwrap().as_str(), "");
394
        assert_eq!(d.get_data("text/plain"), Some(&b""[..]));
395
    }
396

            
397
    #[test]
398
    fn set_text_huge_string_round_trips() {
399
        let huge: String = "\u{1F600}".repeat(100_000); // 400_000 bytes
400
        let mut d = DragData::new();
401
        d.set_text(huge.as_str());
402
        let got = d.get_text().unwrap();
403
        assert_eq!(got.as_str().len(), 400_000);
404
        assert_eq!(got.as_str(), huge.as_str());
405
        assert_eq!(d.data.len(), 1);
406
    }
407

            
408
    #[test]
409
    fn set_text_twice_replaces_and_does_not_grow() {
410
        let mut d = DragData::new();
411
        d.set_text("one");
412
        d.set_text("two");
413
        assert_eq!(d.data.len(), 1);
414
        assert_eq!(d.get_text().unwrap().as_str(), "two");
415
    }
416

            
417
    #[test]
418
    fn set_text_then_set_data_on_same_mime_wins() {
419
        let mut d = DragData::new();
420
        d.set_text("text");
421
        d.set_data("text/plain", b"raw".to_vec());
422
        assert_eq!(d.data.len(), 1);
423
        assert_eq!(d.get_text().unwrap().as_str(), "raw");
424
    }
425

            
426
    #[test]
427
    fn get_text_on_invalid_utf8_yields_empty_string_not_panic() {
428
        // Documents the `unwrap_or("")` fallback: invalid UTF-8 under
429
        // "text/plain" is silently reported as an EMPTY string, not None and
430
        // not a panic. (Lossy data: the bytes are still there via get_data.)
431
        let mut d = DragData::new();
432
        d.set_data("text/plain", alloc::vec![0xFF, 0xFE, 0x80]);
433
        let got = d.get_text().expect("entry exists, so Some");
434
        assert_eq!(got.as_str(), "");
435
        assert_eq!(d.get_data("text/plain"), Some(&[0xFFu8, 0xFE, 0x80][..]));
436
    }
437

            
438
    #[test]
439
    fn get_text_truncated_utf8_yields_empty_string() {
440
        let mut d = DragData::new();
441
        // First 3 bytes of a 4-byte emoji.
442
        d.set_data("text/plain", alloc::vec![0xF0, 0x9F, 0x98]);
443
        assert_eq!(d.get_text().unwrap().as_str(), "");
444
    }
445

            
446
    #[test]
447
    fn get_text_is_none_when_only_other_mimes_present() {
448
        let mut d = DragData::new();
449
        d.set_data("text/html", b"<b>x</b>".to_vec());
450
        assert!(d.get_text().is_none());
451
    }
452

            
453
    // ==================================================== DragContext ctors
454

            
455
    #[test]
456
    fn drag_context_new_preserves_session_id_and_is_not_cancelled() {
457
        for sid in [0u64, 1, u64::MAX] {
458
            let ctx = DragContext::new(
459
                ActiveDragType::WindowMove(WindowMoveDrag {
460
                    start_position: LogicalPosition::zero(),
461
                    current_position: LogicalPosition::zero(),
462
                    initial_window_position: WindowPosition::Uninitialized,
463
                }),
464
                sid,
465
            );
466
            assert_eq!(ctx.session_id, sid);
467
            assert!(!ctx.cancelled);
468
        }
469
    }
470

            
471
    #[test]
472
    fn text_selection_invariants_at_extremes() {
473
        let pos = LogicalPosition::new(f32::MIN, f32::MAX);
474
        let ctx =
475
            DragContext::text_selection(dom(usize::MAX), NodeId::new(usize::MAX), pos, u64::MAX);
476
        let ts = ctx.as_text_selection().expect("must be a text selection");
477
        assert_eq!(ts.dom_id, dom(usize::MAX));
478
        assert_eq!(ts.anchor_ifc_node, NodeId::new(usize::MAX));
479
        assert!(ts.anchor_cursor.is_none());
480
        // start == current at construction, bit-for-bit (quantized PartialEq
481
        // would happily accept a saturated mismatch here, so compare raw bits).
482
        assert_eq!(ts.start_mouse_position.x.to_bits(), f32::MIN.to_bits());
483
        assert_eq!(ts.start_mouse_position.y.to_bits(), f32::MAX.to_bits());
484
        assert_eq!(
485
            ts.current_mouse_position.x.to_bits(),
486
            ts.start_mouse_position.x.to_bits()
487
        );
488
        assert_eq!(ctx.session_id, u64::MAX);
489
    }
490

            
491
    #[test]
492
    fn text_selection_with_nan_position_does_not_panic() {
493
        let ctx = DragContext::text_selection(
494
            dom(0),
495
            NodeId::ZERO,
496
            LogicalPosition::new(f32::NAN, f32::NEG_INFINITY),
497
            0,
498
        );
499
        let ts = ctx.as_text_selection().unwrap();
500
        assert!(ts.start_mouse_position.x.is_nan());
501
        assert!(ts.current_mouse_position.x.is_nan());
502
        assert_eq!(ts.start_mouse_position.y, f32::NEG_INFINITY);
503
    }
504

            
505
    #[test]
506
    fn scrollbar_thumb_stores_all_float_metrics_verbatim_incl_nan_inf() {
507
        let ctx = DragContext::scrollbar_thumb(
508
            dom(3),
509
            NodeId::new(9),
510
            ScrollbarAxis::Horizontal,
511
            LogicalPosition::new(f32::INFINITY, f32::NEG_INFINITY),
512
            f32::NAN,
513
            f32::INFINITY,
514
            -0.0,
515
            f32::MAX,
516
            0,
517
        );
518
        let sb = ctx.as_scrollbar_thumb().unwrap();
519
        assert_eq!(sb.dom_id, dom(3));
520
        assert_eq!(sb.scroll_container_node, NodeId::new(9));
521
        assert_eq!(sb.axis, ScrollbarAxis::Horizontal);
522
        assert!(
523
            sb.start_scroll_offset.is_nan(),
524
            "NaN was mangled at construction"
525
        );
526
        assert_eq!(sb.track_length_px, f32::INFINITY);
527
        assert!(
528
            sb.content_length_px.is_sign_negative(),
529
            "-0.0 lost its sign"
530
        );
531
        assert_eq!(sb.content_length_px, 0.0);
532
        assert_eq!(sb.viewport_length_px, f32::MAX);
533
        assert_eq!(sb.current_mouse_position.x, f32::INFINITY);
534
    }
535

            
536
    #[test]
537
    fn scrollbar_thumb_all_zero_is_constructible() {
538
        let ctx = vscroll(0.0, 0.0, 0.0, 0.0);
539
        assert!(ctx.is_scrollbar_thumb());
540
        let sb = ctx.as_scrollbar_thumb().unwrap();
541
        assert_eq!(sb.start_scroll_offset, 0.0);
542
        assert_eq!(sb.track_length_px, 0.0);
543
    }
544

            
545
    #[test]
546
    fn node_drag_invariants_hold_after_construction() {
547
        let mut data = DragData::new();
548
        data.set_text("payload");
549
        let ctx = DragContext::node_drag(
550
            dom(2),
551
            NodeId::new(usize::MAX),
552
            LogicalPosition::new(-1.5, 2.5),
553
            data,
554
            u64::MAX,
555
        );
556
        let nd = ctx.as_node_drag().unwrap();
557
        assert_eq!(nd.dom_id, dom(2));
558
        assert_eq!(nd.node_id, NodeId::new(usize::MAX));
559
        assert_eq!(nd.start_position, nd.current_position);
560
        assert_eq!(nd.drag_offset, LogicalPosition::zero());
561
        assert!(nd.current_drop_target.into_option().is_none());
562
        assert!(nd.previous_drop_target.into_option().is_none());
563
        assert!(!nd.drop_accepted);
564
        assert_eq!(nd.drop_effect, DropEffect::None);
565
        assert_eq!(nd.drag_data.get_text().unwrap().as_str(), "payload");
566
    }
567

            
568
    #[test]
569
    fn node_drag_with_empty_drag_data_is_fine() {
570
        let ctx = DragContext::node_drag(
571
            dom(0),
572
            NodeId::ZERO,
573
            LogicalPosition::new(f32::NAN, f32::NAN),
574
            DragData::new(),
575
            0,
576
        );
577
        let nd = ctx.as_node_drag().unwrap();
578
        assert!(nd.drag_data.data.is_empty());
579
        assert!(nd.start_position.x.is_nan());
580
        assert!(nd.current_position.x.is_nan());
581
    }
582

            
583
    #[test]
584
    fn window_move_preserves_initial_window_position_extremes() {
585
        for wp in [
586
            WindowPosition::Uninitialized,
587
            WindowPosition::Initialized(PhysicalPosition {
588
                x: i32::MIN,
589
                y: i32::MAX,
590
            }),
591
            WindowPosition::Initialized(PhysicalPosition { x: 0, y: 0 }),
592
        ] {
593
            let ctx =
594
                DragContext::window_move(LogicalPosition::new(f32::MAX, f32::MIN), wp, u64::MAX);
595
            let wm = ctx.as_window_move().unwrap();
596
            assert_eq!(wm.initial_window_position, wp);
597
            assert_eq!(wm.start_position.x.to_bits(), f32::MAX.to_bits());
598
            assert_eq!(
599
                wm.current_position.y.to_bits(),
600
                wm.start_position.y.to_bits()
601
            );
602
        }
603
    }
604

            
605
    #[test]
606
    fn file_drop_empty_file_list_is_allowed() {
607
        let ctx = DragContext::file_drop(Vec::new(), LogicalPosition::zero(), 0);
608
        let fd = ctx.as_file_drop().unwrap();
609
        assert_eq!(fd.files.len(), 0);
610
        assert!(fd.drop_target.into_option().is_none());
611
        assert_eq!(fd.drop_effect, DropEffect::Copy);
612
    }
613

            
614
    #[test]
615
    fn file_drop_unicode_and_pathological_filenames_round_trip() {
616
        let files = alloc::vec![
617
            AzString::from(""),
618
            AzString::from("/tmp/\u{1F4C1}/f\u{0301}ile.txt"),
619
            AzString::from("C:\\Windows\\..\\..\\etc\\passwd"),
620
            AzString::from("a".repeat(4096)),
621
            AzString::from("with\nnewline\tand\u{0}nul"),
622
        ];
623
        let ctx = DragContext::file_drop(files, LogicalPosition::new(1.0, 2.0), 42);
624
        let fd = ctx.as_file_drop().unwrap();
625
        assert_eq!(fd.files.len(), 5);
626
        assert_eq!(fd.files.as_slice()[0].as_str(), "");
627
        assert_eq!(fd.files.as_slice()[3].as_str().len(), 4096);
628
        assert_eq!(
629
            fd.files.as_slice()[4].as_str(),
630
            "with\nnewline\tand\u{0}nul"
631
        );
632
        assert_eq!(ctx.session_id, 42);
633
    }
634

            
635
    #[test]
636
    fn file_drop_ten_thousand_files_does_not_hang() {
637
        let mut files = Vec::with_capacity(10_000);
638
        for i in 0..10_000usize {
639
            files.push(AzString::from(i.to_string()));
640
        }
641
        let ctx = DragContext::file_drop(files, LogicalPosition::zero(), 1);
642
        assert_eq!(ctx.as_file_drop().unwrap().files.len(), 10_000);
643
    }
644

            
645
    // ================================================ predicates / accessors
646

            
647
    fn one_of_each() -> [DragContext; 6] {
648
        [
649
            DragContext::text_selection(dom(0), NodeId::ZERO, LogicalPosition::zero(), 0),
650
            vscroll(0.0, 100.0, 200.0, 100.0),
651
            DragContext::node_drag(
652
                dom(0),
653
                NodeId::ZERO,
654
                LogicalPosition::zero(),
655
                DragData::new(),
656
                0,
657
            ),
658
            DragContext::window_move(LogicalPosition::zero(), WindowPosition::Uninitialized, 0),
659
            resize_ctx(),
660
            DragContext::file_drop(Vec::new(), LogicalPosition::zero(), 0),
661
        ]
662
    }
663

            
664
    #[test]
665
    fn predicates_are_mutually_exclusive_across_every_variant() {
666
        for (i, ctx) in one_of_each().iter().enumerate() {
667
            let flags = [
668
                ctx.is_text_selection(),
669
                ctx.is_scrollbar_thumb(),
670
                ctx.is_node_drag(),
671
                ctx.is_window_move(),
672
                ctx.is_file_drop(),
673
            ];
674
            let set = flags.iter().filter(|f| **f).count();
675
            if i == 4 {
676
                // WindowResize has no predicate: every is_* must be false.
677
                assert_eq!(set, 0, "WindowResize matched a predicate");
678
            } else {
679
                assert_eq!(set, 1, "variant {i} matched {set} predicates, expected 1");
680
                assert!(flags[if i == 5 { 4 } else { i }], "wrong predicate for {i}");
681
            }
682
        }
683
    }
684

            
685
    #[test]
686
    fn as_accessors_return_none_for_every_non_matching_variant() {
687
        for (i, ctx) in one_of_each().iter().enumerate() {
688
            assert_eq!(ctx.as_text_selection().is_some(), i == 0);
689
            assert_eq!(ctx.as_scrollbar_thumb().is_some(), i == 1);
690
            assert_eq!(ctx.as_node_drag().is_some(), i == 2);
691
            assert_eq!(ctx.as_window_move().is_some(), i == 3);
692
            assert_eq!(ctx.as_file_drop().is_some(), i == 5);
693
        }
694
    }
695

            
696
    #[test]
697
    fn as_mut_accessors_return_none_for_every_non_matching_variant() {
698
        for (i, ctx) in one_of_each().iter_mut().enumerate() {
699
            assert_eq!(ctx.as_text_selection_mut().is_some(), i == 0);
700
            assert_eq!(ctx.as_scrollbar_thumb_mut().is_some(), i == 1);
701
            assert_eq!(ctx.as_node_drag_mut().is_some(), i == 2);
702
            assert_eq!(ctx.as_file_drop_mut().is_some(), i == 5);
703
        }
704
    }
705

            
706
    #[test]
707
    fn as_text_selection_mut_writes_are_visible_through_shared_getter() {
708
        let mut ctx =
709
            DragContext::text_selection(dom(0), NodeId::new(1), LogicalPosition::zero(), 0);
710
        {
711
            let ts = ctx.as_text_selection_mut().unwrap();
712
        }
713
        let ts = ctx.as_text_selection().unwrap();
714
    }
715

            
716
    #[test]
717
    fn as_scrollbar_thumb_mut_writes_are_visible_through_shared_getter() {
718
        let mut ctx = vscroll(0.0, 100.0, 200.0, 100.0);
719
        ctx.as_scrollbar_thumb_mut().unwrap().start_scroll_offset = f32::NAN;
720
        assert!(ctx
721
            .as_scrollbar_thumb()
722
            .unwrap()
723
            .start_scroll_offset
724
            .is_nan());
725
    }
726

            
727
    #[test]
728
    fn as_node_drag_mut_writes_are_visible_through_shared_getter() {
729
        let mut ctx = DragContext::node_drag(
730
            dom(0),
731
            NodeId::ZERO,
732
            LogicalPosition::zero(),
733
            DragData::new(),
734
            0,
735
        );
736
        {
737
            let nd = ctx.as_node_drag_mut().unwrap();
738
            nd.drop_accepted = true;
739
            nd.drop_effect = DropEffect::Move;
740
            nd.current_drop_target = Some(dnid(0, 4)).into();
741
        }
742
        let nd = ctx.as_node_drag().unwrap();
743
        assert!(nd.drop_accepted);
744
        assert_eq!(nd.drop_effect, DropEffect::Move);
745
        assert_eq!(
746
            nd.current_drop_target
747
                .into_option()
748
                .unwrap()
749
                .node
750
                .into_crate_internal(),
751
            Some(NodeId::new(4))
752
        );
753
    }
754

            
755
    #[test]
756
    fn as_file_drop_mut_writes_are_visible_through_shared_getter() {
757
        let mut ctx = DragContext::file_drop(Vec::new(), LogicalPosition::zero(), 0);
758
        ctx.as_file_drop_mut().unwrap().drop_effect = DropEffect::Link;
759
        assert_eq!(ctx.as_file_drop().unwrap().drop_effect, DropEffect::Link);
760
    }
761

            
762
    // ============================================== update / position getters
763

            
764
    #[test]
765
    fn update_position_moves_current_for_every_variant_and_leaves_start_alone() {
766
        let new_pos = LogicalPosition::new(123.5, -456.25);
767
        for (i, mut ctx) in one_of_each().into_iter().enumerate() {
768
            let start_before = ctx.start_position();
769
            ctx.update_position(new_pos);
770
            assert_eq!(ctx.current_position(), new_pos, "variant {i} did not move");
771
            if i == 5 {
772
                // FileDrop has a single `position` field: start aliases current,
773
                // so updating the position also moves the reported start.
774
                assert_eq!(ctx.start_position(), new_pos);
775
            } else {
776
                assert_eq!(
777
                    ctx.start_position(),
778
                    start_before,
779
                    "variant {i} start moved"
780
                );
781
            }
782
        }
783
    }
784

            
785
    #[test]
786
    fn update_position_with_nan_and_inf_is_stored_verbatim() {
787
        for mut ctx in one_of_each() {
788
            ctx.update_position(LogicalPosition::new(f32::NAN, f32::INFINITY));
789
            let cur = ctx.current_position();
790
            assert!(cur.x.is_nan());
791
            assert_eq!(cur.y, f32::INFINITY);
792

            
793
            ctx.update_position(LogicalPosition::new(f32::MIN, f32::NEG_INFINITY));
794
            let cur = ctx.current_position();
795
            assert_eq!(cur.x.to_bits(), f32::MIN.to_bits());
796
            assert_eq!(cur.y, f32::NEG_INFINITY);
797
        }
798
    }
799

            
800
    #[test]
801
    fn update_position_is_idempotent_and_last_write_wins() {
802
        let mut ctx = vscroll(0.0, 100.0, 200.0, 100.0);
803
        for i in 0..1000u32 {
804
            ctx.update_position(LogicalPosition::new(i as f32, -(i as f32)));
805
        }
806
        assert_eq!(ctx.current_position(), LogicalPosition::new(999.0, -999.0));
807
        assert_eq!(ctx.start_position(), LogicalPosition::zero());
808
    }
809

            
810
    #[test]
811
    fn window_resize_position_getters_work_without_a_predicate() {
812
        let mut ctx = resize_ctx();
813
        assert_eq!(ctx.start_position(), LogicalPosition::new(1.0, 2.0));
814
        assert_eq!(ctx.current_position(), LogicalPosition::new(1.0, 2.0));
815
        ctx.update_position(LogicalPosition::new(-3.0, -4.0));
816
        assert_eq!(ctx.current_position(), LogicalPosition::new(-3.0, -4.0));
817
        assert_eq!(ctx.start_position(), LogicalPosition::new(1.0, 2.0));
818
        // No as_window_resize() accessor exists; the others must all say None.
819
        assert!(ctx.as_text_selection().is_none());
820
        assert!(ctx.as_window_move().is_none());
821
    }
822

            
823
    // ===================================== calculate_scrollbar_scroll_offset
824

            
825
    #[test]
826
    fn scroll_offset_is_none_for_non_scrollbar_drags() {
827
        for (i, ctx) in one_of_each().iter().enumerate() {
828
            if i == 1 {
829
                continue;
830
            }
831
            assert!(
832
                ctx.calculate_scrollbar_scroll_offset().is_none(),
833
                "variant {i} returned Some"
834
            );
835
        }
836
    }
837

            
838
    #[test]
839
    fn scroll_offset_basic_vertical_half_track() {
840
        // track=100, content=200, viewport=100 => range=100, thumb=50,
841
        // scrollable_track=50. A 25px drag is half the scrollable track =>
842
        // half the range = 50.
843
        let mut ctx = vscroll(0.0, 100.0, 200.0, 100.0);
844
        ctx.update_position(LogicalPosition::new(0.0, 25.0));
845
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(50.0));
846
    }
847

            
848
    #[test]
849
    fn scroll_offset_horizontal_uses_x_and_ignores_y() {
850
        let mut ctx = DragContext::scrollbar_thumb(
851
            dom(0),
852
            NodeId::new(1),
853
            ScrollbarAxis::Horizontal,
854
            LogicalPosition::zero(),
855
            0.0,
856
            100.0,
857
            200.0,
858
            100.0,
859
            0,
860
        );
861
        // Pure vertical movement must not scroll a horizontal scrollbar.
862
        ctx.update_position(LogicalPosition::new(0.0, 9999.0));
863
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(0.0));
864
        ctx.update_position(LogicalPosition::new(25.0, 9999.0));
865
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(50.0));
866
    }
867

            
868
    #[test]
869
    fn scroll_offset_clamps_to_range_on_huge_and_infinite_drags() {
870
        let mut ctx = vscroll(0.0, 100.0, 200.0, 100.0); // range = 100
871
        for (y, expect) in [
872
            (1.0e30f32, 100.0f32),
873
            (f32::MAX, 100.0),
874
            (f32::INFINITY, 100.0),
875
            (-1.0e30, 0.0),
876
            (f32::MIN, 0.0),
877
            (f32::NEG_INFINITY, 0.0),
878
        ] {
879
            ctx.update_position(LogicalPosition::new(0.0, y));
880
            assert_eq!(
881
                ctx.calculate_scrollbar_scroll_offset(),
882
                Some(expect),
883
                "y = {y}"
884
            );
885
        }
886
    }
887

            
888
    #[test]
889
    fn scroll_offset_result_always_within_range_for_finite_inputs() {
890
        let mut ctx = vscroll(30.0, 80.0, 500.0, 120.0);
891
        let range = 500.0 - 120.0;
892
        for y in [-1e9f32, -1.0, 0.0, 0.5, 1.0, 37.0, 1e9] {
893
            ctx.update_position(LogicalPosition::new(0.0, y));
894
            let off = ctx.calculate_scrollbar_scroll_offset().unwrap();
895
            assert!(
896
                (0.0..=range).contains(&off),
897
                "offset {off} escaped [0, {range}] for y = {y}"
898
            );
899
        }
900
    }
901

            
902
    #[test]
903
    fn scroll_offset_out_of_range_start_offset_is_clamped_back_in() {
904
        // Even with zero mouse movement, a bogus start offset must be clamped.
905
        let ctx = vscroll(9999.0, 100.0, 200.0, 100.0);
906
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(100.0));
907
        let ctx = vscroll(-9999.0, 100.0, 200.0, 100.0);
908
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(0.0));
909
    }
910

            
911
    #[test]
912
    fn scroll_offset_non_scrollable_content_returns_start_offset_unchanged() {
913
        // content <= viewport => nothing to scroll; the (possibly out-of-range)
914
        // start offset is returned verbatim, WITHOUT clamping.
915
        let mut ctx = vscroll(7.0, 100.0, 50.0, 100.0);
916
        ctx.update_position(LogicalPosition::new(0.0, 1000.0));
917
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(7.0));
918

            
919
        let ctx = vscroll(7.0, 100.0, 100.0, 100.0); // range == 0
920
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(7.0));
921

            
922
        let ctx = vscroll(7.0, 100.0, 0.0, 0.0); // all zero metrics
923
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(7.0));
924
    }
925

            
926
    #[test]
927
    fn scroll_offset_zero_or_negative_track_returns_start_offset() {
928
        for track in [0.0f32, -1.0, -1e30, f32::NEG_INFINITY] {
929
            let mut ctx = vscroll(7.0, track, 200.0, 100.0);
930
            ctx.update_position(LogicalPosition::new(0.0, 50.0));
931
            assert_eq!(
932
                ctx.calculate_scrollbar_scroll_offset(),
933
                Some(7.0),
934
                "track = {track}"
935
            );
936
        }
937
    }
938

            
939
    #[test]
940
    fn scroll_offset_negative_content_and_viewport_return_start_offset() {
941
        let mut ctx = vscroll(3.0, 100.0, -200.0, -100.0);
942
        ctx.update_position(LogicalPosition::new(0.0, 50.0));
943
        // range = -200 - (-100) = -100 <= 0 => early out.
944
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(3.0));
945
    }
946

            
947
    #[test]
948
    fn scroll_offset_nan_start_offset_propagates_nan_without_panicking() {
949
        let mut ctx = vscroll(f32::NAN, 100.0, 200.0, 100.0);
950
        ctx.update_position(LogicalPosition::new(0.0, 10.0));
951
        let off = ctx.calculate_scrollbar_scroll_offset().expect("Some");
952
        // NaN start offset is neither clamped nor rejected: it leaks through.
953
        assert!(off.is_nan());
954
    }
955

            
956
    #[test]
957
    fn scroll_offset_nan_track_length_propagates_nan_without_panicking() {
958
        let mut ctx = vscroll(0.0, f32::NAN, 200.0, 100.0);
959
        ctx.update_position(LogicalPosition::new(0.0, 10.0));
960
        let off = ctx.calculate_scrollbar_scroll_offset().expect("Some");
961
        // NaN track passes the `track_length_px <= 0.0` guard (NaN compares
962
        // false) and poisons the result. min/max of the clamp stay finite, so
963
        // no panic — just a NaN scroll offset handed to the caller.
964
        assert!(off.is_nan());
965
    }
966

            
967
    #[test]
968
    fn scroll_offset_nan_mouse_position_propagates_nan_without_panicking() {
969
        let mut ctx = vscroll(0.0, 100.0, 200.0, 100.0);
970
        ctx.update_position(LogicalPosition::new(0.0, f32::NAN));
971
        let off = ctx.calculate_scrollbar_scroll_offset().expect("Some");
972
        assert!(off.is_nan());
973
    }
974

            
975
    #[test]
976
    fn scroll_offset_infinite_content_yields_nan_on_zero_mouse_delta() {
977
        // range = inf, thumb = 0, ratio = 0 => scroll_delta = 0.0 * inf = NaN.
978
        // Not a panic (clamp's min/max are 0.0/inf), but the returned offset is
979
        // NaN even though the mouse never moved.
980
        let ctx = vscroll(0.0, 100.0, f32::INFINITY, 100.0);
981
        let off = ctx.calculate_scrollbar_scroll_offset().expect("Some");
982
        assert!(off.is_nan(), "expected the 0 * inf NaN, got {off}");
983
    }
984

            
985
    // A NaN `scrollable_range` (from a NaN, or inf-minus-inf, content/viewport
986
    // length) used to make `new_offset.clamp(0.0, scrollable_range)` PANIC inside
987
    // this getter (f32::clamp asserts min <= max, and every NaN comparison is
988
    // false), taking the app down on the next scrollbar drag. The guard now uses
989
    // `!(range > 0.0)`, so a NaN range falls back to the start offset.
990
    #[test]
991
    fn scroll_offset_nan_content_length_falls_back_without_panicking() {
992
        let mut ctx = vscroll(0.0, 100.0, f32::NAN, 100.0);
993
        ctx.update_position(LogicalPosition::new(0.0, 10.0));
994
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(0.0));
995
    }
996

            
997
    #[test]
998
    fn scroll_offset_nan_viewport_length_falls_back_without_panicking() {
999
        let mut ctx = vscroll(0.0, 100.0, 200.0, f32::NAN);
        ctx.update_position(LogicalPosition::new(0.0, 10.0));
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(0.0));
    }
    #[test]
    fn scroll_offset_infinite_content_and_viewport_falls_back_without_panicking() {
        // inf - inf = NaN scrollable_range => the guard falls back to start.
        let mut ctx = vscroll(0.0, 100.0, f32::INFINITY, f32::INFINITY);
        ctx.update_position(LogicalPosition::new(0.0, 10.0));
        assert_eq!(ctx.calculate_scrollbar_scroll_offset(), Some(0.0));
    }
    // ================================================ remap_node_ids / targets
    #[test]
    fn remap_text_selection_other_dom_is_a_no_op_and_succeeds() {
        let mut ctx =
            DragContext::text_selection(dom(0), NodeId::new(5), LogicalPosition::zero(), 0);
        assert!(ctx.remap_node_ids(dom(1), &nid_map(&[(5, 500)])));
        assert_eq!(
            ctx.as_text_selection().unwrap().anchor_ifc_node,
            NodeId::new(5)
        );
    }
    #[test]
    fn remap_text_selection_missing_anchor_cancels_the_drag() {
        let mut ctx =
            DragContext::text_selection(dom(0), NodeId::new(5), LogicalPosition::zero(), 0);
        assert!(!ctx.remap_node_ids(dom(0), &BTreeMap::new()));
        assert!(!ctx.remap_node_ids(dom(0), &nid_map(&[(6, 7)])));
        // The anchor is left untouched when the remap fails.
        assert_eq!(
            ctx.as_text_selection().unwrap().anchor_ifc_node,
            NodeId::new(5)
        );
    }
    #[test]
    fn remap_text_selection_follows_the_anchor_and_survives() {
        let mut ctx =
            DragContext::text_selection(dom(0), NodeId::new(5), LogicalPosition::zero(), 0);
        assert!(ctx.remap_node_ids(dom(0), &nid_map(&[(5, 50), (9, 90)])));
        let ts = ctx.as_text_selection().unwrap();
        assert_eq!(ts.anchor_ifc_node, NodeId::new(50));
        assert!(ctx.remap_node_ids(dom(0), &nid_map(&[(50, 51)])));
        let ts = ctx.as_text_selection().unwrap();
        assert_eq!(ts.anchor_ifc_node, NodeId::new(51));
    }
    #[test]
    fn remap_scrollbar_empty_map_cancels_the_drag() {
        let mut ctx = vscroll(0.0, 100.0, 200.0, 100.0); // node 1, dom 0
        assert!(!ctx.remap_node_ids(dom(0), &BTreeMap::new()));
        assert_eq!(
            ctx.as_scrollbar_thumb().unwrap().scroll_container_node,
            NodeId::new(1)
        );
    }
    #[test]
    fn remap_node_drag_missing_node_cancels_and_leaves_targets_alone() {
        let mut ctx = DragContext::node_drag(
            dom(0),
            NodeId::new(1),
            LogicalPosition::zero(),
            DragData::new(),
            0,
        );
        ctx.as_node_drag_mut().unwrap().current_drop_target = Some(dnid(0, 5)).into();
        // Map covers the drop target but NOT the dragged node => cancel.
        assert!(!ctx.remap_node_ids(dom(0), &nid_map(&[(5, 50)])));
        let nd = ctx.as_node_drag().unwrap();
        assert_eq!(nd.node_id, NodeId::new(1));
        assert_eq!(
            nd.current_drop_target
                .into_option()
                .unwrap()
                .node
                .into_crate_internal(),
            Some(NodeId::new(5)),
            "targets must not be half-remapped on a cancelled drag"
        );
    }
    #[test]
    fn remap_node_drag_clears_drop_targets_that_were_removed() {
        let mut ctx = DragContext::node_drag(
            dom(0),
            NodeId::new(1),
            LogicalPosition::zero(),
            DragData::new(),
            0,
        );
        {
            let nd = ctx.as_node_drag_mut().unwrap();
            nd.current_drop_target = Some(dnid(0, 5)).into();
            nd.previous_drop_target = Some(dnid(0, 6)).into();
        }
        // Only the dragged node survives; both targets are gone.
        assert!(ctx.remap_node_ids(dom(0), &nid_map(&[(1, 100)])));
        let nd = ctx.as_node_drag().unwrap();
        assert_eq!(nd.node_id, NodeId::new(100));
        assert!(nd.current_drop_target.into_option().is_none());
        assert!(nd.previous_drop_target.into_option().is_none());
    }
    #[test]
    fn remap_does_not_touch_drop_targets_belonging_to_another_dom() {
        let mut ctx = DragContext::node_drag(
            dom(0),
            NodeId::new(1),
            LogicalPosition::zero(),
            DragData::new(),
            0,
        );
        // Drop target lives in DOM 1 (a different DOM than the drag).
        ctx.as_node_drag_mut().unwrap().current_drop_target = Some(dnid(1, 5)).into();
        assert!(ctx.remap_node_ids(dom(0), &nid_map(&[(1, 100), (5, 500)])));
        let nd = ctx.as_node_drag().unwrap();
        assert_eq!(nd.node_id, NodeId::new(100));
        let dt = nd.current_drop_target.into_option().unwrap();
        assert_eq!(dt.dom, dom(1));
        assert_eq!(dt.node.into_crate_internal(), Some(NodeId::new(5)));
    }
    #[test]
    fn remap_drop_target_without_a_node_id_is_left_intact() {
        // A DomNodeId whose node encodes `None` must not be cleared or panic.
        let mut ctx = DragContext::node_drag(
            dom(0),
            NodeId::new(1),
            LogicalPosition::zero(),
            DragData::new(),
            0,
        );
        ctx.as_node_drag_mut().unwrap().current_drop_target = Some(dnid_no_node(0)).into();
        assert!(ctx.remap_node_ids(dom(0), &nid_map(&[(1, 1)])));
        let dt = ctx
            .as_node_drag()
            .unwrap()
            .current_drop_target
            .into_option()
            .expect("target must survive");
        assert_eq!(dt.dom, dom(0));
        assert_eq!(dt.node.into_crate_internal(), None);
    }
    #[test]
    fn remap_drop_target_directly_handles_none_and_foreign_doms() {
        // Exercise the private helper on its own.
        let mut none_target = OptionDomNodeId::None;
        DragContext::remap_drop_target(&mut none_target, dom(0), &nid_map(&[(1, 2)]));
        assert!(none_target.into_option().is_none());
        let mut foreign: OptionDomNodeId = Some(dnid(9, 1)).into();
        DragContext::remap_drop_target(&mut foreign, dom(0), &nid_map(&[(1, 2)]));
        let dt = foreign.into_option().unwrap();
        assert_eq!(dt.dom, dom(9));
        assert_eq!(dt.node.into_crate_internal(), Some(NodeId::new(1)));
        // Empty map on a matching DOM clears the target.
        let mut matching: OptionDomNodeId = Some(dnid(0, 1)).into();
        DragContext::remap_drop_target(&mut matching, dom(0), &BTreeMap::new());
        assert!(matching.into_option().is_none());
    }
    #[test]
    fn remap_file_drop_always_survives_and_clears_stale_targets() {
        let mut ctx = DragContext::file_drop(
            alloc::vec![AzString::from("/tmp/a")],
            LogicalPosition::zero(),
            0,
        );
        // No target: nothing to do, drag survives.
        assert!(ctx.remap_node_ids(dom(0), &BTreeMap::new()));
        assert!(ctx
            .as_file_drop()
            .unwrap()
            .drop_target
            .into_option()
            .is_none());
        // Target present and mapped => remapped.
        ctx.as_file_drop_mut().unwrap().drop_target = Some(dnid(0, 5)).into();
        assert!(ctx.remap_node_ids(dom(0), &nid_map(&[(5, 55)])));
        assert_eq!(
            ctx.as_file_drop()
                .unwrap()
                .drop_target
                .into_option()
                .unwrap()
                .node
                .into_crate_internal(),
            Some(NodeId::new(55))
        );
        // Target removed => cleared, but the file drop itself still survives.
        assert!(ctx.remap_node_ids(dom(0), &BTreeMap::new()));
        assert!(ctx
            .as_file_drop()
            .unwrap()
            .drop_target
            .into_option()
            .is_none());
        assert_eq!(ctx.as_file_drop().unwrap().files.len(), 1);
    }
    #[test]
    fn remap_window_drags_always_succeed() {
        let mut wm =
            DragContext::window_move(LogicalPosition::zero(), WindowPosition::Uninitialized, 0);
        assert!(wm.remap_node_ids(dom(0), &BTreeMap::new()));
        assert!(wm.remap_node_ids(dom(usize::MAX), &nid_map(&[(1, 2)])));
        let mut wr = resize_ctx();
        assert!(wr.remap_node_ids(dom(0), &BTreeMap::new()));
        assert_eq!(wr.current_position(), LogicalPosition::new(1.0, 2.0));
    }
    #[test]
    fn remap_with_a_hundred_thousand_entries_does_not_hang() {
        let mut m = BTreeMap::new();
        for i in 0..100_000usize {
            m.insert(NodeId::new(i), NodeId::new(i + 1));
        }
        let mut ctx = vscroll(0.0, 100.0, 200.0, 100.0); // node 1
        assert!(ctx.remap_node_ids(dom(0), &m));
        assert_eq!(
            ctx.as_scrollbar_thumb().unwrap().scroll_container_node,
            NodeId::new(2)
        );
    }
    #[test]
    fn remap_identity_map_is_a_fixed_point() {
        let mut ctx = DragContext::node_drag(
            dom(0),
            NodeId::new(1),
            LogicalPosition::new(1.0, 2.0),
            DragData::new(),
            0,
        );
        {
            let nd = ctx.as_node_drag_mut().unwrap();
            nd.current_drop_target = Some(dnid(0, 5)).into();
            nd.previous_drop_target = Some(dnid(0, 5)).into();
        }
        let before = ctx.clone();
        let m = nid_map(&[(1, 1), (5, 5)]);
        assert!(ctx.remap_node_ids(dom(0), &m));
        assert!(ctx.remap_node_ids(dom(0), &m)); // twice, for good measure
        assert_eq!(ctx, before);
    }
    // ==================================================== DragDelta
    #[test]
    fn drag_delta_new_stores_extremes_verbatim() {
        for (dx, dy) in [
            (0.0f32, 0.0f32),
            (f32::MAX, f32::MIN),
            (f32::INFINITY, f32::NEG_INFINITY),
            (f32::MIN_POSITIVE, -f32::MIN_POSITIVE),
        ] {
            let d = DragDelta::new(dx, dy);
            assert_eq!(d.dx.to_bits(), dx.to_bits());
            assert_eq!(d.dy.to_bits(), dy.to_bits());
        }
    }
    #[test]
    fn drag_delta_zero_is_the_neutral_default() {
        let z = DragDelta::zero();
        assert_eq!(z.dx, 0.0);
        assert_eq!(z.dy, 0.0);
        assert!(!z.dx.is_sign_negative(), "zero() must be +0.0, not -0.0");
        assert_eq!(z, DragDelta::default());
        assert_eq!(z, DragDelta::new(0.0, 0.0));
        // IEEE-754: -0.0 == +0.0, so a negative zero delta still equals zero().
        assert_eq!(DragDelta::new(-0.0, -0.0), z);
        // ...but the sign bit is preserved in the stored field.
        assert!(DragDelta::new(-0.0, -0.0).dx.is_sign_negative());
    }
    #[test]
    fn drag_delta_nan_is_not_equal_to_itself() {
        // Derived PartialEq on f32 => NaN != NaN. Callers must not use
        // equality to detect "no movement" on a NaN delta.
        let n = DragDelta::new(f32::NAN, f32::NAN);
        assert_ne!(n, DragDelta::new(f32::NAN, f32::NAN));
        assert_ne!(n, DragDelta::zero());
        assert!(n.dx.is_nan() && n.dy.is_nan());
        // PartialOrd is also useless on NaN: no ordering at all.
        assert!(n.partial_cmp(&DragDelta::zero()).is_none());
    }
}