azul-core 0.0.7

Common datatypes used for the Azul document object model, shared across all azul-* crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! DOM Reconciliation Module
//!
//! This module provides the reconciliation algorithm that compares two DOM trees
//! and generates lifecycle events. It uses stable keys and content hashing to
//! identify moves vs. mounts/unmounts.
//!
//! The reconciliation strategy is:
//! 1. **Stable Key Match:** If `.with_key()` is used, it's an absolute match (O(1)).
//! 2. **CSS ID Match:** If no key, use the CSS ID as key.
//! 3. **Structural Key Match:** nth-of-type-within-parent + parent's key (recursive).
//! 4. **Hash Match (Content Match):** Check for identical `DomNodeHash`.
//! 5. **Structural Hash Match:** For text nodes, match by structural hash (ignoring content).
//! 6. **Fallback:** Anything not matched is a `Mount` (new) or `Unmount` (old leftovers).

use alloc::{collections::VecDeque, vec::Vec};
use core::hash::Hash;

use crate::{
    dom::{DomId, DomNodeHash, DomNodeId, NodeData, IdOrClass},
    events::{
        ComponentEventFilter, EventData, EventFilter, EventPhase, EventSource, EventType,
        LifecycleEventData, LifecycleReason, SyntheticEvent,
    },
    geom::LogicalRect,
    id::NodeId,
    styled_dom::{NodeHierarchyItemId, NodeHierarchyItem},
    task::Instant,
    FastHashMap,
};

/// Represents a mapping between a node in the old DOM and the new DOM.
#[derive(Debug, Clone, Copy)]
pub struct NodeMove {
    /// The NodeId in the old DOM array
    pub old_node_id: NodeId,
    /// The NodeId in the new DOM array
    pub new_node_id: NodeId,
}

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

impl Default for DiffResult {
    fn default() -> Self {
        Self {
            events: Vec::new(),
            node_moves: Vec::new(),
        }
    }
}

/// Calculate the reconciliation key for a node using the priority hierarchy:
/// 1. Explicit key (set via `.with_key()`)
/// 2. CSS ID (set via `.with_id("my-id")`)
/// 3. Structural key: nth-of-type-within-parent + parent's reconciliation key
///
/// The structural key prevents incorrect matching when nodes are inserted
/// before existing nodes (e.g., prepending items to a list).
///
/// # Arguments
/// * `node_data` - Slice of all node data
/// * `hierarchy` - Slice of node hierarchy (parent/child relationships)
/// * `node_id` - The node to calculate the key for
///
/// # Returns
/// A 64-bit key that uniquely identifies this node's logical position in the tree.
pub fn calculate_reconciliation_key(
    node_data: &[NodeData],
    hierarchy: &[NodeHierarchyItem],
    node_id: NodeId,
) -> u64 {
    use highway::{HighwayHash, HighwayHasher, Key};
    
    let node = &node_data[node_id.index()];
    
    // Priority 1: Explicit key
    if let Some(key) = node.get_key() {
        return key;
    }
    
    // Priority 2: CSS ID
    for id_or_class in node.ids_and_classes.as_ref().iter() {
        if let IdOrClass::Id(id) = id_or_class {
            let mut hasher = HighwayHasher::new(Key([0; 4]));
            id.as_str().hash(&mut hasher);
            return hasher.finalize64();
        }
    }
    
    // Priority 3: Structural key = nth-of-type-within-parent + parent key
    let mut hasher = HighwayHasher::new(Key([0; 4]));
    
    // Hash node type discriminant and classes (nth-of-type logic)
    core::mem::discriminant(node.get_node_type()).hash(&mut hasher);
    for id_or_class in node.ids_and_classes.as_ref().iter() {
        if let IdOrClass::Class(class) = id_or_class {
            class.as_str().hash(&mut hasher);
        }
    }
    
    // Calculate sibling index (nth-of-type within parent)
    if let Some(hierarchy_item) = hierarchy.get(node_id.index()) {
        if let Some(parent_id) = hierarchy_item.parent_id() {
            // Count siblings of same type before this node
            let mut sibling_index: usize = 0;
            let parent_hierarchy = &hierarchy[parent_id.index()];
            
            // Walk siblings from first child to this node
            let mut current = parent_hierarchy.first_child_id(parent_id);
            while let Some(sibling_id) = current {
                if sibling_id == node_id {
                    break;
                }
                // Check if sibling has same type/classes
                let sibling = &node_data[sibling_id.index()];
                if core::mem::discriminant(sibling.get_node_type()) 
                    == core::mem::discriminant(node.get_node_type()) 
                {
                    sibling_index += 1;
                }
                current = hierarchy[sibling_id.index()].next_sibling_id();
            }
            
            sibling_index.hash(&mut hasher);
            
            // Recursively include parent's key
            let parent_key = calculate_reconciliation_key(node_data, hierarchy, parent_id);
            parent_key.hash(&mut hasher);
        }
    }
    
    hasher.finalize64()
}

/// Precompute reconciliation keys for all nodes in a DOM tree.
///
/// This should be called once before reconciliation to compute stable keys
/// for all nodes. Keys are computed using the hierarchy:
/// 1. Explicit key → 2. CSS ID → 3. Structural key (nth-of-type + parent key)
///
/// # Returns
/// A map from NodeId to its reconciliation key.
pub fn precompute_reconciliation_keys(
    node_data: &[NodeData],
    hierarchy: &[NodeHierarchyItem],
) -> FastHashMap<NodeId, u64> {
    let mut keys = FastHashMap::default();
    for idx in 0..node_data.len() {
        let node_id = NodeId::new(idx);
        let key = calculate_reconciliation_key(node_data, hierarchy, node_id);
        keys.insert(node_id, key);
    }
    keys
}

/// Calculates the difference between two DOM frames and generates lifecycle events.
///
/// This is the main entry point for DOM reconciliation. It compares the old and new
/// DOM trees and produces:
/// - Mount events for new nodes
/// - Unmount events for removed nodes
/// - Resize events for nodes whose bounds changed
/// - Update events for nodes whose content changed (when matched by key)
///
/// # Arguments
/// * `old_node_data` - Node data from the previous frame
/// * `new_node_data` - Node data from the current frame
/// * `old_layout` - Layout bounds from the previous frame
/// * `new_layout` - Layout bounds from the current frame
/// * `dom_id` - The DOM identifier
/// * `timestamp` - Current timestamp for events
pub fn reconcile_dom(
    old_node_data: &[NodeData],
    new_node_data: &[NodeData],
    old_layout: &FastHashMap<NodeId, LogicalRect>,
    new_layout: &FastHashMap<NodeId, LogicalRect>,
    dom_id: DomId,
    timestamp: Instant,
) -> DiffResult {
    let mut result = DiffResult::default();

    // --- STEP 1: INDEX THE OLD DOM ---
    // Create lookups to find old nodes by Key or by Hash.
    // 
    // IMPORTANT: We use TWO hash indexes:
    // 1. Content Hash (calculate_node_data_hash) - for exact matching including text content
    // 2. Structural Hash (calculate_structural_hash) - for text nodes where content may change
    //
    // This allows Text("Hello") to match Text("Hello World") as a structural match,
    // preserving cursor/selection state during text editing.

    let mut old_keyed: FastHashMap<u64, NodeId> = FastHashMap::default();
    let mut old_hashed: FastHashMap<DomNodeHash, VecDeque<NodeId>> = FastHashMap::default();
    let mut old_structural: FastHashMap<DomNodeHash, VecDeque<NodeId>> = FastHashMap::default();
    let mut old_nodes_consumed = vec![false; old_node_data.len()];

    for (idx, node) in old_node_data.iter().enumerate() {
        let id = NodeId::new(idx);

        if let Some(key) = node.get_key() {
            // Priority 1: Explicit Key
            old_keyed.insert(key, id);
        } else {
            // Priority 2: Content Hash (exact match)
            let hash = node.calculate_node_data_hash();
            old_hashed.entry(hash).or_default().push_back(id);
            
            // Priority 3: Structural Hash (for text node matching)
            let structural_hash = node.calculate_structural_hash();
            old_structural.entry(structural_hash).or_default().push_back(id);
        }
    }

    // --- STEP 2: ITERATE NEW DOM AND CLAIM MATCHES ---

    for (new_idx, new_node) in new_node_data.iter().enumerate() {
        let new_id = NodeId::new(new_idx);
        let mut matched_old_id = None;

        // A. Try Match by Key
        if let Some(key) = new_node.get_key() {
            if let Some(&old_id) = old_keyed.get(&key) {
                if !old_nodes_consumed[old_id.index()] {
                    matched_old_id = Some(old_id);
                }
            }
        }
        // B. Try Match by Content Hash first (exact match - The "Automagic" Reordering)
        else {
            let hash = new_node.calculate_node_data_hash();

            // Get the queue of old nodes with this identical content
            if let Some(queue) = old_hashed.get_mut(&hash) {
                // Find first non-consumed node in queue
                while let Some(old_id) = queue.front() {
                    if !old_nodes_consumed[old_id.index()] {
                        matched_old_id = Some(*old_id);
                        queue.pop_front();
                        break;
                    } else {
                        queue.pop_front();
                    }
                }
            }
            
            // C. If no exact match, try Structural Hash (for text nodes with changed content)
            if matched_old_id.is_none() {
                let structural_hash = new_node.calculate_structural_hash();
                if let Some(queue) = old_structural.get_mut(&structural_hash) {
                    while let Some(old_id) = queue.front() {
                        if !old_nodes_consumed[old_id.index()] {
                            matched_old_id = Some(*old_id);
                            queue.pop_front();
                            break;
                        } else {
                            queue.pop_front();
                        }
                    }
                }
            }
        }

        // --- STEP 3: PROCESS MATCH OR MOUNT ---

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

            old_nodes_consumed[old_id.index()] = true;
            result.node_moves.push(NodeMove {
                old_node_id: old_id,
                new_node_id: new_id,
            });

            // Check for Resize
            let old_rect = old_layout.get(&old_id).copied().unwrap_or(LogicalRect::zero());
            let new_rect = new_layout.get(&new_id).copied().unwrap_or(LogicalRect::zero());

            if old_rect.size != new_rect.size {
                // Fire Resize Event
                if has_resize_callback(new_node) {
                    result.events.push(create_lifecycle_event(
                        EventType::Resize,
                        new_id,
                        dom_id,
                        &timestamp,
                        LifecycleEventData {
                            reason: LifecycleReason::Resize,
                            previous_bounds: Some(old_rect),
                            current_bounds: new_rect,
                        },
                    ));
                }
            }

            // If matched by Key, the content might have changed, so we should check hash equality.
            if new_node.get_key().is_some() {
                let old_hash = old_node_data[old_id.index()].calculate_node_data_hash();
                let new_hash = new_node.calculate_node_data_hash();

                if old_hash != new_hash && has_update_callback(new_node) {
                    result.events.push(create_lifecycle_event(
                        EventType::Update,
                        new_id,
                        dom_id,
                        &timestamp,
                        LifecycleEventData {
                            reason: LifecycleReason::Update,
                            previous_bounds: Some(old_rect),
                            current_bounds: new_rect,
                        },
                    ));
                }
            }
        } else {
            // NO MATCH FOUND -> MOUNT (New Node)
            if has_mount_callback(new_node) {
                let bounds = new_layout.get(&new_id).copied().unwrap_or(LogicalRect::zero());
                result.events.push(create_lifecycle_event(
                    EventType::Mount,
                    new_id,
                    dom_id,
                    &timestamp,
                    LifecycleEventData {
                        reason: LifecycleReason::InitialMount,
                        previous_bounds: None,
                        current_bounds: bounds,
                    },
                ));
            }
        }
    }

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

    for (old_idx, consumed) in old_nodes_consumed.iter().enumerate() {
        if !consumed {
            let old_id = NodeId::new(old_idx);
            let old_node = &old_node_data[old_idx];

            if has_unmount_callback(old_node) {
                let bounds = old_layout.get(&old_id).copied().unwrap_or(LogicalRect::zero());
                result.events.push(create_lifecycle_event(
                    EventType::Unmount,
                    old_id,
                    dom_id,
                    &timestamp,
                    LifecycleEventData {
                        reason: LifecycleReason::InitialMount, // Context implies unmount
                        previous_bounds: Some(bounds),
                        current_bounds: LogicalRect::zero(),
                    },
                ));
            }
        }
    }

    result
}

/// Creates a lifecycle event with all necessary fields.
fn create_lifecycle_event(
    event_type: EventType,
    node_id: NodeId,
    dom_id: DomId,
    timestamp: &Instant,
    data: LifecycleEventData,
) -> SyntheticEvent {
    let dom_node_id = DomNodeId {
        dom: dom_id,
        node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
    };
    SyntheticEvent {
        event_type,
        source: EventSource::Lifecycle,
        phase: EventPhase::Target,
        target: dom_node_id,
        current_target: dom_node_id,
        timestamp: timestamp.clone(),
        data: EventData::Lifecycle(data),
        stopped: false,
        stopped_immediate: false,
        prevented_default: false,
    }
}

/// Check if the node has an AfterMount callback registered.
fn has_mount_callback(node: &NodeData) -> bool {
    node.get_callbacks().iter().any(|cb| {
        matches!(
            cb.event,
            EventFilter::Component(ComponentEventFilter::AfterMount)
        )
    })
}

/// Check if the node has a BeforeUnmount callback registered.
fn has_unmount_callback(node: &NodeData) -> bool {
    node.get_callbacks().iter().any(|cb| {
        matches!(
            cb.event,
            EventFilter::Component(ComponentEventFilter::BeforeUnmount)
        )
    })
}

/// Check if the node has a NodeResized callback registered.
fn has_resize_callback(node: &NodeData) -> bool {
    node.get_callbacks().iter().any(|cb| {
        matches!(
            cb.event,
            EventFilter::Component(ComponentEventFilter::NodeResized)
        )
    })
}

/// Check if the node has any lifecycle callback that would respond to updates.
fn has_update_callback(node: &NodeData) -> bool {
    // For now, we use Selected as a placeholder for "update" events
    // This could be extended to a dedicated UpdateCallback in the future
    node.get_callbacks().iter().any(|cb| {
        matches!(
            cb.event,
            EventFilter::Component(ComponentEventFilter::Selected)
        )
    })
}

/// 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
/// 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;
///     }
/// }
/// ```
pub fn create_migration_map(node_moves: &[NodeMove]) -> FastHashMap<NodeId, NodeId> {
    let mut map = FastHashMap::default();
    for m in node_moves {
        map.insert(m.old_node_id, m.new_node_id);
    }
    map
}

/// 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);
/// ```
pub fn transfer_states(
    old_node_data: &mut [NodeData],
    new_node_data: &mut [NodeData],
    node_moves: &[NodeMove],
) {
    use crate::refany::OptionRefAny;

    for movement in node_moves {
        let old_idx = movement.old_node_id.index();
        let new_idx = movement.new_node_id.index();

        // Bounds check
        if old_idx >= old_node_data.len() || new_idx >= new_node_data.len() {
            continue;
        }

        // 1. Check if the NEW node has requested a merge callback
        let merge_callback = match new_node_data[new_idx].get_merge_callback() {
            Some(cb) => cb,
            None => continue, // No merge callback, skip
        };

        // 2. Check if BOTH nodes have datasets
        // We need to temporarily take the datasets to satisfy borrow checker
        let old_dataset = core::mem::replace(
            &mut old_node_data[old_idx].dataset, 
            OptionRefAny::None
        );
        let new_dataset = core::mem::replace(
            &mut new_node_data[new_idx].dataset, 
            OptionRefAny::None
        );

        match (new_dataset, old_dataset) {
            (OptionRefAny::Some(new_data), OptionRefAny::Some(old_data)) => {
                // 3. EXECUTE THE MERGE CALLBACK
                // The callback receives both datasets and returns the merged result
                let merged = (merge_callback.cb)(new_data, old_data);
                
                // 4. Store the merged result back in the new node
                new_node_data[new_idx].dataset = OptionRefAny::Some(merged);
            }
            (new_ds, old_ds) => {
                // One or both datasets missing - restore what we had
                new_node_data[new_idx].dataset = new_ds;
                old_node_data[old_idx].dataset = old_ds;
            }
        }
    }
}

/// 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
pub fn calculate_contenteditable_key(
    node_data: &[NodeData],
    hierarchy: &[crate::styled_dom::NodeHierarchyItem],
    node_id: NodeId,
) -> u64 {
    use highway::{HighwayHash, HighwayHasher, Key};
    use crate::dom::IdOrClass;
    
    let node = &node_data[node_id.index()];
    
    // Priority 1: Explicit key (from .with_key())
    if let Some(explicit_key) = node.get_key() {
        return explicit_key;
    }
    
    // Priority 2: CSS ID
    for id_or_class in node.get_ids_and_classes().as_ref().iter() {
        if let IdOrClass::Id(id) = id_or_class {
            let mut hasher = HighwayHasher::new(Key([1; 4])); // Different seed for ID keys
            hasher.append(id.as_str().as_bytes());
            return hasher.finalize64();
        }
    }
    
    // Priority 3: Structural key = (nth-of-type, classes, parent_key)
    let mut hasher = HighwayHasher::new(Key([2; 4])); // Different seed for structural keys
    
    // Get parent and calculate its key recursively
    let parent_key = if let Some(parent_id) = hierarchy.get(node_id.index()).and_then(|h| h.parent_id()) {
        calculate_contenteditable_key(node_data, hierarchy, parent_id)
    } else {
        0u64 // Root node
    };
    hasher.append(&parent_key.to_le_bytes());
    
    // Calculate nth-of-type (count siblings of same node type before this one)
    // We compare discriminants directly without hashing
    let node_discriminant = core::mem::discriminant(node.get_node_type());
    let nth_of_type = if let Some(parent_id) = hierarchy.get(node_id.index()).and_then(|h| h.parent_id()) {
        // Count siblings with same node type that come before this node
        let mut count = 0u32;
        let mut sibling_id = hierarchy.get(parent_id.index()).and_then(|h| h.first_child_id(parent_id));
        while let Some(sib_id) = sibling_id {
            if sib_id == node_id {
                break;
            }
            let sibling_discriminant = core::mem::discriminant(node_data[sib_id.index()].get_node_type());
            if sibling_discriminant == node_discriminant {
                count += 1;
            }
            sibling_id = hierarchy.get(sib_id.index()).and_then(|h| h.next_sibling_id());
        }
        count
    } else {
        0
    };
    
    hasher.append(&nth_of_type.to_le_bytes());
    
    // Hash the node type using its Debug representation as a stable identifier
    // This works because NodeType implements Debug
    #[cfg(feature = "std")]
    {
        let type_str = format!("{:?}", node_discriminant);
        hasher.append(type_str.as_bytes());
    }
    #[cfg(not(feature = "std"))]
    {
        // For no_std, use the memory representation of the discriminant
        // NodeType variants are numbered 0..N, and discriminant stores this
        let discriminant_bytes: [u8; core::mem::size_of::<core::mem::Discriminant<crate::dom::NodeType>>()] = 
            unsafe { core::mem::transmute(node_discriminant) };
        hasher.append(&discriminant_bytes);
    }
    
    // Also hash the classes for additional stability
    for id_or_class in node.get_ids_and_classes().as_ref().iter() {
        if let IdOrClass::Class(class) = id_or_class {
            hasher.append(class.as_str().as_bytes());
        }
    }
    
    hasher.finalize64()
}

/// 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)
/// ```
pub fn reconcile_cursor_position(
    old_text: &str,
    new_text: &str,
    old_cursor_byte: usize,
) -> usize {
    // If texts are equal, cursor is unchanged
    if old_text == new_text {
        return old_cursor_byte;
    }
    
    // Empty old text - place cursor at end of new text
    if old_text.is_empty() {
        return new_text.len();
    }
    
    // Empty new text - place cursor at 0
    if new_text.is_empty() {
        return 0;
    }
    
    // Find common prefix (how many bytes from the start are identical)
    let common_prefix_bytes = old_text
        .bytes()
        .zip(new_text.bytes())
        .take_while(|(a, b)| a == b)
        .count();
    
    // If cursor was in the unchanged prefix, it stays at the same byte offset
    if old_cursor_byte <= common_prefix_bytes {
        return old_cursor_byte.min(new_text.len());
    }
    
    // Find common suffix (how many bytes from the end are identical)
    let common_suffix_bytes = old_text
        .bytes()
        .rev()
        .zip(new_text.bytes().rev())
        .take_while(|(a, b)| a == b)
        .count();
    
    // Calculate where the suffix starts in old and new text
    let old_suffix_start = old_text.len().saturating_sub(common_suffix_bytes);
    let new_suffix_start = new_text.len().saturating_sub(common_suffix_bytes);
    
    // If cursor was in the unchanged suffix, adjust by length difference
    if old_cursor_byte >= old_suffix_start {
        let offset_from_end = old_text.len() - old_cursor_byte;
        return new_text.len().saturating_sub(offset_from_end);
    }
    
    // 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)
    new_suffix_start
}

/// 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`.
pub fn get_node_text_content(node: &NodeData) -> Option<&str> {
    if let crate::dom::NodeType::Text(ref text) = node.get_node_type() {
        Some(text.as_str())
    } else {
        None
    }
}