1
//! Manager types responsible for stateful input and UI concerns.
2
//!
3
//! This module collects managers for accessibility, clipboard, drag-and-drop,
4
//! focus/cursor, gestures, hover, scroll state, selection, text editing,
5
//! text input, undo/redo, and virtual views. These managers are consumed
6
//! primarily by `layout/src/window.rs` and `layout/src/event_determination.rs`.
7
//!
8
//! # `NodeId` staleness — read this before adding a manager
9
//!
10
//! A `NodeId` is an INDEX into the current DOM arena, not a stable identity.
11
//! Every DOM rebuild (virtual-view re-invocation, window resize, route switch,
12
//! any `regenerate_layout`) renumbers them. Reconciliation
13
//! (`azul_core::diff::reconcile_dom`) tells us how: `node_moves` maps every
14
//! MATCHED old `NodeId` to its new one. An old `NodeId` that is absent from
15
//! that map was UNMOUNTED.
16
//!
17
//! Any manager that keys state by `NodeId` and does not participate in that
18
//! remap ends up pointing at a *live but wrong* node — deleting a preceding
19
//! sibling shifts every following index down by one, so the state silently
20
//! re-attaches to a different element (no dangling id, no panic, no error).
21
//! Unmapped keys also leak forever.
22
//!
23
//! The fix is structural: every node-keyed manager implements
24
//! [`NodeIdRemap`], and [`crate::window::LayoutWindow::remap_node_ids`]
25
//! (exhaustively destructured, so a NEW FIELD IS A COMPILE ERROR until it is
26
//! classified) drives all of them from one place.
27

            
28
pub mod a11y;
29
/// Platform-neutral a11y element list for the shells `accesskit` does not
30
/// cover (iOS / Android). Gated with the same feature as `a11y` itself.
31
#[cfg(feature = "a11y")]
32
pub mod a11y_snapshot;
33
pub mod biometric;
34
pub mod changeset;
35
pub mod clipboard;
36
pub mod device_events;
37
pub mod drag_drop;
38
pub mod eyedropper;
39
pub mod file_drop;
40
pub mod focus_cursor;
41
pub mod gamepad;
42
pub mod geolocation;
43
pub mod gesture;
44
pub mod gpu_state;
45
pub mod hid;
46
pub mod hover;
47
pub mod keyring;
48
pub mod media_keys;
49
/// Media playback state machine (11c): the transport + the six media events.
50
pub mod media_player;
51
pub mod permission;
52
pub mod scroll_into_view;
53
pub mod scroll_registration;
54
pub mod scroll_state;
55
pub mod selection;
56
pub mod sensors;
57
pub mod text_edit;
58
pub mod text_input;
59
pub mod undo_redo;
60
pub mod virtual_view;
61
/// Cross-thread "raise this window" requests (9h-i-a-ii).
62
pub mod window_activation;
63

            
64
use alloc::collections::BTreeMap;
65

            
66
use azul_core::{
67
    dom::{DomId, DomNodeId, NodeId},
68
    styled_dom::NodeHierarchyItemId,
69
};
70

            
71
/// The result of a DOM reconciliation, from the point of view of anyone holding
72
/// `NodeId`-keyed state for a single DOM.
73
///
74
/// Built from `azul_core::diff::DiffResult::node_moves`, which contains an entry
75
/// for EVERY matched node (including nodes that kept their index). The absence
76
/// of an old `NodeId` from the map therefore has a precise meaning: that node was
77
/// **unmounted**. This is what makes GC possible without a second "alive" set.
78
///
79
/// The contract for consumers is a single rule:
80
///
81
/// * [`NodeIdMap::resolve`] returns `Some(new_id)` — the node survived, rewrite the key.
82
/// * [`NodeIdMap::resolve`] returns `None` — the node is GONE, **drop the state**.
83
///
84
/// Never "keep it, just in case": a kept key is a key that now denotes a
85
/// different node.
86
#[derive(Debug, Clone, Default, PartialEq, Eq)]
87
pub struct NodeIdMap {
88
    moves: BTreeMap<NodeId, NodeId>,
89
}
90

            
91
impl NodeIdMap {
92
    /// Build from reconciliation output (`DiffResult::node_moves`).
93
    #[must_use]
94
451
    pub fn from_node_moves(node_moves: &[azul_core::diff::NodeMove]) -> Self {
95
        Self {
96
451
            moves: node_moves
97
451
                .iter()
98
4619
                .map(|m| (m.old_node_id, m.new_node_id))
99
451
                .collect(),
100
        }
101
451
    }
102

            
103
    /// Build from raw `(old, new)` pairs — used by tests and by callers that
104
    /// already computed a migration map.
105
    #[must_use]
106
118
    pub fn from_pairs<I: IntoIterator<Item = (NodeId, NodeId)>>(pairs: I) -> Self {
107
118
        Self {
108
118
            moves: pairs.into_iter().collect(),
109
118
        }
110
118
    }
111

            
112
    /// `Some(new_id)` if the node survived the rebuild, `None` if it was unmounted.
113
    #[must_use]
114
2902
    pub fn resolve(&self, old: NodeId) -> Option<NodeId> {
115
2902
        self.moves.get(&old).copied()
116
2902
    }
117

            
118
    /// `true` if `old` no longer exists in the new DOM.
119
    #[must_use]
120
2068
    pub fn is_unmounted(&self, old: NodeId) -> bool {
121
2068
        !self.moves.contains_key(&old)
122
2068
    }
123

            
124
    /// Resolve a full `DomNodeId`. Ids belonging to a *different* DOM are passed
125
    /// through untouched (this reconciliation says nothing about them).
126
    #[must_use]
127
118
    pub fn resolve_dom_node_id(&self, dom: DomId, id: DomNodeId) -> Option<DomNodeId> {
128
118
        if id.dom != dom {
129
12
            return Some(id);
130
106
        }
131
106
        let old = id.node.into_crate_internal()?;
132
103
        let new = self.resolve(old)?;
133
84
        Some(DomNodeId {
134
84
            dom,
135
84
            node: NodeHierarchyItemId::from_crate_internal(Some(new)),
136
84
        })
137
118
    }
138

            
139
    /// The raw old→new map, for `azul_core` APIs that take a `BTreeMap`
140
    /// (`DragContext::remap_node_ids`, `MultiCursorState::remap_node_ids`).
141
    #[must_use]
142
529
    pub const fn as_btree_map(&self) -> &BTreeMap<NodeId, NodeId> {
143
529
        &self.moves
144
529
    }
145

            
146
    /// No matched nodes at all (everything was unmounted / the DOM is brand new).
147
    #[must_use]
148
10
    pub fn is_empty(&self) -> bool {
149
10
        self.moves.is_empty()
150
10
    }
151
}
152

            
153
/// Implemented by EVERY manager (or cache) that keys state by `NodeId`.
154
///
155
/// One method on purpose: remapping and GC are the same pass, so it is
156
/// impossible to do one and forget the other. Implementors MUST, for state
157
/// belonging to `dom`:
158
///
159
/// 1. rewrite each key/field `old` to `map.resolve(old)`, and
160
/// 2. **drop** the state whenever `resolve` returns `None` (unmounted node).
161
///
162
/// State belonging to any *other* `DomId` must be left alone.
163
pub trait NodeIdRemap {
164
    /// Rewrite all `NodeId`s for `dom` and drop state for unmounted nodes.
165
    fn remap_node_ids(&mut self, dom: DomId, map: &NodeIdMap);
166
}
167

            
168
/// Remap the keys of a `BTreeMap<NodeId, V>` in place, dropping unmounted nodes.
169
62
pub(crate) fn remap_keys<V>(map: &mut BTreeMap<NodeId, V>, node_map: &NodeIdMap) {
170
62
    let old = core::mem::take(map);
171
439
    for (old_id, v) in old {
172
377
        if let Some(new_id) = node_map.resolve(old_id) {
173
367
            map.insert(new_id, v);
174
367
        }
175
    }
176
62
}
177

            
178
/// Remap the keys of a `BTreeMap<(DomId, NodeId), V>` in place: entries for
179
/// `dom` are rewritten (or dropped if unmounted), entries for other DOMs are
180
/// left untouched.
181
2691
pub(crate) fn remap_dom_keys<V>(
182
2691
    map: &mut BTreeMap<(DomId, NodeId), V>,
183
2691
    dom: DomId,
184
2691
    node_map: &NodeIdMap,
185
2691
) {
186
2691
    let old = core::mem::take(map);
187
3634
    for ((d, old_id), v) in old {
188
943
        if d != dom {
189
851
            map.insert((d, old_id), v);
190
922
        } else if let Some(new_id) = node_map.resolve(old_id) {
191
84
            map.insert((d, new_id), v);
192
84
        }
193
    }
194
2691
}
195

            
196
// ============================================================================
197
// THE PRECEDING-SIBLING TEST
198
// ============================================================================
199
//
200
// These tests encode the failure mode that motivated `NodeIdRemap`. They do NOT
201
// assert "no panic" — an unremapped manager never panics, that is exactly what
202
// made this bug survive. They assert LOGICAL IDENTITY: after the rebuild, every
203
// manager's state must still describe the SAME ELEMENT it described before.
204
//
205
// Scenario (one DOM, four nodes):
206
//
207
//     before:  0=root  1=A   2=B   3=C
208
//     delete A
209
//     after:   0=root        1=B   2=C          map = {0→0, 2→1, 3→2}
210
//
211
// State is seeded on B(2) and C(3) with DISTINGUISHABLE payloads, and on the
212
// doomed A(1). A manager that skips the remap keeps C's state at key 3 and
213
// leaves B's state at key 2 — but index 2 now denotes C. So the state is not
214
// dangling, it is MISATTACHED: "give me C's state" silently answers with B's.
215
// Asserting `state_at(2) == C_payload` is what catches that; a null/panic check
216
// does not.
217
#[cfg(all(test, feature = "std"))]
218
mod preceding_sibling_remap_tests {
219
    use alloc::collections::BTreeMap;
220

            
221
    use azul_core::{
222
        dom::{DomId, DomNodeId, NodeId},
223
        drag::{DragContext, DragData},
224
        geom::LogicalPosition,
225
        hit_test::{FullHitTest, HitTest, HitTestItem},
226
        selection::{CursorAffinity, GraphemeClusterId, MultiCursorState, TextCursor},
227
        styled_dom::NodeHierarchyItemId,
228
        task::{Instant, SystemTick},
229
    };
230

            
231
    use super::{
232
        changeset::{TextChangeset, TextOpInsertText, TextOperation},
233
        focus_cursor::FocusManager,
234
        gesture::GestureAndDragManager,
235
        gpu_state::GpuStateManager,
236
        hover::{HoverManager, InputPointId},
237
        scroll_state::ScrollManager,
238
        text_edit::TextEditManager,
239
        text_input::{TextInputManager, TextInputSource},
240
        undo_redo::{NodeStateSnapshot, UndoRedoManager},
241
        virtual_view::VirtualViewManager,
242
        NodeIdMap, NodeIdRemap,
243
    };
244

            
245
    const ROOT: DomId = DomId { inner: 0 };
246
    /// The node that gets deleted.
247
    const A: NodeId = NodeId::new(1);
248
    /// Surviving sibling, index 2 → 1.
249
    const B_OLD: NodeId = NodeId::new(2);
250
    const B_NEW: NodeId = NodeId::new(1);
251
    /// Surviving sibling, index 3 → 2.
252
    const C_OLD: NodeId = NodeId::new(3);
253
    const C_NEW: NodeId = NodeId::new(2);
254

            
255
    /// Exactly what `reconcile_dom` produces when the preceding sibling A is
256
    /// deleted: every MATCHED node, with A absent (= unmounted).
257
16
    fn delete_a() -> NodeIdMap {
258
16
        NodeIdMap::from_pairs([
259
16
            (NodeId::new(0), NodeId::new(0)),
260
16
            (B_OLD, B_NEW),
261
16
            (C_OLD, C_NEW),
262
16
        ])
263
16
    }
264

            
265
10
    fn now() -> Instant {
266
10
        Instant::Tick(SystemTick { tick_counter: 0 })
267
10
    }
268

            
269
9
    fn dom_node(node: NodeId) -> DomNodeId {
270
9
        DomNodeId {
271
9
            dom: ROOT,
272
9
            node: NodeHierarchyItemId::from_crate_internal(Some(node)),
273
9
        }
274
9
    }
275

            
276
    // ---------------------------------------------------------------- scroll
277

            
278
    #[test]
279
1
    fn scroll_offsets_follow_their_node_across_a_preceding_sibling_delete() {
280
1
        let mut m = ScrollManager::new();
281
        // Distinguishable payloads: y = 10 for A, 20 for B, 30 for C.
282
1
        m.set_scroll_position_unclamped(ROOT, A, LogicalPosition::new(0.0, 10.0), now());
283
1
        m.set_scroll_position_unclamped(ROOT, B_OLD, LogicalPosition::new(0.0, 20.0), now());
284
1
        m.set_scroll_position_unclamped(ROOT, C_OLD, LogicalPosition::new(0.0, 30.0), now());
285

            
286
1
        m.remap_node_ids(ROOT, &delete_a());
287

            
288
        // C is now node 2 and MUST still have C's offset (30) — not B's (20),
289
        // which is what an unremapped manager would answer here.
290
1
        assert_eq!(
291
1
            m.get_scroll_state(ROOT, C_NEW).map(|s| s.current_offset.y),
292
            Some(30.0),
293
            "C's scroll offset must follow C to its new NodeId"
294
        );
295
1
        assert_eq!(
296
1
            m.get_scroll_state(ROOT, B_NEW).map(|s| s.current_offset.y),
297
            Some(20.0),
298
            "B's scroll offset must follow B to its new NodeId"
299
        );
300
        // GC: the deleted node's state must not linger. NodeId(3) no longer exists.
301
1
        assert!(
302
1
            m.get_scroll_state(ROOT, NodeId::new(3)).is_none(),
303
            "no state may remain at a NodeId that no longer exists"
304
        );
305
1
        assert_eq!(
306
1
            m.get_scroll_states_for_dom(ROOT).len(),
307
            2,
308
            "A's state must be GC'd"
309
        );
310
1
    }
311

            
312
    // ------------------------------------------------------------- undo/redo
313

            
314
3
    fn undo_op(
315
3
        changeset_id: usize,
316
3
        node: NodeId,
317
3
        text: &str,
318
3
    ) -> super::undo_redo::UndoableOperation {
319
3
        super::undo_redo::UndoableOperation {
320
3
            changeset: TextChangeset {
321
3
                id: changeset_id,
322
3
                target: dom_node(node),
323
3
                operation: TextOperation::InsertText(TextOpInsertText {
324
3
                    text: text.into(),
325
3
                    position: azul_core::window::CursorPosition::Uninitialized,
326
3
                    new_cursor: azul_core::window::CursorPosition::Uninitialized,
327
3
                }),
328
3
                timestamp: now(),
329
3
            },
330
3
            pre_state: NodeStateSnapshot {
331
3
                node_id: node,
332
3
                text_content: text.into(),
333
3
                cursor_position: None.into(),
334
3
                selection_range: None.into(),
335
3
                timestamp: now(),
336
3
            },
337
3
            seat_id: 0,
338
3
        }
339
3
    }
340

            
341
    #[test]
342
1
    fn undo_history_stays_attached_to_the_same_element() {
343
1
        let mut m = UndoRedoManager::new();
344
1
        let a = undo_op(1, A, "typed-into-A");
345
1
        let b = undo_op(2, B_OLD, "typed-into-B");
346
1
        let c = undo_op(3, C_OLD, "typed-into-C");
347
1
        m.record_operation(a.changeset.clone(), a.pre_state.clone());
348
1
        m.record_operation(b.changeset.clone(), b.pre_state.clone());
349
1
        m.record_operation(c.changeset.clone(), c.pre_state.clone());
350

            
351
1
        m.remap_node_ids(ROOT, &delete_a());
352

            
353
        // THE bug: undoing "on C" must revert C's edit, not B's.
354
1
        let undo_on_c = m.peek_undo(C_NEW).expect("C must still have undo history");
355
1
        assert_eq!(
356
1
            undo_on_c.pre_state.text_content.as_str(),
357
            "typed-into-C",
358
            "undo on C must revert C's edit — an unremapped Vec re-attaches B's history here"
359
        );
360
1
        let undo_on_b = m.peek_undo(B_NEW).expect("B must still have undo history");
361
1
        assert_eq!(undo_on_b.pre_state.text_content.as_str(), "typed-into-B");
362

            
363
        // The embedded NodeIds must be rewritten too, or the *replay* targets the wrong node.
364
1
        assert_eq!(
365
1
            undo_on_c.changeset.target.node.into_crate_internal(),
366
            Some(C_NEW)
367
        );
368
1
        assert_eq!(undo_on_c.pre_state.node_id, C_NEW);
369

            
370
        // GC: A is gone, its history must be gone.
371
1
        assert_eq!(
372
1
            m.node_stacks.len(),
373
            2,
374
            "the deleted node's undo stack must be GC'd"
375
        );
376
1
        assert!(
377
1
            !m.can_undo(NodeId::new(3)),
378
            "no history at a NodeId that no longer exists"
379
        );
380
1
    }
381

            
382
    // ----------------------------------------------------------- virtual view
383

            
384
    #[test]
385
1
    fn virtual_view_nested_doms_stay_with_their_host_node() {
386
1
        let mut m = VirtualViewManager::new();
387
1
        let dom_a = m.get_or_create_nested_dom_id(ROOT, A);
388
1
        let dom_b = m.get_or_create_nested_dom_id(ROOT, B_OLD);
389
1
        let dom_c = m.get_or_create_nested_dom_id(ROOT, C_OLD);
390
1
        assert_ne!(dom_b, dom_c);
391

            
392
1
        m.remap_node_ids(ROOT, &delete_a());
393

            
394
1
        assert_eq!(
395
1
            m.get_nested_dom_id(ROOT, C_NEW),
396
1
            Some(dom_c),
397
            "C's nested DOM must follow C — otherwise C renders B's virtual view"
398
        );
399
1
        assert_eq!(m.get_nested_dom_id(ROOT, B_NEW), Some(dom_b));
400
1
        assert_eq!(m.debug_counts(), 2, "the deleted view's state must be GC'd");
401
2
        assert!(!m.all_view_keys().iter().any(|(_, n)| *n == C_OLD));
402
1
        assert_ne!(m.get_nested_dom_id(ROOT, B_NEW), Some(dom_a));
403
1
    }
404

            
405
    // -------------------------------------------------------------- gpu state
406

            
407
    #[test]
408
1
    fn gpu_transform_keys_stay_with_their_node() {
409
        use azul_core::resources::{OpacityKey, TransformKey};
410
1
        let mut m = GpuStateManager::default();
411
1
        {
412
1
            let cache = m.get_or_create_cache(ROOT);
413
1
            cache.opacity_keys.insert(A, OpacityKey::unique());
414
1
            cache.current_opacity_values.insert(A, 0.1);
415
1
            cache.current_opacity_values.insert(B_OLD, 0.2);
416
1
            cache.current_opacity_values.insert(C_OLD, 0.3);
417
1
            cache
418
1
                .css_transform_keys
419
1
                .insert(C_OLD, TransformKey::unique());
420
1
        }
421
1
        let c_key = m.get_cache(ROOT).unwrap().css_transform_keys[&C_OLD];
422

            
423
1
        m.remap_node_ids(ROOT, &delete_a());
424

            
425
1
        let cache = m.get_cache(ROOT).unwrap();
426
1
        assert_eq!(
427
1
            cache.current_opacity_values.get(&C_NEW).copied(),
428
            Some(0.3),
429
            "C's opacity must follow C, not be inherited from B"
430
        );
431
1
        assert_eq!(cache.current_opacity_values.get(&B_NEW).copied(), Some(0.2));
432
1
        assert_eq!(
433
1
            cache.css_transform_keys.get(&C_NEW).copied(),
434
1
            Some(c_key),
435
            "C's GPU transform key must follow C"
436
        );
437
1
        assert!(
438
1
            cache.opacity_keys.is_empty(),
439
            "the deleted node's GPU keys must be GC'd"
440
        );
441
1
        assert_eq!(cache.current_opacity_values.len(), 2);
442
1
    }
443

            
444
    // ------------------------------------------------------------------ focus
445

            
446
    #[test]
447
1
    fn focus_follows_its_node_and_is_cleared_when_the_node_dies() {
448
1
        let mut m = FocusManager::new();
449
1
        m.set_focused_node(Some(dom_node(C_OLD)));
450
1
        m.remap_node_ids(ROOT, &delete_a());
451
1
        assert_eq!(
452
1
            m.get_focused_node()
453
1
                .and_then(|f| f.node.into_crate_internal()),
454
            Some(C_NEW),
455
            "focus must follow the focused element, not stay on a recycled index"
456
        );
457

            
458
1
        let mut m = FocusManager::new();
459
1
        m.set_focused_node(Some(dom_node(A)));
460
1
        m.remap_node_ids(ROOT, &delete_a());
461
1
        assert!(
462
1
            m.get_focused_node().is_none(),
463
            "focus on an unmounted node must be cleared, never retargeted"
464
        );
465
1
    }
466

            
467
    // -------------------------------------------------------------- text edit
468

            
469
    #[test]
470
1
    fn a_live_selection_stays_on_the_edited_element() {
471
1
        let cursor = TextCursor {
472
1
            cluster_id: GraphemeClusterId {
473
1
                source_run: 0,
474
1
                start_byte_in_run: 0,
475
1
            },
476
1
            affinity: CursorAffinity::Leading,
477
1
        };
478
1
        let mut m = TextEditManager::new();
479
1
        m.multi_cursor = Some(MultiCursorState::new_with_cursor(
480
1
            cursor,
481
1
            dom_node(C_OLD),
482
1
            0,
483
1
        ));
484

            
485
1
        m.remap_node_ids(ROOT, &delete_a());
486

            
487
1
        let mc = m
488
1
            .multi_cursor
489
1
            .as_ref()
490
1
            .expect("the editing session survives");
491
1
        assert_eq!(
492
1
            mc.node_id.node.into_crate_internal(),
493
            Some(C_NEW),
494
            "the caret must stay in the element the user is editing"
495
        );
496
1
        assert_eq!(
497
1
            mc.selections.len(),
498
            1,
499
            "surviving node keeps its selections"
500
        );
501

            
502
        // Editing a node that gets deleted ends the session (no retarget).
503
1
        let mut m = TextEditManager::new();
504
1
        m.multi_cursor = Some(MultiCursorState::new_with_cursor(cursor, dom_node(A), 0));
505
1
        m.remap_node_ids(ROOT, &delete_a());
506
1
        assert!(
507
1
            m.multi_cursor.is_none(),
508
            "editing an unmounted node must end the session"
509
        );
510
1
    }
511

            
512
    // ----------------------------------------------------------------- drag
513

            
514
2
    fn node_drag(node: NodeId) -> DragContext {
515
2
        DragContext::node_drag(ROOT, node, LogicalPosition::zero(), DragData::default(), 1)
516
2
    }
517

            
518
    #[test]
519
1
    fn a_live_drag_keeps_dragging_the_same_element() {
520
1
        let mut m = GestureAndDragManager::new();
521
1
        m.active_drag = Some(node_drag(C_OLD));
522

            
523
1
        m.remap_node_ids(ROOT, &delete_a());
524

            
525
1
        assert!(
526
1
            m.is_node_dragging(ROOT, C_NEW),
527
            "the dragged element must still be the dragged element after the rebuild"
528
        );
529
1
        assert!(
530
1
            !m.is_node_dragging(ROOT, B_NEW),
531
            "the drag must NOT jump onto the sibling that inherited the old index"
532
        );
533

            
534
        // Dragging a node that gets deleted cancels the drag.
535
1
        let mut m = GestureAndDragManager::new();
536
1
        m.active_drag = Some(node_drag(A));
537
1
        m.remap_node_ids(ROOT, &delete_a());
538
1
        assert!(
539
1
            m.get_drag_context().is_none(),
540
            "a drag whose source vanished is cancelled"
541
        );
542
1
    }
543

            
544
    // ----------------------------------------------------------- text input
545

            
546
    #[test]
547
1
    fn a_pending_text_edit_is_not_applied_to_the_wrong_node() {
548
1
        let mut m = TextInputManager::new();
549
1
        m.record_input(
550
1
            dom_node(C_OLD),
551
1
            "x".into(),
552
1
            String::new(),
553
1
            TextInputSource::Keyboard,
554
        );
555
1
        m.remap_node_ids(ROOT, &delete_a());
556
1
        assert_eq!(
557
1
            m.get_pending_changeset()
558
1
                .and_then(|p| p.node.node.into_crate_internal()),
559
            Some(C_NEW),
560
            "the recorded edit must apply to the node it was recorded on"
561
        );
562

            
563
1
        let mut m = TextInputManager::new();
564
1
        m.record_input(
565
1
            dom_node(A),
566
1
            "x".into(),
567
1
            String::new(),
568
1
            TextInputSource::Keyboard,
569
        );
570
1
        m.remap_node_ids(ROOT, &delete_a());
571
1
        assert!(
572
1
            m.get_pending_changeset().is_none(),
573
            "an edit recorded on an unmounted node must be dropped, not applied elsewhere"
574
        );
575
1
    }
576

            
577
    // ---------------------------------------------------------------- hover
578

            
579
    #[test]
580
1
    fn hover_history_hits_follow_their_nodes() {
581
3
        fn hit(depth: u32) -> HitTestItem {
582
3
            HitTestItem {
583
3
                point_in_viewport: LogicalPosition::zero(),
584
3
                point_relative_to_item: Default::default(),
585
3
                is_focusable: false,
586
3
                is_virtual_view_hit: None,
587
3
                hit_depth: depth,
588
3
            }
589
3
        }
590
1
        let mut ht = HitTest::empty();
591
1
        ht.regular_hit_test_nodes.insert(A, hit(1));
592
1
        ht.regular_hit_test_nodes.insert(B_OLD, hit(2));
593
1
        ht.regular_hit_test_nodes.insert(C_OLD, hit(3));
594
1
        let mut full = FullHitTest::empty(None);
595
1
        full.hovered_nodes.insert(ROOT, ht);
596

            
597
1
        let mut m = HoverManager::new();
598
1
        m.push_hit_test(InputPointId::Mouse, full);
599

            
600
1
        m.remap_node_ids(ROOT, &delete_a());
601

            
602
1
        let nodes = &m.get_current(&InputPointId::Mouse).unwrap().hovered_nodes[&ROOT]
603
1
            .regular_hit_test_nodes;
604
1
        assert_eq!(
605
1
            nodes.get(&C_NEW).map(|h| h.hit_depth),
606
            Some(3),
607
            "C's hit must follow C (an unremapped history hands B's hit back for C)"
608
        );
609
1
        assert_eq!(nodes.get(&B_NEW).map(|h| h.hit_depth), Some(2));
610
1
        assert_eq!(nodes.len(), 2, "the deleted node's hit must be GC'd");
611
1
    }
612

            
613
    // ------------------------------------------------------ cross-DOM safety
614

            
615
    #[test]
616
1
    fn state_belonging_to_another_dom_is_never_touched() {
617
1
        let other = DomId { inner: 7 };
618
1
        let mut m = ScrollManager::new();
619
1
        m.set_scroll_position_unclamped(other, C_OLD, LogicalPosition::new(0.0, 99.0), now());
620
1
        m.remap_node_ids(ROOT, &delete_a());
621
1
        assert_eq!(
622
1
            m.get_scroll_state(other, C_OLD).map(|s| s.current_offset.y),
623
            Some(99.0),
624
            "a reconciliation of DOM 0 says nothing about DOM 7"
625
        );
626

            
627
1
        let mut vv = VirtualViewManager::new();
628
1
        let nested = vv.get_or_create_nested_dom_id(other, C_OLD);
629
1
        vv.remap_node_ids(ROOT, &delete_a());
630
1
        assert_eq!(vv.get_nested_dom_id(other, C_OLD), Some(nested));
631
1
    }
632

            
633
    /// The map itself is the GC oracle: `node_moves` lists EVERY matched node, so
634
    /// an id missing from it is unmounted (not merely "unmoved").
635
    #[test]
636
1
    fn node_id_map_semantics() {
637
1
        let map = delete_a();
638
1
        assert_eq!(map.resolve(NodeId::new(0)), Some(NodeId::new(0)));
639
1
        assert_eq!(map.resolve(C_OLD), Some(C_NEW));
640
1
        assert!(map.is_unmounted(A));
641
1
        assert!(map.resolve(A).is_none());
642
1
        let _unused: &BTreeMap<NodeId, NodeId> = map.as_btree_map();
643
1
    }
644
}
645

            
646
// ============================================================================
647
// AUTOTEST: adversarial tests for `NodeIdMap`, `remap_keys`, `remap_dom_keys`
648
// ============================================================================
649
#[cfg(test)]
650
mod autotest_generated {
651
    use azul_core::diff::NodeMove;
652

            
653
    use super::*;
654

            
655
    const DOM0: DomId = DomId { inner: 0 };
656
    const DOM1: DomId = DomId { inner: 1 };
657
    /// A `DomId` at the top of the `usize` range — must be handled like any other.
658
    const DOM_MAX: DomId = DomId { inner: usize::MAX };
659

            
660
    fn nid(i: usize) -> NodeId {
661
        NodeId::new(i)
662
    }
663

            
664
    fn mv(old: usize, new: usize) -> NodeMove {
665
        NodeMove {
666
            old_node_id: nid(old),
667
            new_node_id: nid(new),
668
        }
669
    }
670

            
671
    /// `NodeHierarchyItemId` uses a 1-based encoding, so the largest node index
672
    /// that can round-trip through a `DomNodeId` is `usize::MAX - 1`
673
    /// (`from_crate_internal` computes `inner + 1`). Anything above that is not
674
    /// representable and is deliberately not exercised through `DomNodeId`.
675
    const MAX_ENCODABLE: usize = usize::MAX - 1;
676

            
677
    fn dom_node_at(dom: DomId, node: NodeId) -> DomNodeId {
678
        DomNodeId {
679
            dom,
680
            node: NodeHierarchyItemId::from_crate_internal(Some(node)),
681
        }
682
    }
683

            
684
    // ------------------------------------------------------ constructors
685

            
686
    #[test]
687
    fn from_node_moves_on_an_empty_slice_yields_an_empty_map() {
688
        let map = NodeIdMap::from_node_moves(&[]);
689
        assert!(map.is_empty());
690
        assert!(map.as_btree_map().is_empty());
691
        assert_eq!(map, NodeIdMap::default());
692
    }
693

            
694
    #[test]
695
    fn from_node_moves_agrees_with_from_pairs_on_the_same_data() {
696
        let moves = [mv(0, 0), mv(5, 3), mv(9, 9)];
697
        let from_moves = NodeIdMap::from_node_moves(&moves);
698
        let from_pairs =
699
            NodeIdMap::from_pairs([(nid(0), nid(0)), (nid(5), nid(3)), (nid(9), nid(9))]);
700
        assert_eq!(
701
            from_moves, from_pairs,
702
            "the two constructors must produce identical maps for identical data"
703
        );
704
    }
705

            
706
    /// A malformed `node_moves` slice (the same old id listed twice) must not
707
    /// panic and must resolve deterministically — `BTreeMap::collect` keeps the
708
    /// LAST entry.
709
    #[test]
710
    fn from_node_moves_with_a_duplicated_old_id_keeps_the_last_entry() {
711
        let map = NodeIdMap::from_node_moves(&[mv(1, 10), mv(1, 20), mv(1, 30)]);
712
        assert_eq!(
713
            map.as_btree_map().len(),
714
            1,
715
            "duplicates collapse to one key"
716
        );
717
        assert_eq!(
718
            map.resolve(nid(1)),
719
            Some(nid(30)),
720
            "the last NodeMove for an old id wins"
721
        );
722
    }
723

            
724
    /// Two old nodes mapped onto the SAME new id is nonsense input, but it must
725
    /// still build a well-formed (if lossy) map rather than panic.
726
    #[test]
727
    fn from_node_moves_with_a_non_injective_mapping_does_not_panic() {
728
        let map = NodeIdMap::from_node_moves(&[mv(1, 7), mv(2, 7)]);
729
        assert_eq!(
730
            map.as_btree_map().len(),
731
            2,
732
            "both old ids are retained as keys"
733
        );
734
        assert_eq!(map.resolve(nid(1)), Some(nid(7)));
735
        assert_eq!(map.resolve(nid(2)), Some(nid(7)));
736
    }
737

            
738
    /// `NodeId` wraps a `usize`; ids at the very top of the range are just
739
    /// indices as far as the map is concerned — no arithmetic, no overflow.
740
    #[test]
741
    fn from_node_moves_handles_extreme_node_ids() {
742
        let map = NodeIdMap::from_node_moves(&[
743
            mv(usize::MAX, usize::MAX),
744
            mv(usize::MAX - 1, 0),
745
            mv(0, usize::MAX),
746
        ]);
747
        assert_eq!(map.resolve(nid(usize::MAX)), Some(nid(usize::MAX)));
748
        assert_eq!(map.resolve(nid(usize::MAX - 1)), Some(nid(0)));
749
        assert_eq!(map.resolve(nid(0)), Some(nid(usize::MAX)));
750
        assert!(!map.is_empty());
751
    }
752

            
753
    #[test]
754
    fn from_pairs_on_an_empty_iterator_yields_an_empty_map() {
755
        let map = NodeIdMap::from_pairs(Vec::new());
756
        assert!(map.is_empty());
757
        assert!(map.resolve(NodeId::ZERO).is_none());
758
        assert!(map.is_unmounted(NodeId::ZERO));
759
    }
760

            
761
    #[test]
762
    fn from_pairs_with_a_duplicated_old_id_keeps_the_last_entry() {
763
        let map = NodeIdMap::from_pairs([(nid(4), nid(1)), (nid(4), nid(2))]);
764
        assert_eq!(map.as_btree_map().len(), 1);
765
        assert_eq!(map.resolve(nid(4)), Some(nid(2)));
766
    }
767

            
768
    /// Post-construction invariants at volume: every pair fed in resolves back
769
    /// out, the length matches the number of distinct old ids, and nothing that
770
    /// was never inserted resolves.
771
    #[test]
772
    fn from_pairs_invariants_hold_at_volume() {
773
        let n = 2048usize;
774
        let pairs: Vec<(NodeId, NodeId)> = (0..n).map(|i| (nid(i), nid(n - 1 - i))).collect();
775
        let map = NodeIdMap::from_pairs(pairs);
776

            
777
        assert_eq!(map.as_btree_map().len(), n);
778
        assert!(!map.is_empty());
779
        for i in 0..n {
780
            assert_eq!(map.resolve(nid(i)), Some(nid(n - 1 - i)));
781
            assert!(!map.is_unmounted(nid(i)));
782
        }
783
        assert!(
784
            map.resolve(nid(n)).is_none(),
785
            "an id never inserted is unmounted"
786
        );
787
        assert!(map.is_unmounted(nid(n)));
788
    }
789

            
790
    /// Round-trip: `as_btree_map` is a faithful encoding of what went in, and
791
    /// feeding it back through `from_pairs` reproduces the map exactly.
792
    #[test]
793
    fn as_btree_map_round_trips_through_from_pairs() {
794
        let original = NodeIdMap::from_pairs([
795
            (nid(0), nid(0)),
796
            (nid(2), nid(1)),
797
            (nid(3), nid(2)),
798
            (nid(usize::MAX), nid(4)),
799
        ]);
800
        let decoded = NodeIdMap::from_pairs(
801
            original
802
                .as_btree_map()
803
                .iter()
804
                .map(|(old, new)| (*old, *new))
805
                .collect::<Vec<_>>(),
806
        );
807
        assert_eq!(decoded, original, "encode == decode");
808
        assert_eq!(decoded.as_btree_map(), original.as_btree_map());
809
    }
810

            
811
    #[test]
812
    fn a_default_map_unmounts_everything() {
813
        let map = NodeIdMap::default();
814
        assert!(map.is_empty());
815
        assert!(map.as_btree_map().is_empty());
816
        for i in [0usize, 1, 2, 1024, usize::MAX - 1, usize::MAX] {
817
            assert!(map.resolve(nid(i)).is_none());
818
            assert!(
819
                map.is_unmounted(nid(i)),
820
                "an empty reconciliation means every old node was unmounted"
821
            );
822
        }
823
    }
824

            
825
    // --------------------------------------------- resolve / is_unmounted
826

            
827
    /// The two accessors are two views of the same fact — they must never
828
    /// disagree, for any id, on any map.
829
    #[test]
830
    fn resolve_and_is_unmounted_never_disagree() {
831
        let map = NodeIdMap::from_pairs([(nid(0), nid(0)), (nid(2), nid(1)), (nid(3), nid(2))]);
832
        for i in [0usize, 1, 2, 3, 4, 100, usize::MAX - 1, usize::MAX] {
833
            assert_eq!(
834
                map.resolve(nid(i)).is_none(),
835
                map.is_unmounted(nid(i)),
836
                "is_unmounted({i}) must be exactly !resolve({i}).is_some()"
837
            );
838
        }
839
    }
840

            
841
    #[test]
842
    fn resolve_is_pure_repeated_calls_return_the_same_answer() {
843
        let map = NodeIdMap::from_pairs([(nid(3), nid(2))]);
844
        let first = map.resolve(nid(3));
845
        assert_eq!(first, map.resolve(nid(3)));
846
        assert_eq!(first, map.resolve(nid(3)));
847
        assert_eq!(first, Some(nid(2)));
848
    }
849

            
850
    /// `resolve` is a single lookup, NOT a transitive closure. If it chased
851
    /// chains, `1 → 2 → 3` would collapse and every remap would be wrong for
852
    /// any map whose new ids overlap its old ids (which is the normal case).
853
    #[test]
854
    fn resolve_does_not_chase_chains() {
855
        let map = NodeIdMap::from_pairs([(nid(1), nid(2)), (nid(2), nid(3))]);
856
        assert_eq!(
857
            map.resolve(nid(1)),
858
            Some(nid(2)),
859
            "resolve must apply exactly one hop"
860
        );
861
        assert_eq!(map.resolve(nid(2)), Some(nid(3)));
862
    }
863

            
864
    /// A node that kept its index is MATCHED, not unmounted — the whole GC rule
865
    /// depends on identity entries being present and meaningful.
866
    #[test]
867
    fn an_identity_entry_means_matched_not_unmounted() {
868
        let map = NodeIdMap::from_pairs([(nid(7), nid(7))]);
869
        assert!(!map.is_unmounted(nid(7)));
870
        assert_eq!(map.resolve(nid(7)), Some(nid(7)));
871
        assert!(map.is_unmounted(nid(6)));
872
        assert!(map.is_unmounted(nid(8)));
873
    }
874

            
875
    #[test]
876
    fn is_empty_is_exactly_the_btree_maps_emptiness() {
877
        let empty = NodeIdMap::from_pairs(Vec::new());
878
        assert_eq!(empty.is_empty(), empty.as_btree_map().is_empty());
879
        assert!(empty.is_empty());
880

            
881
        let full = NodeIdMap::from_pairs([(nid(0), nid(0))]);
882
        assert_eq!(full.is_empty(), full.as_btree_map().is_empty());
883
        assert!(!full.is_empty());
884
    }
885

            
886
    // ------------------------------------------------- resolve_dom_node_id
887

            
888
    /// The documented pass-through rule: a reconciliation of DOM 0 says NOTHING
889
    /// about DOM 1, so an id from another DOM must come back byte-identical —
890
    /// even when its node index happens to be unmounted in *this* map.
891
    #[test]
892
    fn a_foreign_dom_node_id_is_passed_through_untouched() {
893
        let map = NodeIdMap::from_pairs([(nid(2), nid(1))]);
894
        // Node 5 is "unmounted" as far as this map is concerned...
895
        let foreign = dom_node_at(DOM1, nid(5));
896
        assert_eq!(
897
            map.resolve_dom_node_id(DOM0, foreign),
898
            Some(foreign),
899
            "an id in another DOM must never be dropped by this DOM's reconciliation"
900
        );
901
        // ...and a foreign id whose index IS in the map must not be rewritten either.
902
        let foreign_colliding = dom_node_at(DOM1, nid(2));
903
        assert_eq!(
904
            map.resolve_dom_node_id(DOM0, foreign_colliding),
905
            Some(foreign_colliding),
906
            "a foreign id must not be remapped just because its index appears in the map"
907
        );
908
    }
909

            
910
    #[test]
911
    fn resolve_dom_node_id_rewrites_matched_nodes_and_drops_unmounted_ones() {
912
        let map = NodeIdMap::from_pairs([(nid(2), nid(1))]);
913
        assert_eq!(
914
            map.resolve_dom_node_id(DOM0, dom_node_at(DOM0, nid(2))),
915
            Some(dom_node_at(DOM0, nid(1)))
916
        );
917
        assert_eq!(
918
            map.resolve_dom_node_id(DOM0, dom_node_at(DOM0, nid(1))),
919
            None,
920
            "a node absent from the map is unmounted, so the id must be dropped"
921
        );
922
    }
923

            
924
    /// `NodeHierarchyItemId::NONE` decodes to `None`. For the reconciled DOM
925
    /// that means "no node" → `None`; for a foreign DOM the pass-through branch
926
    /// fires first, so it survives unchanged. Both are deterministic.
927
    #[test]
928
    fn a_none_node_id_is_handled_without_panicking() {
929
        let map = NodeIdMap::from_pairs([(nid(0), nid(0))]);
930
        let none_here = DomNodeId {
931
            dom: DOM0,
932
            node: NodeHierarchyItemId::NONE,
933
        };
934
        assert_eq!(map.resolve_dom_node_id(DOM0, none_here), None);
935

            
936
        let none_elsewhere = DomNodeId {
937
            dom: DOM1,
938
            node: NodeHierarchyItemId::NONE,
939
        };
940
        assert_eq!(
941
            map.resolve_dom_node_id(DOM0, none_elsewhere),
942
            Some(none_elsewhere),
943
            "the foreign-DOM pass-through happens before the node is decoded"
944
        );
945
    }
946

            
947
    /// Boundary ids on both axes: the largest encodable node index and the
948
    /// largest `DomId`. `MAX_ENCODABLE` maps to raw `usize::MAX` in the 1-based
949
    /// encoding, i.e. the last value that fits.
950
    #[test]
951
    fn resolve_dom_node_id_survives_boundary_ids() {
952
        let map =
953
            NodeIdMap::from_pairs([(nid(MAX_ENCODABLE), nid(0)), (nid(0), nid(MAX_ENCODABLE))]);
954

            
955
        // Largest encodable index as the OLD id.
956
        let big_old = dom_node_at(DOM0, nid(MAX_ENCODABLE));
957
        assert_eq!(
958
            big_old.node.into_raw(),
959
            usize::MAX,
960
            "1-based encoding is saturated"
961
        );
962
        assert_eq!(
963
            map.resolve_dom_node_id(DOM0, big_old),
964
            Some(dom_node_at(DOM0, nid(0)))
965
        );
966

            
967
        // Largest encodable index as the NEW id (re-encoding must not overflow).
968
        assert_eq!(
969
            map.resolve_dom_node_id(DOM0, dom_node_at(DOM0, nid(0))),
970
            Some(dom_node_at(DOM0, nid(MAX_ENCODABLE)))
971
        );
972

            
973
        // An extreme DomId is still just a DomId.
974
        let far_dom = dom_node_at(DOM_MAX, nid(0));
975
        assert_eq!(
976
            map.resolve_dom_node_id(DOM0, far_dom),
977
            Some(far_dom),
978
            "DomId::MAX is foreign to DOM 0 and passes through"
979
        );
980
        assert_eq!(
981
            map.resolve_dom_node_id(DOM_MAX, far_dom),
982
            Some(dom_node_at(DOM_MAX, nid(MAX_ENCODABLE))),
983
            "when DomId::MAX *is* the reconciled DOM, its nodes are remapped"
984
        );
985
    }
986

            
987
    #[test]
988
    fn resolve_dom_node_id_on_an_empty_map_drops_own_dom_and_keeps_foreign() {
989
        let map = NodeIdMap::default();
990
        assert_eq!(
991
            map.resolve_dom_node_id(DOM0, dom_node_at(DOM0, nid(0))),
992
            None
993
        );
994
        let foreign = dom_node_at(DOM1, nid(0));
995
        assert_eq!(map.resolve_dom_node_id(DOM0, foreign), Some(foreign));
996
    }
997

            
998
    // ------------------------------------------------------- remap_keys
999

            
    /// The reason `remap_keys` takes the map out before rebuilding it: a SWAP
    /// (`1 → 2`, `2 → 1`) is a legal reconciliation, and an in-place rewrite
    /// would overwrite one payload with the other. Both payloads must survive,
    /// on the correct keys.
    #[test]
    fn remap_keys_handles_a_swap_without_clobbering_payloads() {
        let mut map: BTreeMap<NodeId, &str> = BTreeMap::new();
        map.insert(nid(1), "one");
        map.insert(nid(2), "two");
        let node_map = NodeIdMap::from_pairs([(nid(1), nid(2)), (nid(2), nid(1))]);
        remap_keys(&mut map, &node_map);
        assert_eq!(map.len(), 2, "a swap must not lose an entry");
        assert_eq!(map.get(&nid(1)).copied(), Some("two"));
        assert_eq!(map.get(&nid(2)).copied(), Some("one"));
    }
    /// The GC half of the contract: keys absent from the map are unmounted and
    /// must be dropped, never kept "just in case".
    #[test]
    fn remap_keys_drops_state_for_unmounted_nodes() {
        let mut map: BTreeMap<NodeId, u32> = BTreeMap::new();
        map.insert(nid(1), 10);
        map.insert(nid(2), 20);
        map.insert(nid(3), 30);
        let node_map = NodeIdMap::from_pairs([(nid(2), nid(1)), (nid(3), nid(2))]);
        remap_keys(&mut map, &node_map);
        assert_eq!(map.len(), 2, "node 1's state must be GC'd");
        assert_eq!(map.get(&nid(1)).copied(), Some(20));
        assert_eq!(map.get(&nid(2)).copied(), Some(30));
        assert!(
            !map.contains_key(&nid(3)),
            "no state may remain at a dead index"
        );
    }
    #[test]
    fn remap_keys_with_an_empty_node_map_clears_all_state() {
        let mut map: BTreeMap<NodeId, u32> = BTreeMap::new();
        map.insert(nid(0), 1);
        map.insert(nid(9), 2);
        remap_keys(&mut map, &NodeIdMap::default());
        assert!(
            map.is_empty(),
            "an empty reconciliation unmounts everything, so all state is dropped"
        );
    }
    #[test]
    fn remap_keys_with_an_identity_map_is_a_no_op() {
        let mut map: BTreeMap<NodeId, u32> = (0..64).map(|i| (nid(i), i as u32)).collect();
        let before = map.clone();
        let node_map = NodeIdMap::from_pairs((0..64).map(|i| (nid(i), nid(i))));
        remap_keys(&mut map, &node_map);
        assert_eq!(map, before);
    }
    #[test]
    fn remap_keys_on_an_empty_map_does_not_panic() {
        let mut map: BTreeMap<NodeId, u32> = BTreeMap::new();
        remap_keys(&mut map, &NodeIdMap::from_pairs([(nid(1), nid(0))]));
        assert!(map.is_empty());
    }
    /// A non-injective reconciliation (`1 → 5` and `2 → 5`) cannot be
    /// represented by a map keyed on `NodeId` — one entry must win. Assert the
    /// outcome is deterministic (source keys are visited in ascending order, so
    /// the HIGHEST old id lands last) rather than a panic or a silent duplicate.
    #[test]
    fn remap_keys_collision_is_lossy_but_deterministic() {
        let mut map: BTreeMap<NodeId, &str> = BTreeMap::new();
        map.insert(nid(1), "from-1");
        map.insert(nid(2), "from-2");
        let node_map = NodeIdMap::from_pairs([(nid(1), nid(5)), (nid(2), nid(5))]);
        remap_keys(&mut map, &node_map);
        assert_eq!(
            map.len(),
            1,
            "two old keys collapsing onto one new key lose one entry"
        );
        assert_eq!(
            map.get(&nid(5)).copied(),
            Some("from-2"),
            "the last-visited (highest) old id wins — deterministic, not arbitrary"
        );
    }
    /// The preceding-sibling delete at scale: deleting node 1 of 256 shifts every
    /// later index down by one. Every payload must land on exactly the key that
    /// now denotes its element — an off-by-one here is the misattachment bug the
    /// module doc-comment describes.
    #[test]
    fn remap_keys_preserves_payload_identity_under_a_shift_down() {
        let n = 256usize;
        let mut map: BTreeMap<NodeId, usize> = (0..n).map(|i| (nid(i), i * 1000)).collect();
        // 0 stays, 1 is deleted, 2..n shift down by one.
        let node_map = NodeIdMap::from_pairs(
            core::iter::once((nid(0), nid(0))).chain((2..n).map(|i| (nid(i), nid(i - 1)))),
        );
        remap_keys(&mut map, &node_map);
        assert_eq!(map.len(), n - 1, "exactly the deleted node's state is GC'd");
        assert_eq!(map.get(&nid(0)).copied(), Some(0));
        for i in 2..n {
            assert_eq!(
                map.get(&nid(i - 1)).copied(),
                Some(i * 1000),
                "node {i}'s payload must follow it to index {}",
                i - 1
            );
        }
        assert!(
            !map.contains_key(&nid(n - 1)),
            "the vacated tail index is empty"
        );
    }
    /// Ordering trap: an entry is rewritten ONTO an index that another (about to
    /// be dropped) entry currently occupies. Because the source map is taken out
    /// first, the survivor must not be eaten by the corpse.
    #[test]
    fn remap_keys_survivor_moving_onto_a_dead_index_is_not_dropped() {
        let mut map: BTreeMap<NodeId, &str> = BTreeMap::new();
        map.insert(nid(1), "doomed");
        map.insert(nid(2), "survivor");
        // Node 1 is unmounted; node 2 moves into its slot.
        let node_map = NodeIdMap::from_pairs([(nid(2), nid(1))]);
        remap_keys(&mut map, &node_map);
        assert_eq!(map.len(), 1);
        assert_eq!(
            map.get(&nid(1)).copied(),
            Some("survivor"),
            "the surviving payload occupies the recycled index — the dead one is gone"
        );
    }
    // --------------------------------------------------- remap_dom_keys
    #[test]
    fn remap_dom_keys_never_touches_another_dom() {
        let mut map: BTreeMap<(DomId, NodeId), u32> = BTreeMap::new();
        map.insert((DOM0, nid(2)), 20);
        // Same node index, different DOM — must survive verbatim.
        map.insert((DOM1, nid(2)), 99);
        // A foreign entry at an index that is unmounted in DOM 0.
        map.insert((DOM1, nid(1)), 98);
        let node_map = NodeIdMap::from_pairs([(nid(2), nid(1))]);
        remap_dom_keys(&mut map, DOM0, &node_map);
        assert_eq!(
            map.get(&(DOM0, nid(1))).copied(),
            Some(20),
            "DOM 0's entry is remapped"
        );
        assert!(
            !map.contains_key(&(DOM0, nid(2))),
            "the old DOM 0 key is gone"
        );
        assert_eq!(
            map.get(&(DOM1, nid(2))).copied(),
            Some(99),
            "DOM 1 is untouched by a DOM 0 reconciliation"
        );
        assert_eq!(map.get(&(DOM1, nid(1))).copied(), Some(98));
        assert_eq!(map.len(), 3);
    }
    #[test]
    fn remap_dom_keys_drops_unmounted_entries_of_the_target_dom_only() {
        let mut map: BTreeMap<(DomId, NodeId), u32> = BTreeMap::new();
        map.insert((DOM0, nid(1)), 10); // unmounted in DOM 0 -> dropped
        map.insert((DOM1, nid(1)), 11); // same index, other DOM -> kept
        let node_map = NodeIdMap::from_pairs([(nid(0), nid(0))]);
        remap_dom_keys(&mut map, DOM0, &node_map);
        assert!(!map.contains_key(&(DOM0, nid(1))));
        assert_eq!(map.get(&(DOM1, nid(1))).copied(), Some(11));
        assert_eq!(map.len(), 1);
    }
    #[test]
    fn remap_dom_keys_handles_a_swap_within_the_target_dom() {
        let mut map: BTreeMap<(DomId, NodeId), &str> = BTreeMap::new();
        map.insert((DOM0, nid(1)), "one");
        map.insert((DOM0, nid(2)), "two");
        map.insert((DOM1, nid(1)), "other-dom");
        let node_map = NodeIdMap::from_pairs([(nid(1), nid(2)), (nid(2), nid(1))]);
        remap_dom_keys(&mut map, DOM0, &node_map);
        assert_eq!(map.get(&(DOM0, nid(1))).copied(), Some("two"));
        assert_eq!(map.get(&(DOM0, nid(2))).copied(), Some("one"));
        assert_eq!(map.get(&(DOM1, nid(1))).copied(), Some("other-dom"));
        assert_eq!(map.len(), 3, "a swap plus a bystander DOM loses nothing");
    }
    #[test]
    fn remap_dom_keys_with_an_empty_node_map_clears_only_the_target_dom() {
        let mut map: BTreeMap<(DomId, NodeId), u32> = BTreeMap::new();
        map.insert((DOM0, nid(0)), 1);
        map.insert((DOM0, nid(5)), 2);
        map.insert((DOM1, nid(0)), 3);
        remap_dom_keys(&mut map, DOM0, &NodeIdMap::default());
        assert_eq!(map.len(), 1, "every DOM 0 node was unmounted");
        assert_eq!(map.get(&(DOM1, nid(0))).copied(), Some(3));
    }
    #[test]
    fn remap_dom_keys_on_an_empty_map_does_not_panic() {
        let mut map: BTreeMap<(DomId, NodeId), u32> = BTreeMap::new();
        remap_dom_keys(&mut map, DOM0, &NodeIdMap::from_pairs([(nid(1), nid(0))]));
        assert!(map.is_empty());
    }
    #[test]
    fn remap_dom_keys_with_a_target_dom_that_has_no_entries_is_a_no_op() {
        let mut map: BTreeMap<(DomId, NodeId), u32> = BTreeMap::new();
        map.insert((DOM1, nid(1)), 1);
        map.insert((DOM_MAX, nid(2)), 2);
        let before = map.clone();
        remap_dom_keys(&mut map, DOM0, &NodeIdMap::from_pairs([(nid(1), nid(9))]));
        assert_eq!(map, before);
    }
    #[test]
    fn remap_dom_keys_handles_boundary_dom_and_node_ids() {
        let mut map: BTreeMap<(DomId, NodeId), u32> = BTreeMap::new();
        map.insert((DOM_MAX, nid(usize::MAX)), 1);
        map.insert((DOM_MAX, nid(usize::MAX - 1)), 2);
        map.insert((DOM0, nid(usize::MAX)), 3);
        let node_map = NodeIdMap::from_pairs([(nid(usize::MAX), nid(0))]);
        remap_dom_keys(&mut map, DOM_MAX, &node_map);
        assert_eq!(
            map.get(&(DOM_MAX, nid(0))).copied(),
            Some(1),
            "usize::MAX remaps like any other index"
        );
        assert!(
            !map.contains_key(&(DOM_MAX, nid(usize::MAX - 1))),
            "unmounted in DOM_MAX -> dropped"
        );
        assert_eq!(
            map.get(&(DOM0, nid(usize::MAX))).copied(),
            Some(3),
            "DOM 0 is a bystander here"
        );
        assert_eq!(map.len(), 2);
    }
    /// Applying the SAME reconciliation twice is not idempotent in general (the
    /// second pass re-reads already-new ids as if they were old), which is why
    /// callers must run it exactly once per rebuild. Pin the one case that IS
    /// safe — the identity map — so the no-op guarantee cannot regress.
    #[test]
    fn remap_dom_keys_with_an_identity_map_is_a_no_op_even_when_repeated() {
        let mut map: BTreeMap<(DomId, NodeId), u32> =
            (0..32).map(|i| ((DOM0, nid(i)), i as u32)).collect();
        let before = map.clone();
        let node_map = NodeIdMap::from_pairs((0..32).map(|i| (nid(i), nid(i))));
        remap_dom_keys(&mut map, DOM0, &node_map);
        remap_dom_keys(&mut map, DOM0, &node_map);
        assert_eq!(map, before);
    }
}