1
//! DOM Reconciliation Module
2
//!
3
//! This module provides the reconciliation algorithm that compares two DOM trees
4
//! and generates lifecycle events. It uses stable keys and content hashing to
5
//! identify moves vs. mounts/unmounts.
6
//!
7
//! The reconciliation strategy is:
8
//! 1. **Stable Key Match:** If `.with_key()` is used, it's an absolute match (O(1)).
9
//! 2. **CSS ID Match:** If no key, use the CSS ID as key.
10
//! 3. **Structural Key Match:** nth-of-type-within-parent + parent's key (recursive).
11
//! 4. **Hash Match (Content Match):** Check for identical `DomNodeHash`.
12
//! 5. **Structural Hash Match:** For text nodes, match by structural hash (ignoring content).
13
//! 6. **Fallback:** Anything not matched is a `Mount` (new) or `Unmount` (old leftovers).
14

            
15
use alloc::{
16
    collections::{BTreeMap, VecDeque},
17
    string::{String, ToString},
18
    vec::Vec,
19
};
20
use core::hash::Hash;
21

            
22
use azul_css::props::property::{CssPropertyType, RelayoutScope};
23

            
24
use crate::{
25
    dom::{DomId, DomNodeHash, DomNodeId, IdOrClass, NodeData, NodeType},
26
    events::{
27
        ComponentEventFilter, EventData, EventFilter, EventPhase, EventSource, EventType,
28
        LifecycleEventData, LifecycleReason, SyntheticEvent,
29
    },
30
    geom::LogicalRect,
31
    id::NodeId,
32
    refany::RefAny,
33
    styled_dom::{
34
        ChangedCssProperty, NodeHierarchyItem, NodeHierarchyItemId, RestyleResult, StyledNodeState,
35
    },
36
    task::Instant,
37
    OrderedMap,
38
};
39

            
40
// ============================================================================
41
// NodeChangeSet — granular per-node change flags
42
// ============================================================================
43

            
44
/// Bit flags describing what changed about a node between old and new DOM.
45
/// Multiple flags can be set simultaneously. Uses manual bit manipulation
46
/// instead of bitflags crate to avoid adding a dependency.
47
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
48
pub struct NodeChangeSet {
49
    pub bits: u32,
50
}
51

            
52
impl NodeChangeSet {
53
    // --- Changes that affect LAYOUT (need relayout + repaint) ---
54

            
55
    /// Node type changed entirely (e.g., Text → Image).
56
    pub const NODE_TYPE_CHANGED: u32 = 0b0000_0000_0000_0001;
57
    /// Text content changed (for Text nodes).
58
    pub const TEXT_CONTENT: u32 = 0b0000_0000_0000_0010;
59
    /// CSS IDs or classes changed (may cause restyle → relayout).
60
    pub const IDS_AND_CLASSES: u32 = 0b0000_0000_0000_0100;
61
    /// Inline CSS properties changed that affect layout.
62
    pub const INLINE_STYLE_LAYOUT: u32 = 0b0000_0000_0000_1000;
63
    /// Children added, removed, or reordered.
64
    pub const CHILDREN_CHANGED: u32 = 0b0000_0000_0001_0000;
65
    /// Image source changed (may affect intrinsic size).
66
    pub const IMAGE_CHANGED: u32 = 0b0000_0000_0010_0000;
67
    /// Contenteditable flag changed.
68
    pub const CONTENTEDITABLE: u32 = 0b0000_0000_0100_0000;
69
    /// Tab index changed.
70
    pub const TAB_INDEX: u32 = 0b0000_0000_1000_0000;
71

            
72
    // --- Changes that affect PAINT only (no relayout needed) ---
73

            
74
    /// Inline CSS properties changed that affect paint only.
75
    pub const INLINE_STYLE_PAINT: u32 = 0b0000_0001_0000_0000;
76
    /// Styled node state changed (hover, active, focus, etc.).
77
    pub const STYLED_STATE: u32 = 0b0000_0010_0000_0000;
78

            
79
    // --- Changes that affect NEITHER layout nor paint ---
80

            
81
    /// Callbacks changed (new `RefAny`, different event handlers).
82
    pub const CALLBACKS: u32 = 0b0000_0100_0000_0000;
83
    /// Dataset changed.
84
    pub const DATASET: u32 = 0b0000_1000_0000_0000;
85
    /// Accessibility info changed.
86
    pub const ACCESSIBILITY: u32 = 0b0001_0000_0000_0000;
87

            
88
    // --- Composite masks ---
89

            
90
    /// Any change that requires a layout pass.
91
    pub const AFFECTS_LAYOUT: u32 = Self::NODE_TYPE_CHANGED
92
        | Self::TEXT_CONTENT
93
        | Self::IDS_AND_CLASSES
94
        | Self::INLINE_STYLE_LAYOUT
95
        | Self::CHILDREN_CHANGED
96
        | Self::IMAGE_CHANGED
97
        | Self::CONTENTEDITABLE;
98

            
99
    /// Any change that requires a paint/display-list update (but not layout).
100
    pub const AFFECTS_PAINT: u32 = Self::INLINE_STYLE_PAINT | Self::STYLED_STATE;
101

            
102
    #[must_use]
103
63279
    pub const fn empty() -> Self {
104
63279
        Self { bits: 0 }
105
63279
    }
106

            
107
    #[must_use]
108
415
    pub const fn is_empty(&self) -> bool {
109
415
        self.bits == 0
110
415
    }
111

            
112
    #[must_use]
113
1597
    pub const fn contains(&self, flag: u32) -> bool {
114
1597
        (self.bits & flag) == flag
115
1597
    }
116

            
117
    #[must_use]
118
124205
    pub const fn intersects(&self, mask: u32) -> bool {
119
124205
        (self.bits & mask) != 0
120
124205
    }
121

            
122
3027
    pub const fn insert(&mut self, flag: u32) {
123
3027
        self.bits |= flag;
124
3027
    }
125

            
126
    /// Returns true if no visual change occurred (only callbacks/dataset/a11y).
127
    #[must_use]
128
137
    pub const fn is_visually_unchanged(&self) -> bool {
129
137
        !self.intersects(Self::AFFECTS_LAYOUT) && !self.intersects(Self::AFFECTS_PAINT)
130
137
    }
131

            
132
    /// Returns true if layout is needed.
133
    #[must_use]
134
62499
    pub const fn needs_layout(&self) -> bool {
135
62499
        self.intersects(Self::AFFECTS_LAYOUT)
136
62499
    }
137

            
138
    /// Returns true if paint is needed (but not necessarily layout).
139
    #[must_use]
140
61431
    pub const fn needs_paint(&self) -> bool {
141
61431
        self.intersects(Self::AFFECTS_PAINT)
142
61431
    }
143
}
144

            
145
impl core::ops::BitOrAssign for NodeChangeSet {
146
104
    fn bitor_assign(&mut self, rhs: Self) {
147
104
        self.bits |= rhs.bits;
148
104
    }
149
}
150

            
151
impl core::ops::BitOr for NodeChangeSet {
152
    type Output = Self;
153
17
    fn bitor(self, rhs: Self) -> Self {
154
17
        Self {
155
17
            bits: self.bits | rhs.bits,
156
17
        }
157
17
    }
158
}
159

            
160
/// Extended diff result that includes per-node change information.
161
#[derive(Debug, Clone, Default)]
162
pub struct ExtendedDiffResult {
163
    /// Original diff result (lifecycle events + node moves).
164
    pub diff: DiffResult,
165
    /// Per-node change report for matched (moved) nodes.
166
    /// Each entry: (`old_node_id`, `new_node_id`, `what_changed`).
167
    /// Only contains entries for nodes that were matched.
168
    pub node_changes: Vec<(NodeId, NodeId, NodeChangeSet)>,
169
}
170

            
171
/// Compare two matched `NodeData` instances field-by-field and return
172
/// a `NodeChangeSet` describing what changed.
173
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
174
#[must_use]
175
1038
pub fn compute_node_changes(
176
1038
    old_node: &NodeData,
177
1038
    new_node: &NodeData,
178
1038
    old_styled_state: Option<&StyledNodeState>,
179
1038
    new_styled_state: Option<&StyledNodeState>,
180
1038
) -> NodeChangeSet {
181
1038
    let mut changes = NodeChangeSet::empty();
182

            
183
    // 1. Node type discriminant
184
1038
    if core::mem::discriminant(old_node.get_node_type())
185
1038
        != core::mem::discriminant(new_node.get_node_type())
186
    {
187
77
        changes.insert(NodeChangeSet::NODE_TYPE_CHANGED);
188
77
        return changes; // everything else is irrelevant
189
961
    }
190

            
191
    // 2. Content-specific comparison (same discriminant)
192
961
    match (old_node.get_node_type(), new_node.get_node_type()) {
193
499
        (NodeType::Text(old_text), NodeType::Text(new_text)) => {
194
499
            if old_text.as_str() != new_text.as_str() {
195
278
                changes.insert(NodeChangeSet::TEXT_CONTENT);
196
278
            }
197
        }
198
2
        (NodeType::Image(old_img), NodeType::Image(new_img)) => {
199
            // Use Hash-based comparison (pointer identity for decoded images,
200
            // callback identity for callback images)
201
            use core::hash::Hasher;
202
4
            let hash_img = |img: &crate::resources::ImageRef| -> u64 {
203
4
                let mut h = crate::hash::DefaultHasher::new();
204
4
                img.hash(&mut h);
205
4
                h.finish()
206
4
            };
207
2
            if hash_img(old_img) != hash_img(new_img) {
208
1
                changes.insert(NodeChangeSet::IMAGE_CHANGED);
209
1
            }
210
        }
211
460
        _ => {} // Same non-content type → no content change
212
    }
213

            
214
    // 3. IDs and classes (now stored in attributes as AttributeType::Id/Class)
215
    {
216
        use crate::dom::AttributeType;
217
961
        let old_ids_classes: Vec<_> = old_node
218
961
            .attributes()
219
961
            .as_ref()
220
961
            .iter()
221
961
            .filter(|a| matches!(a, AttributeType::Id(_) | AttributeType::Class(_)))
222
961
            .collect();
223
961
        let new_ids_classes: Vec<_> = new_node
224
961
            .attributes()
225
961
            .as_ref()
226
961
            .iter()
227
961
            .filter(|a| matches!(a, AttributeType::Id(_) | AttributeType::Class(_)))
228
961
            .collect();
229
961
        if old_ids_classes != new_ids_classes {
230
96
            changes.insert(NodeChangeSet::IDS_AND_CLASSES);
231
865
        }
232
    }
233

            
234
    // 4. Inline CSS properties — classify into layout-affecting vs paint-only.
235
    // After the inline-vs-component unification, inline CSS is stored as a `Css`
236
    // with rule blocks; iterate it via the `(property, conditions)` flat view to
237
    // keep the per-property compare semantics this code was written for.
238
961
    if old_node.style != new_node.style {
239
118
        let mut has_layout = false;
240
118
        let mut has_paint = false;
241

            
242
        // Classify a changed/added/removed property into the layout vs paint bucket.
243
        #[allow(clippy::items_after_statements)]
244
118
        fn mark(prop_type: CssPropertyType, has_layout: &mut bool, has_paint: &mut bool) {
245
118
            if prop_type.relayout_scope(true) == RelayoutScope::None {
246
40
                *has_paint = true;
247
78
            } else {
248
78
                *has_layout = true;
249
78
            }
250
118
        }
251

            
252
        // AUDIT: key the diff by (prop_type, conditions), NOT prop_type alone.
253
        // A node can carry the same property under different conditions (e.g.
254
        // `color: red` and `color: blue` scoped to `:hover`); keying by
255
        // prop_type collapsed them into one map slot, so a change to one
256
        // conditional variant could be silently dropped. Match each new
257
        // property against an old entry with the SAME prop_type AND the same
258
        // conditions, and mark any old entry left unmatched as removed.
259
118
        let old_props: Vec<(CssPropertyType, _, _)> = old_node
260
118
            .style
261
118
            .iter_inline_properties()
262
118
            .map(|(prop, conds)| (prop.get_type(), prop, conds))
263
118
            .collect();
264
118
        let mut old_matched = vec![false; old_props.len()];
265

            
266
118
        for (prop, conds) in new_node.style.iter_inline_properties() {
267
117
            let prop_type = prop.get_type();
268
            // Find an as-yet-unmatched old entry with the same (type, conditions).
269
117
            let mut found_unchanged = false;
270
117
            for (i, (old_type, old_prop, old_conds)) in old_props.iter().enumerate() {
271
59
                if old_matched[i]
272
59
                    || *old_type != prop_type
273
59
                    || old_conds.as_slice() != conds.as_slice()
274
                {
275
                    continue;
276
59
                }
277
59
                old_matched[i] = true;
278
59
                if *old_prop == prop {
279
                    found_unchanged = true;
280
59
                }
281
59
                break;
282
            }
283
            // Unchanged only when we matched an old (type, conditions) slot whose
284
            // value is identical; otherwise the property was added or changed.
285
117
            if !found_unchanged {
286
117
                mark(prop_type, &mut has_layout, &mut has_paint);
287
117
            }
288
        }
289

            
290
        // Check for removed properties (old (type, conditions) slots never matched)
291
118
        for (i, (old_type, _, _)) in old_props.iter().enumerate() {
292
60
            if !old_matched[i] {
293
1
                mark(*old_type, &mut has_layout, &mut has_paint);
294
59
            }
295
        }
296

            
297
118
        if has_layout {
298
78
            changes.insert(NodeChangeSet::INLINE_STYLE_LAYOUT);
299
78
        }
300
118
        if has_paint {
301
40
            changes.insert(NodeChangeSet::INLINE_STYLE_PAINT);
302
78
        }
303
843
    }
304

            
305
    // 5. Callbacks
306
    {
307
961
        let old_cbs = old_node.callbacks.as_ref();
308
961
        let new_cbs = new_node.callbacks.as_ref();
309
961
        if old_cbs.len() == new_cbs.len() {
310
960
            for (o, n) in old_cbs.iter().zip(new_cbs.iter()) {
311
3
                if o.event != n.event || o.callback != n.callback {
312
1
                    changes.insert(NodeChangeSet::CALLBACKS);
313
1
                    break;
314
2
                }
315
            }
316
1
        } else {
317
1
            changes.insert(NodeChangeSet::CALLBACKS);
318
1
        }
319
    }
320

            
321
    // 6. Dataset
322
961
    if old_node.get_dataset() != new_node.get_dataset() {
323
        changes.insert(NodeChangeSet::DATASET);
324
961
    }
325

            
326
    // 7. Contenteditable
327
961
    if old_node.is_contenteditable() != new_node.is_contenteditable() {
328
39
        changes.insert(NodeChangeSet::CONTENTEDITABLE);
329
922
    }
330

            
331
    // 8. Tab index
332
961
    if old_node.get_tab_index() != new_node.get_tab_index() {
333
20
        changes.insert(NodeChangeSet::TAB_INDEX);
334
941
    }
335

            
336
    // 9. Styled node state (hover, active, focused, etc.)
337
961
    if old_styled_state != new_styled_state {
338
40
        changes.insert(NodeChangeSet::STYLED_STATE);
339
921
    }
340

            
341
961
    changes
342
1038
}
343

            
344
/// Calculate the reconciliation key for a node using the priority hierarchy:
345
/// 1. Explicit key (set via `.with_key()`)
346
/// 2. CSS ID (set via `.with_id("my-id")`)
347
/// 3. Structural key: nth-of-type-within-parent + parent's reconciliation key
348
///
349
/// The structural key prevents incorrect matching when nodes are inserted
350
/// before existing nodes (e.g., prepending items to a list) and allows
351
/// keyless nodes to be matched across frames when their logical position
352
/// and type are stable (even if content changed — which then fires an
353
/// `Update` lifecycle event, see `reconcile_dom`).
354
///
355
/// When `hierarchy` is empty (or this node has no entry), the structural
356
/// key degrades to `discriminant(node_type) + classes` — parent/nth-of-type
357
/// context simply drops out. This lets callers that don't track hierarchy
358
/// (tests, flat-DOM scenarios) still benefit from explicit-key and CSS-ID
359
/// matching without divergent behavior.
360
#[must_use]
361
66024
pub fn calculate_reconciliation_key(
362
66024
    node_data: &[NodeData],
363
66024
    hierarchy: &[NodeHierarchyItem],
364
66024
    node_id: NodeId,
365
66024
) -> u64 {
366
    use core::hash::Hasher;
367

            
368
66024
    let n = node_data.len();
369

            
370
    // Terminal (parent-independent) key for a node: Priority 1 explicit key,
371
    // else Priority 2 CSS ID, else `None` (structural — needs the parent chain).
372
2192503
    let terminal_key = |nid: NodeId| -> Option<u64> {
373
2192503
        let node = &node_data[nid.index()];
374
        // Priority 1: Explicit key
375
2192503
        if let Some(key) = node.get_key() {
376
342
            return Some(key);
377
2192161
        }
378
        // Priority 2: CSS ID
379
2192161
        for attr in node.attributes().as_ref() {
380
44269
            if let Some(id) = attr.as_id() {
381
39453
                let mut hasher = crate::hash::DefaultHasher::new();
382
39453
                id.hash(&mut hasher);
383
39453
                return Some(hasher.finish());
384
4816
            }
385
        }
386
2152708
        None
387
2192503
    };
388

            
389
    // Fast path: the node itself has an explicit key or CSS ID.
390
66024
    if let Some(key) = terminal_key(node_id) {
391
39177
        return key;
392
26847
    }
393

            
394
    // Priority 3: structural key, computed ITERATIVELY up the parent chain.
395
    //
396
    // AUDIT: the previous implementation recursed once per ancestor with no
397
    // depth cap and no cycle guard, so a deep DOM overflowed the stack and a
398
    // corrupt (cyclic) hierarchy recursed forever — and `precompute_*` calls
399
    // this once per node. Walk upward instead, bounded by the node count.
400
    //
401
    // Collect the structural chain from `node_id` upward. The walk stops at:
402
    //   - the root (a node with no parent) — structural base is just `discriminant + classes`,
403
    //   - a terminal (explicit-key / CSS-ID) ancestor, whose key seeds the fold, or
404
    //   - `n` iterations (a valid parent chain is at most `n` long, so exceeding that means the
405
    //     hierarchy is cyclic/corrupt — stop).
406
26847
    let mut chain: Vec<NodeId> = Vec::new();
407
26847
    let mut seed_parent_key: Option<u64> = None;
408
26847
    let mut cur = node_id;
409
26847
    for _ in 0..n {
410
2152707
        if cur.index() >= n {
411
            break;
412
2152707
        }
413
2152707
        chain.push(cur);
414
2152707
        match hierarchy
415
2152707
            .get(cur.index())
416
2152707
            .and_then(NodeHierarchyItem::parent_id)
417
        {
418
26228
            None => break,
419
2126479
            Some(parent) => {
420
2126479
                if let Some(k) = terminal_key(parent) {
421
618
                    seed_parent_key = Some(k);
422
618
                    break;
423
2125861
                }
424
2125861
                cur = parent;
425
            }
426
        }
427
    }
428

            
429
    // Fold from the topmost ancestor down to `node_id`. `parent_key` threads the
430
    // accumulated key of the level above (identical to the old recursion, just
431
    // unrolled bottom-up).
432
26847
    let mut parent_key: Option<u64> = seed_parent_key;
433
2152707
    for &nid in chain.iter().rev() {
434
2152707
        let node = &node_data[nid.index()];
435
2152707
        let mut hasher = crate::hash::DefaultHasher::new();
436

            
437
2152707
        core::mem::discriminant(node.get_node_type()).hash(&mut hasher);
438
2152707
        for attr in node.attributes().as_ref() {
439
4684
            if let Some(class) = attr.as_class() {
440
4684
                class.hash(&mut hasher);
441
4684
            }
442
        }
443

            
444
2152707
        if let Some(parent_id) = hierarchy
445
2152707
            .get(nid.index())
446
2152707
            .and_then(NodeHierarchyItem::parent_id)
447
        {
448
            // nth-of-type: count same-discriminant siblings before `nid`.
449
2126479
            let mut sibling_index: usize = 0;
450
2126479
            let mut current = hierarchy
451
2126479
                .get(parent_id.index())
452
2126479
                .and_then(|h| h.first_child_id(parent_id));
453
2154742
            while let Some(sibling_id) = current {
454
2154737
                if sibling_id == nid {
455
2126474
                    break;
456
28263
                }
457
28263
                let sibling = &node_data[sibling_id.index()];
458
28263
                if core::mem::discriminant(sibling.get_node_type())
459
28263
                    == core::mem::discriminant(node.get_node_type())
460
27266
                {
461
27266
                    sibling_index += 1;
462
27272
                }
463
28263
                current = hierarchy
464
28263
                    .get(sibling_id.index())
465
28263
                    .and_then(NodeHierarchyItem::next_sibling_id);
466
            }
467

            
468
2126479
            sibling_index.hash(&mut hasher);
469
2126479
            parent_key.unwrap_or(0).hash(&mut hasher);
470
26228
        }
471

            
472
2152707
        parent_key = Some(hasher.finish());
473
    }
474

            
475
26847
    parent_key.unwrap_or(0)
476
66024
}
477

            
478
/// Precompute reconciliation keys for every node in a DOM tree.
479
///
480
/// Called once per side (old/new) at the start of `reconcile_dom`. Returns a
481
/// vector indexed by node index (`keys[node_id.index()]`) so lookup during
482
/// reconciliation is O(1).
483
#[must_use]
484
3708
pub fn precompute_reconciliation_keys(
485
3708
    node_data: &[NodeData],
486
3708
    hierarchy: &[NodeHierarchyItem],
487
3708
) -> Vec<u64> {
488
3708
    (0..node_data.len())
489
65640
        .map(|idx| calculate_reconciliation_key(node_data, hierarchy, NodeId::new(idx)))
490
3708
        .collect()
491
3708
}
492

            
493
/// Represents a mapping between a node in the old DOM and the new DOM.
494
#[derive(Debug, Clone, Copy)]
495
pub struct NodeMove {
496
    /// The `NodeId` in the old DOM array
497
    pub old_node_id: NodeId,
498
    /// The `NodeId` in the new DOM array
499
    pub new_node_id: NodeId,
500
}
501

            
502
/// The result of a DOM diff, containing lifecycle events and node mappings.
503
#[derive(Debug, Clone, Default)]
504
pub struct DiffResult {
505
    /// Lifecycle events generated by the diff (Mount, Unmount, Resize, Update)
506
    pub events: Vec<SyntheticEvent>,
507
    /// Maps Old `NodeId` -> New `NodeId` for state migration (focus, scroll, etc.)
508
    pub node_moves: Vec<NodeMove>,
509
}
510

            
511
/// Per-node hash of the node's own content PLUS its entire subtree, children
512
/// folded in document order. Two equal values mean the subtrees are
513
/// content-identical for reconciliation purposes — the strong-identity tier
514
/// `reconcile_dom` uses before falling back to positional matching.
515
///
516
/// The arena is depth-first pre-order (a parent's index is always lower than
517
/// its children's), so one REVERSE walk sees every child before its parent.
518
3702
fn compute_subtree_hashes(node_data: &[NodeData], hierarchy: &[NodeHierarchyItem]) -> Vec<u64> {
519
    use core::hash::{Hash, Hasher};
520
3702
    let mut hashes = vec![0u64; node_data.len()];
521
63629
    for idx in (0..node_data.len()).rev() {
522
63629
        let mut h = crate::hash::DefaultHasher::new();
523
63629
        node_data[idx].calculate_node_data_hash().hash(&mut h);
524
63629
        let mut child = hierarchy
525
63629
            .get(idx)
526
63629
            .and_then(|item| item.first_child_id(NodeId::new(idx)));
527
76581
        while let Some(c) = child {
528
12952
            if c.index() >= hashes.len() {
529
                break;
530
12952
            }
531
12952
            hashes[c.index()].hash(&mut h);
532
12952
            child = hierarchy
533
12952
                .get(c.index())
534
12952
                .and_then(NodeHierarchyItem::next_sibling_id);
535
        }
536
63629
        hashes[idx] = h.finish();
537
    }
538
3702
    hashes
539
3702
}
540

            
541
/// Calculates the difference between two DOM frames and generates lifecycle events.
542
///
543
/// This is the main entry point for DOM reconciliation. It compares the old and new
544
/// DOM trees and produces:
545
/// - Mount events for new nodes
546
/// - Unmount events for removed nodes
547
/// - Resize events for nodes whose bounds changed
548
/// - Update events for nodes whose logical position is stable but content changed
549
///
550
/// # Matching priority
551
/// For every node, the reconciliation key (`calculate_reconciliation_key`) encodes
552
/// Priority 1 (`.with_key()`), Priority 2 (CSS ID), and Priority 3 (structural key:
553
/// nth-of-type + parent key). The tiers are then tried in order:
554
///
555
/// 1. **Reconciliation key** — matches logical identity, may fire Update on content change.
556
/// 2. **Content hash** — exact match including content; catches pure reorders of anonymous nodes.
557
/// 3. **Structural hash** — matches node type + attrs ignoring text content; for text-edit cases.
558
///
559
/// # Arguments
560
/// * `old_node_data` / `new_node_data` - Per-node data for each frame
561
/// * `old_hierarchy` / `new_hierarchy` - Parent/sibling pointers. Pass `&[]` if unavailable; the
562
///   structural-key branch of the reconciliation key degrades gracefully.
563
/// * `old_layout` / `new_layout` - Layout bounds used to detect Resize events
564
/// * `dom_id` - The DOM identifier
565
/// * `timestamp` - Current timestamp for events
566
#[allow(clippy::needless_pass_by_value)] // owned azul value taken by value (public API / ownership-transfer convention)
567
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose parser/builder/dispatch (one branch per input variant)
568
#[must_use]
569
1851
pub fn reconcile_dom(
570
1851
    old_node_data: &[NodeData],
571
1851
    new_node_data: &[NodeData],
572
1851
    old_hierarchy: &[NodeHierarchyItem],
573
1851
    new_hierarchy: &[NodeHierarchyItem],
574
1851
    old_layout: &OrderedMap<NodeId, LogicalRect>,
575
1851
    new_layout: &OrderedMap<NodeId, LogicalRect>,
576
1851
    dom_id: DomId,
577
1851
    timestamp: Instant,
578
1851
) -> DiffResult {
579
    // Helper: pop the first non-consumed NodeId from a queue.
580
21501
    fn pop_first_unconsumed(queue: &mut VecDeque<NodeId>, consumed: &[bool]) -> Option<NodeId> {
581
22524
        while let Some(&old_id) = queue.front() {
582
21567
            queue.pop_front();
583
21567
            if !consumed[old_id.index()] {
584
20544
                return Some(old_id);
585
1023
            }
586
        }
587
957
        None
588
21501
    }
589

            
590
1851
    let mut result = DiffResult::default();
591

            
592
    // --- STEP 1: INDEX THE OLD DOM ---
593
    //
594
    // Three tiers, in priority order:
595
    //   Tier 1: reconciliation key (.with_key() / CSS ID / structural key)
596
    //   Tier 2: content hash (exact node_data hash — matches pure reorders)
597
    //   Tier 3: structural hash (discriminant + attrs, ignores text — matches text edits)
598
    //
599
    // Each tier is keyed with a `VecDeque<NodeId>` because all three can legitimately
600
    // collide (two sibling divs produce the same structural key, two identical nodes
601
    // produce the same content hash, etc.); we consume in document order on match.
602

            
603
1851
    let old_rec_keys = precompute_reconciliation_keys(old_node_data, old_hierarchy);
604
    // AUDIT: precompute NEW keys too so the Tier-2/Tier-3 keyless tiers can be
605
    // gated on parent-key agreement (see STEP 2). Also lets Tier 1 look the key
606
    // up instead of recomputing it per node.
607
1851
    let new_rec_keys = precompute_reconciliation_keys(new_node_data, new_hierarchy);
608

            
609
    // Reconciliation key of a node's PARENT (`None` for a root or when the
610
    // hierarchy is unavailable). Used to keep keyless matches from migrating
611
    // focus/scroll/dataset state across different parents.
612
2703
    let old_parent_key = |old_id: NodeId| -> Option<u64> {
613
1408
        old_hierarchy
614
1408
            .get(old_id.index())
615
1408
            .and_then(NodeHierarchyItem::parent_id)
616
1408
            .map(|p| old_rec_keys[p.index()])
617
1408
    };
618

            
619
1851
    let mut old_by_rec_key: OrderedMap<u64, VecDeque<NodeId>> = OrderedMap::default();
620
1851
    let mut old_hashed: OrderedMap<DomNodeHash, VecDeque<NodeId>> = OrderedMap::default();
621
1851
    let mut old_structural: OrderedMap<DomNodeHash, VecDeque<NodeId>> = OrderedMap::default();
622
1851
    let mut old_nodes_consumed = vec![false; old_node_data.len()];
623

            
624
31361
    for (idx, node) in old_node_data.iter().enumerate() {
625
31361
        let id = NodeId::new(idx);
626
31361
        old_by_rec_key
627
31361
            .entry(old_rec_keys[idx])
628
31361
            .or_default()
629
31361
            .push_back(id);
630
31361

            
631
31361
        let hash = node.calculate_node_data_hash();
632
31361
        old_hashed.entry(hash).or_default().push_back(id);
633
31361

            
634
31361
        let structural_hash = node.calculate_structural_hash();
635
31361
        old_structural
636
31361
            .entry(structural_hash)
637
31361
            .or_default()
638
31361
            .push_back(id);
639
31361
    }
640

            
641
    // --- STEP 2: CLAIM MATCHES, STRONG IDENTITY BEFORE POSITIONAL ---
642
    //
643
    // The old single loop ran every tier per new node, in new-document order.
644
    // That let a PREPENDED subtree steal identity: the auto "structural"
645
    // reconciliation key hashes an nth-of-type sibling index, so prepending a
646
    // banner shifts every following sibling's key by one and Tier 1 pairs
647
    // banner↔page0, page0↔page1, … — and (DomId, NodeId)-keyed state (text
648
    // overlay, focus, selections) follows the WRONG element. Shallow
649
    // content-hash tiers cannot save it either: a wrapper div's own hash
650
    // ignores the child text that actually distinguishes it.
651
    //
652
    // So matching now runs in PASSES over all new nodes, strongest evidence
653
    // first, positional evidence last:
654
    //   A1: terminal identity (explicit `.with_key()` / CSS ID)
655
    //   A2: exact SUBTREE hash (node + entire subtree content-identical) —
656
    //       deliberately NOT parent-gated: re-pagination moves a paragraph's
657
    //       whole subtree under a different page container, and following it
658
    //       there is the point.
659
    //   B1: positional structural key (the old Tier 1 fallback)
660
    //   B2: shallow content hash   (parent-gated, as before)
661
    //   B3: shallow structural hash (parent-gated, as before — text edits)
662
1851
    let old_subtree_hashes = compute_subtree_hashes(old_node_data, old_hierarchy);
663
1851
    let new_subtree_hashes = compute_subtree_hashes(new_node_data, new_hierarchy);
664
1851
    let mut old_by_subtree: OrderedMap<u64, VecDeque<NodeId>> = OrderedMap::default();
665
31361
    for (idx, h) in old_subtree_hashes.iter().enumerate() {
666
31361
        old_by_subtree
667
31361
            .entry(*h)
668
31361
            .or_default()
669
31361
            .push_back(NodeId::new(idx));
670
31361
    }
671

            
672
32268
    let has_terminal_identity = |node: &NodeData| -> bool {
673
32268
        node.get_key().is_some()
674
32091
            || node
675
32091
                .attributes()
676
32091
                .as_ref()
677
32091
                .iter()
678
32091
                .any(|attr| attr.as_id().is_some())
679
32268
    };
680

            
681
1851
    let n_new = new_node_data.len();
682
1851
    let mut matched: Vec<Option<NodeId>> = vec![None; n_new];
683
1851
    let mut matched_by_rec_key: Vec<bool> = vec![false; n_new];
684

            
685
    // Pass A1: terminal identity (explicit key / CSS ID). Their reconciliation
686
    // key IS the terminal key, so the existing queue serves them.
687
32268
    for (new_idx, new_node) in new_node_data.iter().enumerate() {
688
32268
        if !has_terminal_identity(new_node) {
689
12612
            continue;
690
19656
        }
691
19656
        if let Some(queue) = old_by_rec_key.get_mut(&new_rec_keys[new_idx]) {
692
19338
            if let Some(old_id) = pop_first_unconsumed(queue, &old_nodes_consumed) {
693
19338
                old_nodes_consumed[old_id.index()] = true;
694
19338
                matched[new_idx] = Some(old_id);
695
19338
                matched_by_rec_key[new_idx] = true;
696
19338
            }
697
318
        }
698
    }
699

            
700
    // Pass A2: exact subtree identity. An explicit `.with_key()` that missed
701
    // A1 stays unmatched (Mount) — a key is an intentional identity marker.
702
    // Identical twins (equal subtrees) consume in document order, which is
703
    // the same positional tie-break they got before.
704
    //
705
    // Cross-parent moves are ALLOWED between anonymous parents (that is the
706
    // point: re-pagination shifts a paragraph's whole subtree under a
707
    // different page container and state must follow it) — but NOT across a
708
    // parent whose TERMINAL identity (explicit key / CSS ID) changed:
709
    // `#left → #right` is the author saying "a different container", and the
710
    // parent-key-gate test pins that a leaf must not migrate across it.
711
12131
    let terminal_key_of = |node: &NodeData| -> Option<u64> {
712
        use core::hash::{Hash, Hasher};
713
11157
        if let Some(key) = node.get_key() {
714
            return Some(key);
715
11157
        }
716
11157
        for attr in node.attributes().as_ref() {
717
800
            if let Some(id) = attr.as_id() {
718
699
                let mut hasher = crate::hash::DefaultHasher::new();
719
699
                id.hash(&mut hasher);
720
699
                return Some(hasher.finish());
721
101
            }
722
        }
723
10458
        None
724
11157
    };
725
7413
    let old_parent_terminal = |old_id: NodeId| -> Option<u64> {
726
7413
        old_hierarchy
727
7413
            .get(old_id.index())
728
7413
            .and_then(NodeHierarchyItem::parent_id)
729
7413
            .and_then(|p| terminal_key_of(&old_node_data[p.index()]))
730
7413
    };
731
32268
    for new_idx in 0..n_new {
732
32268
        if matched[new_idx].is_some() || new_node_data[new_idx].get_key().is_some() {
733
19358
            continue;
734
12910
        }
735
12910
        let new_parent_terminal: Option<u64> = new_hierarchy
736
12910
            .get(new_idx)
737
12910
            .and_then(NodeHierarchyItem::parent_id)
738
12910
            .and_then(|p| terminal_key_of(&new_node_data[p.index()]));
739
12910
        if let Some(queue) = old_by_subtree.get_mut(&new_subtree_hashes[new_idx]) {
740
7413
            if let Some(pos) = queue.iter().position(|&old_id| {
741
7413
                !old_nodes_consumed[old_id.index()]
742
7413
                    && old_parent_terminal(old_id) == new_parent_terminal
743
7413
            }) {
744
7397
                if let Some(old_id) = queue.remove(pos) {
745
7397
                    old_nodes_consumed[old_id.index()] = true;
746
7397
                    matched[new_idx] = Some(old_id);
747
7397
                }
748
12
            }
749
5501
        }
750
    }
751

            
752
    // Pass B1: positional structural key — the old Tier 1 for keyless nodes,
753
    // now running only for what strong evidence left over.
754
32268
    for (new_idx, new_node) in new_node_data.iter().enumerate() {
755
32268
        if matched[new_idx].is_some() || new_node.get_key().is_some() {
756
26755
            continue;
757
5513
        }
758
5513
        if let Some(queue) = old_by_rec_key.get_mut(&new_rec_keys[new_idx]) {
759
2163
            if let Some(old_id) = pop_first_unconsumed(queue, &old_nodes_consumed) {
760
1206
                old_nodes_consumed[old_id.index()] = true;
761
1206
                matched[new_idx] = Some(old_id);
762
1206
                matched_by_rec_key[new_idx] = true;
763
1290
            }
764
3350
        }
765
    }
766

            
767
    // Passes B2/B3: shallow content / structural hash.
768
32268
    for (new_idx, new_node) in new_node_data.iter().enumerate() {
769
32268
        if matched[new_idx].is_some() || new_node.get_key().is_some() {
770
27961
            continue;
771
4307
        }
772
        // AUDIT: parent-key of the new node. The keyless shallow tiers are
773
        // only allowed to claim an old node whose parent's reconciliation key
774
        // agrees — otherwise two structurally-identical nodes under DIFFERENT
775
        // parents would match and migrate focus/scroll/dataset state to an
776
        // unrelated subtree. When either hierarchy is unavailable this is
777
        // `None` on both sides, so the gate is a no-op.
778
4307
        let new_parent_key: Option<u64> = new_hierarchy
779
4307
            .get(new_idx)
780
4307
            .and_then(NodeHierarchyItem::parent_id)
781
4307
            .map(|p| new_rec_keys[p.index()]);
782

            
783
        // B2: Content hash (exact match — catches pure reorders)
784
4307
        let hash = new_node.calculate_node_data_hash();
785
4307
        if let Some(queue) = old_hashed.get_mut(&hash) {
786
2385
            if let Some(pos) = queue.iter().position(|&old_id| {
787
2385
                !old_nodes_consumed[old_id.index()] && old_parent_key(old_id) == new_parent_key
788
2385
            }) {
789
228
                if let Some(old_id) = queue.remove(pos) {
790
228
                    old_nodes_consumed[old_id.index()] = true;
791
228
                    matched[new_idx] = Some(old_id);
792
228
                    continue;
793
                }
794
577
            }
795
3502
        }
796

            
797
        // B3: Structural hash (text-node fallback — ignores text content)
798
4079
        let structural_hash = new_node.calculate_structural_hash();
799
4079
        if let Some(queue) = old_structural.get_mut(&structural_hash) {
800
3885
            if let Some(pos) = queue.iter().position(|&old_id| {
801
3885
                !old_nodes_consumed[old_id.index()] && old_parent_key(old_id) == new_parent_key
802
3885
            }) {
803
                if let Some(old_id) = queue.remove(pos) {
804
                    old_nodes_consumed[old_id.index()] = true;
805
                    matched[new_idx] = Some(old_id);
806
                }
807
896
            }
808
3183
        }
809
    }
810

            
811
    // --- STEP 3: PROCESS MATCHES / MOUNTS, in new-document order ---
812

            
813
32268
    for (new_idx, new_node) in new_node_data.iter().enumerate() {
814
32268
        let new_id = NodeId::new(new_idx);
815
32268
        let matched_old_id = matched[new_idx];
816
32268
        let matched_by_rec_key = matched_by_rec_key[new_idx];
817

            
818
32268
        if let Some(old_id) = matched_old_id {
819
            // FOUND A MATCH (It might be at a different index, but it's the "same" node)
820

            
821
28169
            result.node_moves.push(NodeMove {
822
28169
                old_node_id: old_id,
823
28169
                new_node_id: new_id,
824
28169
            });
825

            
826
            // Check for Resize
827
28169
            let old_rect = old_layout
828
28169
                .get(&old_id)
829
28169
                .copied()
830
28169
                .unwrap_or(LogicalRect::zero());
831
28169
            let new_rect = new_layout
832
28169
                .get(&new_id)
833
28169
                .copied()
834
28169
                .unwrap_or(LogicalRect::zero());
835

            
836
28169
            if old_rect.size != new_rect.size {
837
                // Fire Resize Event
838
22
                if has_resize_callback(new_node) {
839
22
                    result.events.push(create_lifecycle_event(
840
22
                        EventType::Resize,
841
22
                        new_id,
842
22
                        dom_id,
843
22
                        &timestamp,
844
22
                        LifecycleEventData {
845
22
                            reason: LifecycleReason::Resize,
846
22
                            previous_bounds: Some(old_rect),
847
22
                            current_bounds: new_rect,
848
22
                        },
849
22
                    ));
850
22
                }
851
28147
            }
852

            
853
            // Fire Update when the node was matched by logical identity (reconciliation
854
            // key: explicit .with_key(), CSS ID, or structural key) but its content hash
855
            // differs. Tier-2/Tier-3 matches by definition don't carry an Update — a
856
            // content-hash match is content-identical, and a structural-hash match is
857
            // a text edit handled by cursor/text reconciliation elsewhere.
858
28169
            if matched_by_rec_key {
859
20544
                let old_hash = old_node_data[old_id.index()].calculate_node_data_hash();
860
20544
                let new_hash = new_node.calculate_node_data_hash();
861

            
862
20544
                if old_hash != new_hash && has_update_callback(new_node) {
863
20
                    result.events.push(create_lifecycle_event(
864
20
                        EventType::Update,
865
20
                        new_id,
866
20
                        dom_id,
867
20
                        &timestamp,
868
20
                        LifecycleEventData {
869
20
                            reason: LifecycleReason::Update,
870
20
                            previous_bounds: Some(old_rect),
871
20
                            current_bounds: new_rect,
872
20
                        },
873
20
                    ));
874
20524
                }
875
7625
            }
876
        } else {
877
            // NO MATCH FOUND -> MOUNT (New Node)
878
4099
            if has_mount_callback(new_node) {
879
50
                let bounds = new_layout
880
50
                    .get(&new_id)
881
50
                    .copied()
882
50
                    .unwrap_or(LogicalRect::zero());
883
50
                result.events.push(create_lifecycle_event(
884
50
                    EventType::Mount,
885
50
                    new_id,
886
50
                    dom_id,
887
50
                    &timestamp,
888
50
                    LifecycleEventData {
889
50
                        reason: LifecycleReason::InitialMount,
890
50
                        previous_bounds: None,
891
50
                        current_bounds: bounds,
892
50
                    },
893
50
                ));
894
4058
            }
895
        }
896
    }
897

            
898
    // --- STEP 4: CLEANUP (UNMOUNTS) ---
899
    // Any old node that wasn't claimed is effectively destroyed.
900

            
901
31361
    for (old_idx, consumed) in old_nodes_consumed.iter().enumerate() {
902
31361
        if !consumed {
903
3192
            let old_id = NodeId::new(old_idx);
904
3192
            let old_node = &old_node_data[old_idx];
905

            
906
3192
            if has_unmount_callback(old_node) {
907
50
                let bounds = old_layout
908
50
                    .get(&old_id)
909
50
                    .copied()
910
50
                    .unwrap_or(LogicalRect::zero());
911
50
                result.events.push(create_lifecycle_event(
912
50
                    EventType::Unmount,
913
50
                    old_id,
914
50
                    dom_id,
915
50
                    &timestamp,
916
50
                    LifecycleEventData {
917
50
                        reason: LifecycleReason::Unmount,
918
50
                        previous_bounds: Some(bounds),
919
50
                        current_bounds: LogicalRect::zero(),
920
50
                    },
921
50
                ));
922
3152
            }
923
28169
        }
924
    }
925

            
926
1851
    result
927
1851
}
928

            
929
/// Creates a lifecycle event with all necessary fields.
930
143
fn create_lifecycle_event(
931
143
    event_type: EventType,
932
143
    node_id: NodeId,
933
143
    dom_id: DomId,
934
143
    timestamp: &Instant,
935
143
    data: LifecycleEventData,
936
143
) -> SyntheticEvent {
937
143
    let dom_node_id = DomNodeId {
938
143
        dom: dom_id,
939
143
        node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
940
143
    };
941
143
    SyntheticEvent {
942
143
        event_type,
943
143
        source: EventSource::Lifecycle,
944
143
        phase: EventPhase::Target,
945
143
        target: dom_node_id,
946
143
        current_target: dom_node_id,
947
143
        timestamp: timestamp.clone(),
948
143
        data: EventData::Lifecycle(data),
949
143
        stopped: false,
950
143
        stopped_immediate: false,
951
143
        prevented_default: false,
952
143
        at_target_only: false,
953
143
    }
954
143
}
955

            
956
/// The event a `<transient-window>` receives when the USER closed it — an
957
/// outside click, or Escape — as opposed to the app flipping `open`.
958
///
959
/// Built here, next to the other lifecycle events, so it carries the same
960
/// `EventSource::Lifecycle` / `EventPhase::Target` shape the dispatcher
961
/// expects for a `ComponentEventFilter`. `bounds` is the popup's anchor
962
/// rect in the parent, the closest thing to "where it was".
963
#[must_use]
964
pub fn create_dismiss_event(
965
    node_id: NodeId,
966
    dom_id: DomId,
967
    timestamp: &Instant,
968
    bounds: LogicalRect,
969
) -> SyntheticEvent {
970
    create_lifecycle_event(
971
        EventType::Dismiss,
972
        node_id,
973
        dom_id,
974
        timestamp,
975
        LifecycleEventData {
976
            reason: LifecycleReason::Dismiss,
977
            previous_bounds: None,
978
            current_bounds: bounds,
979
        },
980
    )
981
}
982

            
983
/// The lifecycle event a `<transient-window>` gets on a tear-off or a dock.
984
///
985
/// `torn == true`: torn off its anchor (`bounds` = the toplevel's rect in the
986
/// parent). `torn == false`: docked back (`bounds` = the anchor it docked onto).
987
#[must_use]
988
pub fn create_tearoff_event(
989
    node_id: NodeId,
990
    dom_id: DomId,
991
    timestamp: &Instant,
992
    torn: bool,
993
    bounds: LogicalRect,
994
) -> SyntheticEvent {
995
    let (ty, reason) = if torn {
996
        (EventType::TearOff, LifecycleReason::TearOff)
997
    } else {
998
        (EventType::Dock, LifecycleReason::Dock)
999
    };
    create_lifecycle_event(
        ty,
        node_id,
        dom_id,
        timestamp,
        LifecycleEventData {
            reason,
            previous_bounds: None,
            current_bounds: bounds,
        },
    )
}
/// Check if the node has an `AfterMount` callback registered.
4107
fn has_mount_callback(node: &NodeData) -> bool {
4107
    node.get_callbacks().iter().any(|cb| {
8
        matches!(
59
            cb.event,
            EventFilter::Component(ComponentEventFilter::AfterMount)
        )
59
    })
4107
}
/// Check if the node has a `BeforeUnmount` callback registered.
3199
fn has_unmount_callback(node: &NodeData) -> bool {
3199
    node.get_callbacks().iter().any(|cb| {
5
        matches!(
56
            cb.event,
            EventFilter::Component(ComponentEventFilter::BeforeUnmount)
        )
56
    })
3199
}
/// Check if the node has a `NodeResized` callback registered.
30
fn has_resize_callback(node: &NodeData) -> bool {
31
    node.get_callbacks().iter().any(|cb| {
7
        matches!(
31
            cb.event,
            EventFilter::Component(ComponentEventFilter::NodeResized)
        )
31
    })
30
}
/// Check if the node has any lifecycle callback that would respond to updates.
518
fn has_update_callback(node: &NodeData) -> bool {
518
    node.get_callbacks().iter().any(|cb| {
160
        matches!(
85
            cb.event,
            EventFilter::Component(ComponentEventFilter::Updated)
        )
181
    })
518
}
/// Migrate state (focus, scroll, etc.) from old node IDs to new node IDs.
///
/// This function should be called after reconciliation to update any state
/// that references old `NodeIds` to use the new `NodeIds`.
///
/// # Example
/// ```rust,ignore
/// let diff = reconcile_dom(...);
/// let migration_map = create_migration_map(&diff.node_moves);
///
/// // Migrate focus
/// if let Some(current_focus) = focus_manager.focused_node {
///     if let Some(&new_id) = migration_map.get(&current_focus) {
///         focus_manager.focused_node = Some(new_id);
///     } else {
///         // Focused node was unmounted, clear focus
///         focus_manager.focused_node = None;
///     }
/// }
/// ```
#[must_use]
138
pub fn create_migration_map(node_moves: &[NodeMove]) -> OrderedMap<NodeId, NodeId> {
138
    let mut map = OrderedMap::default();
1357
    for m in node_moves {
1219
        map.insert(m.old_node_id, m.new_node_id);
1219
    }
138
    map
138
}
/// Suppression tag for the image-churn lint, honored from `AZ_SUPPRESS`.
pub const IMAGE_CHURN_SUPPRESS_TAG: &str = "image_churn";
/// Re-initialisations per second above which an image node is churning.
///
/// A widget legitimately rebuilds its image node with a placeholder now and
/// then — the first build after mount has no frame yet. Doing it dozens of
/// times a second means a LIVE image is being discarded and re-awaited on every
/// frame, which is a bug in how the node is built, not in the content.
const IMAGE_CHURN_PER_SEC: u32 = 10;
/// The framework notices, by itself, when an image node re-initialises at frame
/// rate — and says what is almost always wrong.
///
/// The symptom is a video or capture node that flickers: it holds a real frame,
/// the DOM rebuilds, the fresh node carries only a placeholder, and the live
/// image is thrown away until the next frame arrives 16-33ms later. On a
/// resizing window, which rebuilds continuously, that is a continuous flash.
///
/// The cause is almost always a missing DATASET + merge callback. Without one
/// the reconciler cannot tell that the rebuilt node is the same widget, so it
/// has nothing to carry forward — see `transfer_states`, which does carry the
/// previous frame when a merge callback exists.
///
/// Detection lives HERE, in the reconciler, because neither DOM shows it alone:
/// the old build has a frame, the new build has a placeholder, and only the
/// pair reveals the churn. No user code has to opt in.
/// Per-node churn bookkeeping: `(count, window_start, warned)`.
///
/// Shared with the tests so the detector can be asserted on directly, instead
/// of only through a message on stderr that nothing can observe.
#[cfg(feature = "std")]
type ImageChurnMap = BTreeMap<usize, (u32, std::time::Instant, bool)>;
#[cfg(feature = "std")]
7
fn image_churn_state() -> &'static std::sync::Mutex<ImageChurnMap> {
    use std::sync::{Mutex, OnceLock};
    static CHURN: OnceLock<Mutex<ImageChurnMap>> = OnceLock::new();
7
    CHURN.get_or_init(|| Mutex::new(ImageChurnMap::new()))
7
}
/// How many times this node has re-initialised inside the current window.
#[cfg(all(feature = "std", test))]
2
pub(crate) fn image_churn_count(node_index: usize) -> u32 {
2
    image_churn_state()
2
        .lock()
2
        .ok()
2
        .and_then(|m| m.get(&node_index).map(|e| e.0))
2
        .unwrap_or(0)
2
}
#[cfg(feature = "std")]
5
fn note_image_reinitialised(node_index: usize, carried: bool) {
    use std::{
        collections::BTreeMap,
        sync::{Mutex, OnceLock},
        time::Instant,
    };
    static SUPPRESSED: OnceLock<bool> = OnceLock::new();
5
    if *SUPPRESSED.get_or_init(|| {
1
        let v = std::env::var("AZ_SUPPRESS")
1
            .or_else(|_| std::env::var("AZ_SUPRESS"))
1
            .unwrap_or_default();
1
        v.split(',')
1
            .any(|t| t.trim().eq_ignore_ascii_case(IMAGE_CHURN_SUPPRESS_TAG))
1
    }) {
        return;
5
    }
    // Per node: how many times it re-initialised, when that window started, and
    // whether we have already said so. "The time it was last updated and how
    // much" is the whole state — no history, no allocation per event.
5
    let churn = image_churn_state();
5
    let Ok(mut map) = churn.lock() else {
        return; // a poisoned lint counter must never take the app down
    };
5
    let now = Instant::now();
5
    let entry = map.entry(node_index).or_insert((0, now, false));
5
    if now.duration_since(entry.1).as_secs_f32() >= 1.0 {
        *entry = (1, now, entry.2);
        return;
5
    }
5
    entry.0 += 1;
    // Warn once per node. This runs on every rebuild of a resizing window; a
    // warning per frame would bury the message it is trying to deliver.
5
    if entry.0 < IMAGE_CHURN_PER_SEC || entry.2 {
5
        return;
    }
    entry.2 = true;
    let rate = entry.0;
    if carried {
        crate::diagnostics::emit(format!(
            "[azul][image-churn] node {node_index} rebuilt its image as a PLACEHOLDER {rate}x in \
             one second. The previous frame was carried forward each time, so nothing flickers — \
             but a live image node is being reconstructed every frame. If this is not a capture \
             widget, build the node once and update it through the image cache. (suppress with \
             AZ_SUPPRESS={IMAGE_CHURN_SUPPRESS_TAG})"
        ));
    } else {
        crate::diagnostics::emit(format!(
            "[azul][image-churn] node {node_index} rebuilt its image as a PLACEHOLDER {rate}x in \
             one second and the previous frame could NOT be carried forward: this node has NO \
             DATASET + merge callback, so the reconciler cannot tell the rebuilt node is the same \
             widget. The live image is discarded every frame and the node falls back to its \
             placeholder until the next one arrives — a continuous flicker. If this is a video or \
             camera node, it is almost certainly missing its dataset: attach one with a \
             DatasetMergeCallback (see MapWidget / ScreenCaptureWidget). (suppress with \
             AZ_SUPPRESS={IMAGE_CHURN_SUPPRESS_TAG})"
        ));
    }
5
}
#[cfg(not(feature = "std"))]
fn note_image_reinitialised(_node_index: usize, _carried: bool) {}
/// Executes state migration between the old DOM and the new DOM based on diff results.
///
/// This iterates through matched nodes. If a match has BOTH a merge callback AND a dataset,
/// it executes the callback to transfer state from the old node to the new node.
///
/// This must be called **before** the old DOM is dropped, because we need to access its data.
///
/// # Arguments
/// * `old_node_data` - Mutable reference to the old DOM's node data (source of heavy state)
/// * `new_node_data` - Mutable reference to the new DOM's node data (target for heavy state)
/// * `node_moves` - The matched nodes from the reconciliation diff
///
/// # Example
/// ```rust,ignore
/// let diff_result = reconcile_dom(&old_data, &new_data, ...);
///
/// // Execute state migration BEFORE old_dom is dropped
/// transfer_states(&mut old_data, &mut new_data, &diff_result.node_moves);
///
/// // Now safe to drop old_dom - heavy resources have been transferred
/// drop(old_dom);
/// ```
294
pub fn transfer_states(
294
    old_node_data: &mut [NodeData],
294
    new_node_data: &mut [NodeData],
294
    node_moves: &[NodeMove],
294
) {
    use crate::refany::OptionRefAny;
849
    for movement in node_moves {
555
        let old_idx = movement.old_node_id.index();
555
        let new_idx = movement.new_node_id.index();
        // Bounds check
555
        if old_idx >= old_node_data.len() || new_idx >= new_node_data.len() {
22
            continue;
533
        }
        // 1. Check if the NEW node has requested a merge callback
533
        let Some(merge_callback) = new_node_data[new_idx].get_merge_callback() else {
            // No merge callback — nothing can be carried forward. If this node
            // is an image that just reverted to a placeholder while the old
            // build held a real frame, that live frame is being DISCARDED, and
            // at frame rate it is a visible flicker. This is the "forgot the
            // dataset on a video node" case, and the framework can see it
            // without anyone asking.
347
            if new_node_data[new_idx].image_is_placeholder()
4
                && !old_node_data[old_idx].image_is_placeholder()
4
            {
4
                note_image_reinitialised(new_idx, false);
346
            }
347
            continue; // No merge callback, skip
        };
        // 2. Check if BOTH nodes have datasets
        // We need to temporarily take the datasets to satisfy borrow checker
186
        let old_dataset = old_node_data[old_idx].take_dataset();
186
        let new_dataset = new_node_data[new_idx].take_dataset();
186
        match (new_dataset, old_dataset) {
147
            (Some(new_data), Some(old_data)) => {
                // The fresh DOM's dataset allocation. A widget builds its dataset,
                // its VirtualView content `refany`, AND its event-callback
                // `refany`s from clones of ONE `RefAny` — so every one shares THIS
                // allocation (`RefAny::clone` shares `sharing_info`; only the
                // per-clone `instance_id` differs). The merge below keeps the
                // PERSISTENT (old) allocation (e.g. MapWidget shares its tile cache
                // so background fetch threads keep writing into it), so every clone
                // of the fresh one is now orphaned and must be re-pointed — or the
                // widget fragments across two caches: the VirtualView rendered an
                // empty clone (blank/grey tiles) while the live data sat in the
                // dataset, and pan/zoom mutated yet a third copy. Identity = the
                // shared `RefCountInner` pointer (`sharing_info.ptr`).
147
                let orphan_alloc = new_data.sharing_info.ptr as usize;
                // 3. EXECUTE THE MERGE CALLBACK
                // The callback receives both datasets and returns the merged result
147
                let merged = (merge_callback.cb)(new_data, old_data);
                // 3b. CARRY THE LIVE IMAGE FORWARD.
                //
                // A merge callback ran, so this is the SAME logical widget as
                // before — the reconciler matched them and the widget asked for
                // its state to persist. A capture widget rebuilds its node with
                // a PLACEHOLDER every time (`Dom::create_image(null_image)`),
                // because the fresh widget struct has no frame yet; the live
                // frame arrives later by writeback. So on every DOM rebuild the
                // node reverted to the placeholder and stayed there until the
                // next frame landed ~16-33ms later.
                //
                // That is the flash reported when resizing a window while
                // screensharing: "the screen flickers, like it is
                // re-initializing". Nothing was re-initialising — the last frame
                // was simply thrown away and re-awaited.
                //
                // NARROW ON PURPOSE: only when the NEW image is a null/
                // placeholder image and the OLD one is not. An app that
                // deliberately swaps in a real image still wins, and one that
                // deliberately clears to a placeholder is the only case this
                // changes — which is indistinguishable from "has not produced a
                // frame yet" and is what the widget itself does every rebuild.
147
                if new_node_data[new_idx].image_is_placeholder()
1
                    && !old_node_data[old_idx].image_is_placeholder()
                {
1
                    if let Some(prev) = old_node_data[old_idx].get_image_ref_cloned() {
1
                        new_node_data[new_idx].set_image_ref(prev);
1
                    }
                    // Handled — but still worth saying if it happens every
                    // frame, because rebuilding a live image node at 60 Hz is
                    // work nobody asked for.
1
                    note_image_reinitialised(new_idx, true);
146
                }
                // 4. Store the merged result back in the new node
147
                new_node_data[new_idx].set_dataset(OptionRefAny::Some(merged.clone()));
                // 5. UNIFY: re-point every refany across the NEW DOM that was a
                // clone of the now-discarded fresh dataset onto the merged result,
                // so the whole widget reads ONE cache. Covers VirtualView content
                // refanys + event-callback refanys + any node's dataset cloned
                // from the same source. (Generalises the old special-case that
                // only re-pointed a VirtualView ON the merge node itself — the
                // MapWidget puts its VirtualView in a CHILD and its pan/zoom
                // callbacks on the parent, which that case missed.)
147
                repoint_orphaned_refanys(new_node_data, orphan_alloc, &merged);
            }
39
            (new_ds, old_ds) => {
                // One or both datasets missing - restore what we had
39
                if let Some(ds) = new_ds {
20
                    new_node_data[new_idx].set_dataset(OptionRefAny::Some(ds));
20
                }
39
                if let Some(ds) = old_ds {
19
                    old_node_data[old_idx].set_dataset(OptionRefAny::Some(ds));
20
                }
            }
        }
    }
294
}
/// Re-point every `RefAny` across `node_data` that is a clone of the
/// allocation `orphan_alloc` (a dataset the merge discarded) at `merged`.
///
/// The whole widget then reads ONE state: `VirtualView` content refanys,
/// event callback refanys and datasets cloned from the same source. The
/// `MapWidget` puts its `VirtualView` in a CHILD and its pan/zoom callbacks
/// on the parent, which is why this scans the whole arena and not just the
/// merge node.
149
fn repoint_orphaned_refanys(node_data: &mut [NodeData], orphan_alloc: usize, merged: &RefAny) {
    use crate::refany::OptionRefAny;
149
    if merged.sharing_info.ptr as usize == orphan_alloc {
127
        return; // the merge kept the fresh allocation: nothing is orphaned
22
    }
23
    for nd in node_data.iter_mut() {
23
        if let Some(vv) = nd.get_virtual_view_node() {
            if vv.refany.sharing_info.ptr as usize == orphan_alloc {
                vv.refany = merged.clone();
            }
23
        }
23
        for cb in nd.callbacks.as_mut().iter_mut() {
3
            if cb.refany.sharing_info.ptr as usize == orphan_alloc {
3
                cb.refany = merged.clone();
3
            }
        }
23
        let ds_is_orphan = nd
23
            .get_dataset()
23
            .is_some_and(|ds| ds.sharing_info.ptr as usize == orphan_alloc);
23
        if ds_is_orphan {
            nd.set_dataset(OptionRefAny::Some(merged.clone()));
23
        }
    }
149
}
/// The pre-cascade fast path's half of [`transfer_states`].
///
/// When the fresh build's fingerprints equal the retained DOM's, the cascade
/// is skipped and the retained `StyledDom` is kept; the fresh build's event
/// callbacks are installed on it (they may reference new app state). That
/// left the DATASETS behind: the fresh callbacks' `RefAny`s were clones of
/// the fresh build's dataset, the retained node kept last frame's, and no
/// merge callback ever ran — so a `RefreshDom` that rebuilt an identical DOM
/// reset every stateful widget's callback state (a slider's drag died on its
/// second move) and split the widget across two allocations, the exact
/// fragmentation [`repoint_orphaned_refanys`] exists to prevent.
///
/// Same rules as `transfer_states`, with the retained node as "old" and the
/// fresh dataset as "new": merge through the node's merge callback when it
/// has one, otherwise the fresh dataset wins; then re-point everything on the
/// retained DOM that was a clone of the fresh dataset at the result. Call it
/// AFTER the fresh callbacks have been installed on `node_data`, once per
/// fresh dataset, with `idx` the node's flattened index.
3
pub fn merge_fresh_dataset(node_data: &mut [NodeData], idx: usize, fresh: RefAny) {
    use crate::refany::OptionRefAny;
3
    let Some(nd) = node_data.get_mut(idx) else {
1
        return;
    };
2
    let orphan_alloc = fresh.sharing_info.ptr as usize;
2
    let merge_callback = nd.get_merge_callback();
2
    let retained = nd.take_dataset();
2
    let result = match (merge_callback, retained) {
1
        (Some(cb), Some(old)) => (cb.cb)(fresh, old),
1
        _ => fresh,
    };
2
    nd.set_dataset(OptionRefAny::Some(result.clone()));
2
    repoint_orphaned_refanys(node_data, orphan_alloc, &result);
3
}
/// Calculate a stable key for a contenteditable node using the hierarchy:
///
/// 1. **Explicit Key** - If `.with_key()` was called, use that
/// 2. **CSS ID** - If the node has a CSS ID (e.g., `#my-editor`), hash that
/// 3. **Structural Key** - Hash of `(nth-of-type, parent_key)` recursively
///
/// The structural key prevents shifting when elements are inserted before siblings.
/// For example, in `<div><p>A</p><p contenteditable>B</p></div>`, if we insert
/// a new `<p>` at the start, the contenteditable `<p>` becomes nth-child(3) but
/// its nth-of-type stays stable (it's still the 2nd `<p>`).
///
/// # Arguments
/// * `node_data` - All nodes in the DOM
/// * `hierarchy` - Parent-child relationships
/// * `node_id` - The node to calculate the key for
///
/// # Returns
/// A stable u64 key for the node
#[must_use]
912
pub fn calculate_contenteditable_key(
912
    node_data: &[NodeData],
912
    hierarchy: &[NodeHierarchyItem],
912
    node_id: NodeId,
912
) -> u64 {
    use core::hash::Hasher;
912
    let n = node_data.len();
    // Terminal (parent-independent) key: Priority 1 explicit key, else
    // Priority 2 CSS ID, else `None` (structural — needs the parent chain).
101841
    let terminal_key = |nid: NodeId| -> Option<u64> {
101841
        let node = &node_data[nid.index()];
        // Priority 1: Explicit key (from .with_key())
101841
        if let Some(explicit_key) = node.get_key() {
2
            return Some(explicit_key);
101839
        }
        // Priority 2: CSS ID
101839
        for attr in node.attributes().as_ref() {
629
            if let Some(id) = attr.as_id() {
14
                let mut hasher = crate::hash::DefaultHasher::new(); // Different seed for ID keys
14
                hasher.write(id.as_bytes());
14
                return Some(hasher.finish());
615
            }
        }
101825
        None
101841
    };
    // Fast path: the node itself has an explicit key or CSS ID.
912
    if let Some(key) = terminal_key(node_id) {
15
        return key;
897
    }
    // Priority 3: structural key, computed ITERATIVELY up the parent chain.
    //
    // AUDIT: replaces unbounded parent-chain recursion (stack overflow on deep
    // DOMs, infinite recursion on a cyclic hierarchy). Same fold as the old
    // recursion, unrolled bottom-up and bounded by the node count.
897
    let mut chain: Vec<NodeId> = Vec::new();
897
    let mut seed_parent_key: Option<u64> = None;
897
    let mut cur = node_id;
897
    for _ in 0..n {
101824
        if cur.index() >= n {
            break;
101824
        }
101824
        chain.push(cur);
101824
        match hierarchy
101824
            .get(cur.index())
101824
            .and_then(NodeHierarchyItem::parent_id)
        {
895
            None => break,
100929
            Some(parent) => {
100929
                if let Some(k) = terminal_key(parent) {
1
                    seed_parent_key = Some(k);
1
                    break;
100928
                }
100928
                cur = parent;
            }
        }
    }
    // Fold from the topmost ancestor down to `node_id`. Unlike the
    // reconciliation key, the contenteditable structural key ALWAYS writes a
    // `parent_key` (0 at the root) and an `nth_of_type` (0 at the root), so the
    // per-level hashing is unconditional — preserve that exactly.
897
    let mut parent_key: u64 = seed_parent_key.unwrap_or(0);
101824
    for &nid in chain.iter().rev() {
101824
        let node = &node_data[nid.index()];
101824
        let mut hasher = crate::hash::DefaultHasher::new(); // Different seed for structural keys
101824
        let node_parent = hierarchy
101824
            .get(nid.index())
101824
            .and_then(NodeHierarchyItem::parent_id);
        // parent_key: 0 at the root, else the accumulated key of the level above.
101824
        let level_parent_key = if node_parent.is_some() { parent_key } else { 0 };
101824
        hasher.write(&level_parent_key.to_le_bytes());
        // nth-of-type: count same-discriminant siblings before `nid`.
101824
        let node_discriminant = core::mem::discriminant(node.get_node_type());
101824
        let nth_of_type = node_parent.map_or(0u32, |parent_id| {
100929
            let mut count = 0u32;
100929
            let mut sibling_id = hierarchy
100929
                .get(parent_id.index())
100929
                .and_then(|h| h.first_child_id(parent_id));
101362
            while let Some(sib_id) = sibling_id {
101359
                if sib_id == nid {
100926
                    break;
433
                }
433
                let sibling_discriminant =
433
                    core::mem::discriminant(node_data[sib_id.index()].get_node_type());
433
                if sibling_discriminant == node_discriminant {
433
                    count += 1;
433
                }
433
                sibling_id = hierarchy
433
                    .get(sib_id.index())
433
                    .and_then(NodeHierarchyItem::next_sibling_id);
            }
100929
            count
100929
        });
101824
        hasher.write(&nth_of_type.to_le_bytes());
        // Hash the node type discriminant (Discriminant<T> implements Hash)
101824
        node_discriminant.hash(&mut hasher);
        // Also hash the classes for additional stability
101824
        for attr in node.attributes().as_ref() {
615
            if let Some(class) = attr.as_class() {
591
                hasher.write(class.as_bytes());
591
            }
        }
101824
        parent_key = hasher.finish();
    }
897
    parent_key
912
}
/// Reconcile cursor byte position when text content changes.
///
/// This function maps a cursor position from old text to new text, preserving
/// the cursor's logical position as much as possible:
///
/// 1. If cursor is in unchanged prefix → stays at same byte offset
/// 2. If cursor is in unchanged suffix → adjusts by length difference
/// 3. If cursor is in changed region → places at end of new content
///
/// # Arguments
/// * `old_text` - The previous text content
/// * `new_text` - The new text content
/// * `old_cursor_byte` - Cursor byte offset in old text
///
/// # Returns
/// The reconciled cursor byte offset in new text
///
/// # Example
/// ```rust,ignore
/// let old_text = "Hello";
/// let new_text = "Hello World";
/// let old_cursor = 5; // cursor at end of "Hello"
/// let new_cursor = reconcile_cursor_position(old_text, new_text, old_cursor);
/// assert_eq!(new_cursor, 5); // cursor stays at same position (prefix unchanged)
/// ```
#[must_use]
2446
pub fn reconcile_cursor_position(old_text: &str, new_text: &str, old_cursor_byte: usize) -> usize {
    // AUDIT: every returned offset is snapped DOWN to the nearest UTF-8 char
    // boundary in `new_text` (and clamped to its length). The prefix/suffix
    // scans below compare byte-by-byte and can land mid-codepoint, so a raw
    // return value could later panic when used to slice `new_text` as a `str`.
2446
    let snap = |offset: usize| -> usize {
2114
        let mut o = offset.min(new_text.len());
2327
        while o > 0 && !new_text.is_char_boundary(o) {
213
            o -= 1;
213
        }
2114
        o
2114
    };
    // If texts are equal, cursor is unchanged
2446
    if old_text == new_text {
276
        return snap(old_cursor_byte);
2170
    }
    // Empty old text - place cursor at end of new text
2170
    if old_text.is_empty() {
84
        return new_text.len();
2086
    }
    // Empty new text - place cursor at 0
2086
    if new_text.is_empty() {
248
        return 0;
1838
    }
    // Find common prefix (how many bytes from the start are identical)
1838
    let common_prefix_bytes = old_text
1838
        .bytes()
1838
        .zip(new_text.bytes())
492627
        .take_while(|(a, b)| a == b)
1838
        .count();
    // If cursor was in the unchanged prefix, it stays at the same byte offset
1838
    if old_cursor_byte <= common_prefix_bytes {
262
        return snap(old_cursor_byte);
1576
    }
    // Find common suffix (how many bytes from the end are identical)
1576
    let common_suffix_bytes = old_text
1576
        .bytes()
1576
        .rev()
1576
        .zip(new_text.bytes().rev())
102093
        .take_while(|(a, b)| a == b)
1576
        .count();
    // Calculate where the suffix starts in old and new text
1576
    let old_suffix_start = old_text.len().saturating_sub(common_suffix_bytes);
1576
    let new_suffix_start = new_text.len().saturating_sub(common_suffix_bytes);
    // If cursor was in the unchanged suffix, adjust by length difference
1576
    if old_cursor_byte >= old_suffix_start {
        // saturating: an out-of-range cursor (> old_text.len()) must clamp to the
        // end of the new text like every other path here, not underflow-panic.
195
        let offset_from_end = old_text.len().saturating_sub(old_cursor_byte);
195
        return snap(new_text.len().saturating_sub(offset_from_end));
1381
    }
    // Cursor was in the changed region - place at end of inserted content
    // This handles insertions (cursor moves with new text) and deletions (cursor at edit point)
1381
    snap(new_suffix_start)
2446
}
/// Get the text content from a `NodeData` if it's a Text node.
///
/// Returns the text string if the node is `NodeType::Text`, otherwise `None`.
#[must_use]
189
pub fn get_node_text_content(node: &NodeData) -> Option<&str> {
189
    if let NodeType::Text(ref text) = node.get_node_type() {
166
        Some(text.as_str())
    } else {
23
        None
    }
189
}
// ============================================================================
// ChangeAccumulator — unifies all change input paths
// ============================================================================
/// Text change info for cursor/selection reconciliation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextChange {
    /// The text content before the change.
    pub old_text: String,
    /// The text content after the change.
    pub new_text: String,
}
/// Per-node change report combining multiple information sources.
#[derive(Debug, Clone, Default)]
pub struct NodeChangeReport {
    /// Bitflags from DOM-level field comparison.
    pub change_set: NodeChangeSet,
    /// Highest `RelayoutScope` from any CSS property that changed on this node.
    /// This is more granular than `NodeChangeSet`'s binary LAYOUT/PAINT split.
    ///
    /// - `None` → repaint only (color, opacity, transform)
    /// - `IfcOnly` → reshape text in the containing IFC
    /// - `SizingOnly` → recompute this node's intrinsic size
    /// - `Full` → full subtree relayout (display, position, float, etc.)
    pub relayout_scope: RelayoutScope,
    /// Individual CSS properties that changed (for fine-grained cache invalidation).
    /// Empty if the change was structural (text content, node type, etc.)
    pub changed_css_properties: Vec<CssPropertyType>,
    /// If text content changed, the old and new text for cursor reconciliation.
    pub text_change: Option<TextChange>,
}
impl NodeChangeReport {
    /// Returns the `DirtyFlag` level needed for this change report.
    /// Maps `RelayoutScope` + `NodeChangeSet` → a simple tri-state.
    #[must_use]
180
    pub fn needs_layout(&self) -> bool {
180
        self.change_set.needs_layout() || self.relayout_scope > RelayoutScope::None
180
    }
    #[must_use]
82
    pub const fn needs_paint(&self) -> bool {
82
        self.change_set.needs_paint()
82
    }
    #[must_use]
61
    pub fn is_visually_unchanged(&self) -> bool {
61
        self.change_set.is_visually_unchanged() && self.relayout_scope == RelayoutScope::None
61
    }
}
/// Unified change report that merges information from all three change paths:
///
/// 1. **DOM reconciliation** (`compute_node_changes` after `reconcile_dom`)
/// 2. **CSS restyle** (`restyle_on_state_change` for hover/focus/active)
/// 3. **Runtime edits** (`words_changed`, `css_properties_changed`, `images_changed`)
///
/// This is the single source of truth for "what work needs to happen this frame".
#[derive(Debug, Clone, Default)]
pub struct ChangeAccumulator {
    /// Per-node change info. Key is the new-DOM `NodeId`.
    pub per_node: BTreeMap<NodeId, NodeChangeReport>,
    /// Maximum `RelayoutScope` across all changed nodes.
    /// Quick check: if this is `None`, we can skip layout entirely.
    pub max_scope: RelayoutScope,
    /// Nodes that are newly mounted (no old counterpart).
    /// These always need full layout.
    pub mounted_nodes: Vec<NodeId>,
    /// Nodes that were unmounted (no new counterpart).
    /// Used for cleanup (remove from scroll/focus/cursor managers).
    pub unmounted_nodes: Vec<NodeId>,
}
impl ChangeAccumulator {
    #[must_use]
71
    pub fn new() -> Self {
71
        Self::default()
71
    }
    /// Returns true if no changes were detected at all.
    #[must_use]
16
    pub fn is_empty(&self) -> bool {
16
        self.per_node.is_empty() && self.mounted_nodes.is_empty() && self.unmounted_nodes.is_empty()
16
    }
    /// Returns true if layout work is needed (any node has scope > None).
    #[must_use]
369
    pub fn needs_layout(&self) -> bool {
369
        self.max_scope > RelayoutScope::None
240
            || !self.mounted_nodes.is_empty()
123
            || self.per_node.values().any(NodeChangeReport::needs_layout)
369
    }
    /// Returns true if only paint work is needed (no layout).
    #[must_use]
82
    pub fn needs_paint_only(&self) -> bool {
82
        !self.needs_layout() && self.per_node.values().any(NodeChangeReport::needs_paint)
82
    }
    /// Returns true if only non-visual changes occurred (callbacks, dataset, a11y).
    #[must_use]
140
    pub fn is_visually_unchanged(&self) -> bool {
140
        self.mounted_nodes.is_empty()
119
            && self.unmounted_nodes.is_empty()
99
            && self.max_scope == RelayoutScope::None
79
            && self
79
                .per_node
79
                .values()
79
                .all(NodeChangeReport::is_visually_unchanged)
140
    }
    /// Add a node change from DOM reconciliation (Path A).
99
    pub fn add_dom_change(
99
        &mut self,
99
        new_node_id: NodeId,
99
        change_set: NodeChangeSet,
99
        relayout_scope: RelayoutScope,
99
        text_change: Option<TextChange>,
99
        changed_css_properties: Vec<CssPropertyType>,
99
    ) {
99
        if relayout_scope > self.max_scope {
79
            self.max_scope = relayout_scope;
79
        }
99
        let report = self.per_node.entry(new_node_id).or_default();
99
        report.change_set |= change_set;
99
        if relayout_scope > report.relayout_scope {
79
            report.relayout_scope = relayout_scope;
79
        }
99
        if text_change.is_some() {
79
            report.text_change = text_change;
79
        }
99
        report.changed_css_properties.extend(changed_css_properties);
99
    }
    /// Add a text change (from runtime edit or DOM reconciliation).
200
    pub fn add_text_change(&mut self, node_id: NodeId, old_text: String, new_text: String) {
200
        let scope = RelayoutScope::IfcOnly;
200
        if scope > self.max_scope {
200
            self.max_scope = scope;
200
        }
200
        let report = self.per_node.entry(node_id).or_default();
200
        report.change_set.insert(NodeChangeSet::TEXT_CONTENT);
200
        if scope > report.relayout_scope {
200
            report.relayout_scope = scope;
200
        }
200
        report.text_change = Some(TextChange { old_text, new_text });
200
    }
    /// Add a CSS property change (from runtime edit or restyle).
426
    pub fn add_css_change(
426
        &mut self,
426
        node_id: NodeId,
426
        prop_type: CssPropertyType,
426
        scope: RelayoutScope,
426
    ) {
426
        if scope > self.max_scope {
250
            self.max_scope = scope;
252
        }
426
        let report = self.per_node.entry(node_id).or_default();
426
        if scope > RelayoutScope::None {
270
            report.change_set.insert(NodeChangeSet::INLINE_STYLE_LAYOUT);
272
        } else {
156
            report.change_set.insert(NodeChangeSet::INLINE_STYLE_PAINT);
156
        }
426
        if scope > report.relayout_scope {
251
            report.relayout_scope = scope;
253
        }
426
        report.changed_css_properties.push(prop_type);
426
    }
    /// Add an image change (from runtime edit or DOM reconciliation).
58
    pub fn add_image_change(&mut self, node_id: NodeId, scope: RelayoutScope) {
58
        if scope > self.max_scope {
39
            self.max_scope = scope;
39
        }
58
        let report = self.per_node.entry(node_id).or_default();
58
        report.change_set.insert(NodeChangeSet::IMAGE_CHANGED);
58
        if scope > report.relayout_scope {
58
            report.relayout_scope = scope;
58
        }
58
    }
    /// Add a mounted (new) node.
232
    pub fn add_mount(&mut self, node_id: NodeId) {
232
        self.mounted_nodes.push(node_id);
232
    }
    /// Add an unmounted (removed) node.
193
    pub fn add_unmount(&mut self, node_id: NodeId) {
193
        self.unmounted_nodes.push(node_id);
193
    }
    /// Merge a `RestyleResult` (from `restyle_on_state_change()`) into this accumulator.
    ///
    /// This is the bridge between Path B (restyle) and the unified change pipeline.
    /// Each `ChangedCssProperty` is classified via `relayout_scope()` to determine
    /// whether it affects layout or only paint.
4
    pub fn merge_restyle_result(&mut self, restyle: &crate::styled_dom::RestyleResult) {
7
        for (node_id, changed_props) in &restyle.changed_nodes {
6
            for changed in changed_props {
3
                let prop_type = changed.current_prop.get_type();
3
                let scope = prop_type.relayout_scope(true); // conservative
3
                self.add_css_change(*node_id, prop_type, scope);
3
            }
        }
4
    }
    /// Populate this accumulator from an `ExtendedDiffResult` + the old/new DOM data.
    ///
    /// This converts per-node `NodeChangeSet` flags into full `NodeChangeReport`s
    /// with `RelayoutScope` classification.
233
    pub fn merge_extended_diff(
233
        &mut self,
233
        extended: &ExtendedDiffResult,
233
        old_node_data: &[NodeData],
233
        new_node_data: &[NodeData],
233
    ) {
502
        for &(old_id, new_id, ref change_set) in &extended.node_changes {
269
            if change_set.is_empty() {
210
                continue;
59
            }
            // Determine RelayoutScope from the change flags
59
            let scope = Self::classify_change_scope(*change_set, new_node_data, new_id);
            // Extract text change info if TEXT_CONTENT flag is set
59
            let text_change = if change_set.contains(NodeChangeSet::TEXT_CONTENT) {
59
                let old_text = get_node_text_content(&old_node_data[old_id.index()])
59
                    .unwrap_or("")
59
                    .to_string();
59
                let new_text = get_node_text_content(&new_node_data[new_id.index()])
59
                    .unwrap_or("")
59
                    .to_string();
59
                Some(TextChange { old_text, new_text })
            } else {
                None
            };
59
            self.add_dom_change(new_id, *change_set, scope, text_change, Vec::new());
        }
        // Track mounts: new nodes that didn't match anything in old
233
        let matched_new: alloc::collections::BTreeSet<usize> = extended
233
            .diff
233
            .node_moves
233
            .iter()
271
            .map(|m| m.new_node_id.index())
233
            .collect();
405
        for idx in 0..new_node_data.len() {
405
            if !matched_new.contains(&idx) {
136
                self.add_mount(NodeId::new(idx));
269
            }
        }
        // Track unmounts: old nodes that didn't match anything in new
233
        let matched_old: alloc::collections::BTreeSet<usize> = extended
233
            .diff
233
            .node_moves
233
            .iter()
271
            .map(|m| m.old_node_id.index())
233
            .collect();
404
        for idx in 0..old_node_data.len() {
404
            if !matched_old.contains(&idx) {
135
                self.add_unmount(NodeId::new(idx));
269
            }
        }
233
    }
    /// Classify a `NodeChangeSet` into the appropriate `RelayoutScope`.
76
    fn classify_change_scope(
76
        change_set: NodeChangeSet,
76
        new_node_data: &[NodeData],
76
        new_node_id: NodeId,
76
    ) -> RelayoutScope {
        // NODE_TYPE_CHANGED or CHILDREN_CHANGED → Full
76
        if change_set.contains(NodeChangeSet::NODE_TYPE_CHANGED)
74
            || change_set.contains(NodeChangeSet::CHILDREN_CHANGED)
        {
3
            return RelayoutScope::Full;
73
        }
        // IDS_AND_CLASSES → Full (conservative: class change may add layout-affecting CSS)
73
        if change_set.contains(NodeChangeSet::IDS_AND_CLASSES) {
1
            return RelayoutScope::Full;
72
        }
        // INLINE_STYLE_LAYOUT → could be IfcOnly, SizingOnly, or Full
        // We need to check individual properties for the exact scope.
        // For now, we use SizingOnly as a conservative default since
        // the individual property scopes were already checked in compute_node_changes.
72
        if change_set.contains(NodeChangeSet::INLINE_STYLE_LAYOUT) {
            // Walk the inline CSS properties to find the max scope
3
            let new_node = &new_node_data[new_node_id.index()];
3
            let mut max_scope = RelayoutScope::None;
3
            for (prop, _conds) in new_node.style.iter_inline_properties() {
2
                let scope = prop.get_type().relayout_scope(true);
2
                if scope > max_scope {
2
                    max_scope = scope;
2
                }
            }
3
            return if max_scope == RelayoutScope::None {
1
                RelayoutScope::SizingOnly // conservative fallback
            } else {
2
                max_scope
            };
69
        }
        // TEXT_CONTENT → IfcOnly (reshape text, may cascade)
69
        if change_set.contains(NodeChangeSet::TEXT_CONTENT) {
61
            return RelayoutScope::IfcOnly;
8
        }
        // IMAGE_CHANGED → SizingOnly (intrinsic size may change)
8
        if change_set.contains(NodeChangeSet::IMAGE_CHANGED) {
1
            return RelayoutScope::SizingOnly;
7
        }
        // CONTENTEDITABLE → SizingOnly
7
        if change_set.contains(NodeChangeSet::CONTENTEDITABLE) {
1
            return RelayoutScope::SizingOnly;
6
        }
        // Paint-only or no-visual changes
6
        if change_set.intersects(NodeChangeSet::AFFECTS_PAINT) {
2
            return RelayoutScope::None;
4
        }
4
        RelayoutScope::None
76
    }
}
/// Perform a full reconciliation with change detection.
///
/// This combines `reconcile_dom()` + `compute_node_changes()` into a single
/// pass that produces an `ExtendedDiffResult` with per-node change flags.
///
/// The `ChangeAccumulator` can then be populated from the result via
/// `accumulator.merge_extended_diff()`.
#[must_use]
384
pub fn reconcile_dom_with_changes(
384
    old_node_data: &[NodeData],
384
    new_node_data: &[NodeData],
384
    old_hierarchy: &[NodeHierarchyItem],
384
    new_hierarchy: &[NodeHierarchyItem],
384
    old_styled_nodes: Option<&[StyledNodeState]>,
384
    new_styled_nodes: Option<&[StyledNodeState]>,
384
    old_layout: &OrderedMap<NodeId, LogicalRect>,
384
    new_layout: &OrderedMap<NodeId, LogicalRect>,
384
    dom_id: DomId,
384
    timestamp: Instant,
384
) -> ExtendedDiffResult {
    // Step 1: Run standard reconciliation
384
    let diff = reconcile_dom(
384
        old_node_data,
384
        new_node_data,
384
        old_hierarchy,
384
        new_hierarchy,
384
        old_layout,
384
        new_layout,
384
        dom_id,
384
        timestamp,
    );
    // Step 2: For each matched pair, compute what changed
384
    let mut node_changes = Vec::new();
825
    for node_move in &diff.node_moves {
441
        let old_nd = &old_node_data[node_move.old_node_id.index()];
441
        let new_nd = &new_node_data[node_move.new_node_id.index()];
441
        let old_state = old_styled_nodes.and_then(|s| s.get(node_move.old_node_id.index()));
441
        let new_state = new_styled_nodes.and_then(|s| s.get(node_move.new_node_id.index()));
441
        let changes = compute_node_changes(old_nd, new_nd, old_state, new_state);
441
        node_changes.push((node_move.old_node_id, node_move.new_node_id, changes));
    }
384
    ExtendedDiffResult { diff, node_changes }
384
}
// ============================================================================
// NodeDataFingerprint — multi-field hash for fast change detection
// ============================================================================
/// Per-node hash broken into independent fields for fast change detection.
///
/// Instead of a single u64 hash (which loses all granularity), this stores
/// separate hashes per field category. Comparing two fingerprints is O(1)
/// (6 integer comparisons) and immediately tells us WHICH category changed,
/// avoiding the more expensive `compute_node_changes()` for unchanged nodes.
///
/// Two-tier strategy:
/// - **Tier 1** (this struct): O(1) per node, identifies which categories changed.
/// - **Tier 2** (`compute_node_changes`): O(n) per changed field, does field-by-field comparison
///   only for nodes that Tier 1 identified as changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct NodeDataFingerprint {
    /// Hash of `node_type` (Text content, Image ref, Div, etc.)
    pub content_hash: u64,
    /// Hash of `styled_node_state` (hover, focus, active bits)
    pub state_hash: u64,
    /// Hash of inline CSS properties
    pub inline_css_hash: u64,
    /// Hash of `ids_and_classes`
    pub ids_classes_hash: u64,
    /// Hash of callbacks (event types + function pointers)
    pub callbacks_hash: u64,
    /// Hash of the layout-relevant attributes (contenteditable, flags)
    pub attrs_hash: u64,
    /// Hash of the dataset's PRESENCE and TYPE — never its allocation.
    ///
    /// A widget's dataset is state, not layout. Most widgets allocate a fresh
    /// `RefAny` on every build, and `RefAny` hashes by pointer, so hashing the
    /// dataset into `attrs_hash` (which maps to `CONTENTEDITABLE`, a layout
    /// change) made every `with_dataset` node LAYOUT-DIRTY on every
    /// `RefreshDom`: the `TextArea` became a standalone layout root on each
    /// callback, was re-laid-out with its `min-height` while its flex
    /// container kept the old slot, and painted 64 px into a 36 px slot — over
    /// the slider beneath it. A dataset change is [`NodeChangeSet::DATASET`],
    /// which affects neither layout nor paint.
    pub dataset_hash: u64,
}
impl NodeDataFingerprint {
    /// Compute a fingerprint from a node's data and styled state.
    #[must_use]
603955
    pub fn compute(node: &NodeData, styled_state: Option<&StyledNodeState>) -> Self {
        use core::hash::{Hash, Hasher};
        // Content hash
603955
        let content_hash = {
603955
            let mut h = crate::hash::DefaultHasher::new();
603955
            node.get_node_type().hash(&mut h);
603955
            h.finish()
        };
        // State hash
603955
        let state_hash = {
603955
            let mut h = crate::hash::DefaultHasher::new();
603955
            if let Some(state) = styled_state {
603009
                state.hash(&mut h);
603769
            }
603955
            h.finish()
        };
        // Inline CSS hash — full CssProperty value (matches the legacy
        // CssPropertyWithConditions::hash that hashed both property and the
        // condition vec length).
603955
        let inline_css_hash = {
603955
            let mut h = crate::hash::DefaultHasher::new();
3628747
            for (prop, conds) in node.style.iter_inline_properties() {
3626040
                prop.hash(&mut h);
3626040
                conds.as_slice().len().hash(&mut h);
3626040
            }
603955
            h.finish()
        };
        // IDs and classes hash (now stored in attributes)
603955
        let ids_classes_hash = {
603955
            let mut h = crate::hash::DefaultHasher::new();
603955
            for attr in node.attributes().as_ref() {
278931
                match attr {
1409
                    crate::dom::AttributeType::Id(s) => {
1409
                        crate::dom::IdOrClass::Id(s.clone()).hash(&mut h);
1409
                    }
276826
                    crate::dom::AttributeType::Class(s) => {
276826
                        crate::dom::IdOrClass::Class(s.clone()).hash(&mut h);
276826
                    }
696
                    _ => {}
                }
            }
603955
            h.finish()
        };
        // Callbacks hash
603955
        let callbacks_hash = {
603955
            let mut h = crate::hash::DefaultHasher::new();
603955
            for cb in node.callbacks.as_ref() {
93099
                cb.event.hash(&mut h);
93099
                cb.callback.hash(&mut h);
93099
            }
603955
            h.finish()
        };
        // Attributes hash — the layout-relevant ones only
603955
        let attrs_hash = {
603955
            let mut h = crate::hash::DefaultHasher::new();
603955
            node.is_contenteditable().hash(&mut h);
603955
            node.flags.hash(&mut h);
603955
            h.finish()
        };
        // Dataset hash: presence + type, NOT the allocation (see the field doc).
603955
        let dataset_hash = {
603955
            let mut h = crate::hash::DefaultHasher::new();
603955
            match node.get_dataset() {
4479
                Some(ds) => {
4479
                    true.hash(&mut h);
4479
                    ds.get_type_id().hash(&mut h);
4479
                }
599476
                None => false.hash(&mut h),
            }
603955
            h.finish()
        };
603955
        Self {
603955
            content_hash,
603955
            state_hash,
603955
            inline_css_hash,
603955
            ids_classes_hash,
603955
            callbacks_hash,
603955
            attrs_hash,
603955
            dataset_hash,
603955
        }
603955
    }
    /// Returns a quick `NodeChangeSet` by comparing two fingerprints.
    /// This is O(1) — just comparing 7 u64s.
    ///
    /// The result is *conservative*: if a field hash differs, we set the
    /// broadest applicable flag. For precise classification (e.g., which
    /// CSS properties changed and their `relayout_scope()`), the caller
    /// should fall back to `compute_node_changes()` for changed nodes.
    #[must_use]
56892
    pub const fn diff(&self, other: &Self) -> NodeChangeSet {
56892
        let mut changes = NodeChangeSet::empty();
56892
        if self.content_hash != other.content_hash {
530
            // Could be TEXT_CONTENT, IMAGE_CHANGED, or NODE_TYPE_CHANGED
530
            // We set both TEXT_CONTENT and IMAGE_CHANGED conservatively;
530
            // compute_node_changes() will refine this.
530
            changes.insert(NodeChangeSet::TEXT_CONTENT);
530
            changes.insert(NodeChangeSet::IMAGE_CHANGED);
56362
        }
56892
        if self.state_hash != other.state_hash {
13
            changes.insert(NodeChangeSet::STYLED_STATE);
56879
        }
56892
        if self.inline_css_hash != other.inline_css_hash {
185
            // Conservative: inline CSS could affect layout or paint.
185
            // compute_node_changes() checks relayout_scope() per property.
185
            changes.insert(NodeChangeSet::INLINE_STYLE_LAYOUT);
56707
        }
56892
        if self.ids_classes_hash != other.ids_classes_hash {
20
            changes.insert(NodeChangeSet::IDS_AND_CLASSES);
56872
        }
56892
        if self.callbacks_hash != other.callbacks_hash {
1
            changes.insert(NodeChangeSet::CALLBACKS);
56891
        }
56892
        if self.attrs_hash != other.attrs_hash {
2
            changes.insert(NodeChangeSet::TAB_INDEX);
2
            changes.insert(NodeChangeSet::CONTENTEDITABLE);
56890
        }
56892
        if self.dataset_hash != other.dataset_hash {
3
            changes.insert(NodeChangeSet::DATASET);
56889
        }
56892
        changes
56892
    }
    /// Returns true if the fingerprint is identical (no changes at all).
    #[must_use]
136
    pub fn is_identical(&self, other: &Self) -> bool {
136
        self == other
136
    }
    /// Quick check: could this change affect layout?
    #[must_use]
15
    pub const fn might_affect_layout(&self, other: &Self) -> bool {
15
        self.content_hash != other.content_hash
11
            || self.inline_css_hash != other.inline_css_hash
10
            || self.ids_classes_hash != other.ids_classes_hash
8
            || self.attrs_hash != other.attrs_hash
15
    }
    /// Quick check: could this change affect visuals at all?
    #[must_use]
11
    pub const fn might_affect_visuals(&self, other: &Self) -> bool {
11
        self.content_hash != other.content_hash
8
            || self.state_hash != other.state_hash
6
            || self.inline_css_hash != other.inline_css_hash
5
            || self.ids_classes_hash != other.ids_classes_hash
11
    }
}
// ============================================================================
// Pre-cascade DOM fingerprints (two tiers: STRUCTURE vs STYLE)
// ============================================================================
/// Two-tier fingerprints of a recursive [`crate::dom::Dom`].
///
/// Computed BEFORE the cascade, in the same pre-order the flattener
/// (`convert_dom_into_compact_dom`) assigns `NodeId`s — index `i` in each Vec
/// is flattened `NodeId(i)`.
///
/// WHY TWO TIERS (user directive 2026-08-08): "the start should just scan
/// over the `NodeHierarchy` to discover anything that changed, which is
/// iterating over a minimal array" — and css must be EXCLUDED from that
/// first equivalence, because a stylesheet can only affect the subtree it
/// is attached to:
///
/// - **structure**: hierarchy shape + node content (`node_type`, ids/classes, attributes, callback
///   EVENT types). NO css of any kind. If this tier is equal, the old tree, its shaped text and its
///   intrinsic caches are all reusable — and if the style tier is ALSO equal, the previous CASCADE
///   is reusable wholesale (skip `create_from_dom` entirely).
/// - **style**: per-node inline css + (at subtree roots that carry `.with_css()` sheets) the sheet
///   content. A difference here with an equal structure tier means: keep the tree, re-cascade the
///   affected subtree(s) only.
///
/// The per-node arrays exist so a mismatch NAMES the changed nodes (the
/// eventual dirty-set for scoped re-cascade / word-granular text relayout);
/// the root folds make the equal case one u64 compare per tier.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DomFingerprints {
    /// Per-node structural hash, pre-order. Folds: `node_type` content
    /// (image-callback nodes hash (fn ptr, `RefAny` `type_id`) — the `RefAny`
    /// INSTANCE is rebuilt every frame by design and is transferred, not
    /// compared; mirrors `is_layout_equivalent`), ids+classes, callback
    /// event types, contenteditable/flags/dataset, and child COUNT (pre-order
    /// alone cannot distinguish `[a [b] c]` from `[a [b c]]`).
    pub structure: Vec<u64>,
    /// Per-node style hash, pre-order: inline css properties + conditions,
    /// plus the node's attached `.with_css()` sheets (path, declarations,
    /// @-conditions, priority per rule).
    pub style: Vec<u64>,
    /// Order-sensitive fold of `structure`.
    pub structure_root: u64,
    /// Order-sensitive fold of `style`.
    pub style_root: u64,
}
/// `RefAny` payloads collected during the fingerprint walk.
///
/// Transferred onto the retained DOM when the produce side is skipped. The skip path
/// keeps last frame's `StyledDom`, but callbacks/image callbacks must use the
/// freshly-created `RefAnys` (they may reference new app state) — same
/// transfer `regenerate_layout`'s equivalence branch has always done, minus
/// the cascade it used to pay to get here. Indices are flattened `NodeIds`.
#[derive(Debug, Default, Clone)]
pub struct PreCascadeTransfers {
    /// `(flattened NodeId index, fresh image callback)` for every
    /// `NodeType::Image(DecodedImage::Callback)` node.
    pub image_callbacks: Vec<(usize, crate::callbacks::CoreImageCallback)>,
    /// `(flattened NodeId index, fresh event callbacks)` for every node with
    /// a non-empty callback list.
    pub callbacks: Vec<(usize, crate::callbacks::CoreCallbackDataVec)>,
    /// `(flattened NodeId index, fresh dataset)` for every node that carries
    /// one. Merged onto the retained DOM by [`merge_fresh_dataset`] — the
    /// skip path's equivalent of `transfer_states` — so a widget's state
    /// survives an identical rebuild and its callbacks (installed from
    /// `callbacks` above) end up on the SAME allocation as its dataset.
    pub datasets: Vec<(usize, RefAny)>,
}
/// Walk a recursive [`crate::dom::Dom`] once, pre-order.
///
/// Produces both fingerprint tiers and the `RefAny` transfer list. Cost: one hash pass over
/// node data — no cascade, no allocation proportional to anything but node
/// count.
#[allow(clippy::too_many_lines)] // cohesive single-pass walker; splitting adds state-threading
#[must_use]
13
pub fn fingerprint_dom(dom: &crate::dom::Dom) -> (DomFingerprints, PreCascadeTransfers) {
    use core::hash::{Hash, Hasher};
53
    fn node_structure_hash(node: &NodeData, child_count: usize) -> u64 {
        use core::hash::{Hash, Hasher};
        use crate::{dom::NodeType, resources::DecodedImage};
53
        let mut h = crate::hash::DefaultHasher::new();
        // node_type content — image-callback special case (see struct doc)
53
        match node.get_node_type() {
            NodeType::Image(img) => {
                match img.get_data() {
                    DecodedImage::Callback(cb) => {
                        0xB0DE_CA11u32.hash(&mut h);
                        cb.callback.cb.hash(&mut h);
                        cb.refany.get_type_id().hash(&mut h);
                    }
                    _ => {
                        // Raw / GPU images: ImageRef hashes by id — instance
                        // identity, the same strictness is_layout_equivalent's
                        // `old_img != new_img` applies.
                        node.get_node_type().hash(&mut h);
                    }
                }
            }
53
            other => other.hash(&mut h),
        }
        // ids + classes (order-sensitive, as worn)
53
        for attr in node.attributes().as_ref() {
13
            match attr {
                crate::dom::AttributeType::Id(s) => {
                    1u8.hash(&mut h);
                    s.hash(&mut h);
                }
13
                crate::dom::AttributeType::Class(s) => {
13
                    2u8.hash(&mut h);
13
                    s.hash(&mut h);
13
                }
                other => {
                    3u8.hash(&mut h);
                    other.hash(&mut h);
                }
            }
        }
        // callback EVENT types only — the fn ptr + RefAny are transferred,
        // not compared (is_layout_equivalent: "compare only event types")
53
        node.callbacks.as_ref().len().hash(&mut h);
53
        for cb in node.callbacks.as_ref() {
            cb.event.hash(&mut h);
        }
        // layout-relevant attributes
53
        node.is_contenteditable().hash(&mut h);
53
        node.flags.hash(&mut h);
        // hierarchy shape
53
        child_count.hash(&mut h);
53
        h.finish()
53
    }
53
    fn node_style_hash(dom: &crate::dom::Dom) -> u64 {
        use core::hash::{Hash, Hasher};
53
        let mut h = crate::hash::DefaultHasher::new();
53
        for (prop, conds) in dom.root.style.iter_inline_properties() {
1
            prop.hash(&mut h);
1
            conds.as_slice().len().hash(&mut h);
1
        }
        // Attached .with_css() sheets — subtree-scoped by construction, so
        // they belong to THIS node's style identity.
53
        dom.css.as_ref().len().hash(&mut h);
53
        for css in dom.css.as_ref() {
2
            for rule in css.rules.as_ref() {
2
                rule.path.hash(&mut h);
2
                for decl in rule.declarations.as_ref() {
2
                    decl.hash(&mut h);
2
                }
                // DynamicSelector carries f32 media thresholds and derives no
                // Hash — the Debug repr is the stable identity here (rare
                // path: only @-rule-conditioned blocks have any).
2
                for cond in rule.conditions.as_ref() {
                    alloc::format!("{cond:?}").hash(&mut h);
                }
2
                rule.priority.hash(&mut h);
            }
        }
53
        h.finish()
53
    }
53
    fn walk(dom: &crate::dom::Dom, fp: &mut DomFingerprints, transfers: &mut PreCascadeTransfers) {
        use crate::{dom::NodeType, resources::DecodedImage};
53
        let idx = fp.structure.len();
53
        fp.structure
53
            .push(node_structure_hash(&dom.root, dom.children.as_ref().len()));
53
        fp.style.push(node_style_hash(dom));
53
        if let NodeType::Image(img) = dom.root.get_node_type() {
            if let DecodedImage::Callback(cb) = img.get_data() {
                transfers.image_callbacks.push((idx, cb.clone()));
            }
53
        }
53
        if !dom.root.callbacks.as_ref().is_empty() {
            transfers.callbacks.push((idx, dom.root.callbacks.clone()));
53
        }
53
        if let Some(ds) = dom.root.get_dataset() {
            transfers.datasets.push((idx, ds.clone()));
53
        }
53
        for child in dom.children.as_ref() {
40
            walk(child, fp, transfers);
40
        }
53
    }
13
    let mut fp = DomFingerprints {
13
        structure: Vec::new(),
13
        style: Vec::new(),
13
        structure_root: 0,
13
        style_root: 0,
13
    };
13
    let mut transfers = PreCascadeTransfers::default();
13
    walk(dom, &mut fp, &mut transfers);
13
    let mut hs = crate::hash::DefaultHasher::new();
66
    for v in &fp.structure {
53
        v.hash(&mut hs);
53
    }
13
    fp.structure_root = hs.finish();
13
    let mut hy = crate::hash::DefaultHasher::new();
66
    for v in &fp.style {
53
        v.hash(&mut hy);
53
    }
13
    fp.style_root = hy.finish();
13
    (fp, transfers)
13
}
#[cfg(test)]
#[path = "diff_test.rs"]
mod diff_test;