presentar-core 0.3.4

Core types and traits for Presentar UI framework
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
//! Widget tree diffing for efficient UI updates.
//!
//! This module provides algorithms for comparing two widget trees and computing
//! the minimal set of operations needed to transform one into the other.
//!
//! # Algorithm
//!
//! The diffing algorithm works in two phases:
//!
//! 1. **Matching**: Match widgets between old and new trees by key or position
//! 2. **Reconciliation**: Generate operations for differences
//!
//! Widgets are matched by:
//! - Explicit key (if set via `key` attribute)
//! - Type + position (fallback)

use crate::widget::TypeId;
use std::collections::HashMap;

/// A key used to identify widgets across renders.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum WidgetKey {
    /// Explicit string key
    String(String),
    /// Auto-generated index key
    Index(usize),
}

impl WidgetKey {
    /// Create a string key.
    #[must_use]
    pub fn string(s: impl Into<String>) -> Self {
        Self::String(s.into())
    }

    /// Create an index key.
    #[must_use]
    pub const fn index(i: usize) -> Self {
        Self::Index(i)
    }
}

/// A node in the widget tree for diffing.
#[derive(Debug, Clone)]
pub struct DiffNode {
    /// Widget type
    pub type_id: TypeId,
    /// Optional key for matching
    pub key: Option<String>,
    /// Widget properties hash (for detecting changes)
    pub props_hash: u64,
    /// Child nodes
    pub children: Vec<Self>,
    /// Position in parent's children list
    pub index: usize,
}

impl DiffNode {
    /// Create a new diff node.
    #[must_use]
    pub const fn new(type_id: TypeId, props_hash: u64) -> Self {
        Self {
            type_id,
            key: None,
            props_hash,
            children: Vec::new(),
            index: 0,
        }
    }

    /// Set the key for this node.
    #[must_use]
    pub fn with_key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// Set the index of this node.
    #[must_use]
    pub const fn with_index(mut self, index: usize) -> Self {
        self.index = index;
        self
    }

    /// Add a child node.
    pub fn add_child(&mut self, child: Self) {
        self.children.push(child);
    }

    /// Add a child node with fluent API.
    #[must_use]
    pub fn with_child(mut self, child: Self) -> Self {
        self.children.push(child);
        self
    }
}

/// Operation to apply during reconciliation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffOp {
    /// Insert a new widget at path
    Insert {
        /// Path to parent (indices from root)
        path: Vec<usize>,
        /// Index to insert at
        index: usize,
        /// Type of widget to insert
        type_id: TypeId,
        /// Props hash of the new widget
        props_hash: u64,
    },
    /// Remove widget at path
    Remove {
        /// Path to widget to remove
        path: Vec<usize>,
    },
    /// Update widget properties at path
    Update {
        /// Path to widget to update
        path: Vec<usize>,
        /// New props hash
        new_props_hash: u64,
    },
    /// Move widget from one position to another
    Move {
        /// Old path
        from_path: Vec<usize>,
        /// New path
        to_path: Vec<usize>,
    },
    /// Replace widget with different type
    Replace {
        /// Path to widget to replace
        path: Vec<usize>,
        /// New type ID
        new_type_id: TypeId,
        /// New props hash
        new_props_hash: u64,
    },
}

/// Result of diffing two widget trees.
#[derive(Debug, Clone, Default)]
pub struct DiffResult {
    /// List of operations to apply
    pub operations: Vec<DiffOp>,
}

impl DiffResult {
    /// Create an empty diff result.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Check if there are no changes.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.operations.is_empty()
    }

    /// Get the number of operations.
    #[must_use]
    pub fn len(&self) -> usize {
        self.operations.len()
    }

    /// Add an operation.
    pub fn push(&mut self, op: DiffOp) {
        self.operations.push(op);
    }
}

/// Widget tree differ.
#[derive(Debug, Default)]
pub struct TreeDiffer {
    /// Current path during traversal
    current_path: Vec<usize>,
}

impl TreeDiffer {
    /// Create a new tree differ.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Compute the diff between two widget trees.
    #[must_use]
    pub fn diff(&mut self, old: &DiffNode, new: &DiffNode) -> DiffResult {
        let mut result = DiffResult::new();
        self.current_path.clear();
        self.diff_node(old, new, &mut result);
        result
    }

    fn diff_node(&mut self, old: &DiffNode, new: &DiffNode, result: &mut DiffResult) {
        // Check if type changed - need full replacement
        if old.type_id != new.type_id {
            result.push(DiffOp::Replace {
                path: self.current_path.clone(),
                new_type_id: new.type_id,
                new_props_hash: new.props_hash,
            });
            return;
        }

        // Check if props changed
        if old.props_hash != new.props_hash {
            result.push(DiffOp::Update {
                path: self.current_path.clone(),
                new_props_hash: new.props_hash,
            });
        }

        // Diff children
        self.diff_children(&old.children, &new.children, result);
    }

    fn diff_children(
        &mut self,
        old_children: &[DiffNode],
        new_children: &[DiffNode],
        result: &mut DiffResult,
    ) {
        // Build key -> index maps for keyed children
        let old_keyed: HashMap<&str, usize> = old_children
            .iter()
            .enumerate()
            .filter_map(|(i, c)| c.key.as_deref().map(|k| (k, i)))
            .collect();

        let _new_keyed: HashMap<&str, usize> = new_children
            .iter()
            .enumerate()
            .filter_map(|(i, c)| c.key.as_deref().map(|k| (k, i)))
            .collect();

        // Track which old children have been matched
        let mut old_matched = vec![false; old_children.len()];
        let mut new_matched = vec![false; new_children.len()];

        // Phase 1: Match by key
        for (new_idx, new_child) in new_children.iter().enumerate() {
            if let Some(key) = &new_child.key {
                if let Some(&old_idx) = old_keyed.get(key.as_str()) {
                    old_matched[old_idx] = true;
                    new_matched[new_idx] = true;

                    // Check if moved
                    if old_idx != new_idx {
                        let mut from_path = self.current_path.clone();
                        from_path.push(old_idx);
                        let mut to_path = self.current_path.clone();
                        to_path.push(new_idx);
                        result.push(DiffOp::Move { from_path, to_path });
                    }

                    // Recursively diff
                    self.current_path.push(new_idx);
                    self.diff_node(&old_children[old_idx], new_child, result);
                    self.current_path.pop();
                }
            }
        }

        // Phase 2: Match unkeyed children by type + position
        let old_unkeyed: Vec<usize> = old_children
            .iter()
            .enumerate()
            .filter(|(i, c)| c.key.is_none() && !old_matched[*i])
            .map(|(i, _)| i)
            .collect();

        let new_unkeyed: Vec<usize> = new_children
            .iter()
            .enumerate()
            .filter(|(i, c)| c.key.is_none() && !new_matched[*i])
            .map(|(i, _)| i)
            .collect();

        // Match by type
        let mut old_unkeyed_used = vec![false; old_unkeyed.len()];
        for new_pos in &new_unkeyed {
            let new_child = &new_children[*new_pos];
            let mut found = false;

            for (old_pos_idx, old_pos) in old_unkeyed.iter().enumerate() {
                if old_unkeyed_used[old_pos_idx] {
                    continue;
                }
                let old_child = &old_children[*old_pos];

                if old_child.type_id == new_child.type_id {
                    old_unkeyed_used[old_pos_idx] = true;
                    old_matched[*old_pos] = true;
                    new_matched[*new_pos] = true;
                    found = true;

                    // Recursively diff
                    self.current_path.push(*new_pos);
                    self.diff_node(old_child, new_child, result);
                    self.current_path.pop();
                    break;
                }
            }

            if !found {
                // New child with no match - insert
                new_matched[*new_pos] = true;
                result.push(DiffOp::Insert {
                    path: self.current_path.clone(),
                    index: *new_pos,
                    type_id: new_child.type_id,
                    props_hash: new_child.props_hash,
                });

                // Recursively handle new children's children
                self.current_path.push(*new_pos);
                self.insert_subtree(new_child, result);
                self.current_path.pop();
            }
        }

        // Phase 3: Remove unmatched old children (in reverse order)
        for (i, matched) in old_matched.iter().enumerate().rev() {
            if !matched {
                let mut path = self.current_path.clone();
                path.push(i);
                result.push(DiffOp::Remove { path });
            }
        }

        // Phase 4: Insert remaining new children
        for (i, matched) in new_matched.iter().enumerate() {
            if !matched {
                let new_child = &new_children[i];
                result.push(DiffOp::Insert {
                    path: self.current_path.clone(),
                    index: i,
                    type_id: new_child.type_id,
                    props_hash: new_child.props_hash,
                });

                // Recursively handle new children's children
                self.current_path.push(i);
                self.insert_subtree(new_child, result);
                self.current_path.pop();
            }
        }
    }

    fn insert_subtree(&mut self, node: &DiffNode, result: &mut DiffResult) {
        for (i, child) in node.children.iter().enumerate() {
            result.push(DiffOp::Insert {
                path: self.current_path.clone(),
                index: i,
                type_id: child.type_id,
                props_hash: child.props_hash,
            });

            self.current_path.push(i);
            self.insert_subtree(child, result);
            self.current_path.pop();
        }
    }
}

/// Convenience function to diff two trees.
#[must_use]
pub fn diff_trees(old: &DiffNode, new: &DiffNode) -> DiffResult {
    let mut differ = TreeDiffer::new();
    differ.diff(old, new)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_type_id<T: 'static>() -> TypeId {
        TypeId::of::<T>()
    }

    #[test]
    fn test_widget_key_string() {
        let key = WidgetKey::string("test");
        assert_eq!(key, WidgetKey::String("test".to_string()));
    }

    #[test]
    fn test_widget_key_index() {
        let key = WidgetKey::index(42);
        assert_eq!(key, WidgetKey::Index(42));
    }

    #[test]
    fn test_diff_node_new() {
        let type_id = make_type_id::<u32>();
        let node = DiffNode::new(type_id, 123);

        assert_eq!(node.type_id, type_id);
        assert_eq!(node.props_hash, 123);
        assert!(node.key.is_none());
        assert!(node.children.is_empty());
    }

    #[test]
    fn test_diff_node_with_key() {
        let type_id = make_type_id::<u32>();
        let node = DiffNode::new(type_id, 123).with_key("my-key");

        assert_eq!(node.key, Some("my-key".to_string()));
    }

    #[test]
    fn test_diff_node_with_child() {
        let type_id = make_type_id::<u32>();
        let child = DiffNode::new(type_id, 456);
        let parent = DiffNode::new(type_id, 123).with_child(child);

        assert_eq!(parent.children.len(), 1);
        assert_eq!(parent.children[0].props_hash, 456);
    }

    #[test]
    fn test_diff_result_empty() {
        let result = DiffResult::new();
        assert!(result.is_empty());
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_diff_identical_trees() {
        let type_id = make_type_id::<u32>();
        let old = DiffNode::new(type_id, 123);
        let new = DiffNode::new(type_id, 123);

        let result = diff_trees(&old, &new);
        assert!(result.is_empty());
    }

    #[test]
    fn test_diff_props_changed() {
        let type_id = make_type_id::<u32>();
        let old = DiffNode::new(type_id, 123);
        let new = DiffNode::new(type_id, 456);

        let result = diff_trees(&old, &new);
        assert_eq!(result.len(), 1);
        assert!(matches!(
            &result.operations[0],
            DiffOp::Update { path, new_props_hash: 456 } if path.is_empty()
        ));
    }

    #[test]
    fn test_diff_type_changed() {
        let old_type = make_type_id::<u32>();
        let new_type = make_type_id::<String>();
        let old = DiffNode::new(old_type, 123);
        let new = DiffNode::new(new_type, 123);

        let result = diff_trees(&old, &new);
        assert_eq!(result.len(), 1);
        assert!(matches!(
            &result.operations[0],
            DiffOp::Replace { path, new_type_id, .. } if path.is_empty() && *new_type_id == new_type
        ));
    }

    #[test]
    fn test_diff_child_added() {
        let type_id = make_type_id::<u32>();
        let child_type = make_type_id::<String>();

        let old = DiffNode::new(type_id, 123);
        let new = DiffNode::new(type_id, 123).with_child(DiffNode::new(child_type, 456));

        let result = diff_trees(&old, &new);
        assert_eq!(result.len(), 1);
        assert!(matches!(
            &result.operations[0],
            DiffOp::Insert { path, index: 0, type_id: t, .. } if path.is_empty() && *t == child_type
        ));
    }

    #[test]
    fn test_diff_child_removed() {
        let type_id = make_type_id::<u32>();
        let child_type = make_type_id::<String>();

        let old = DiffNode::new(type_id, 123).with_child(DiffNode::new(child_type, 456));
        let new = DiffNode::new(type_id, 123);

        let result = diff_trees(&old, &new);
        assert_eq!(result.len(), 1);
        assert!(matches!(
            &result.operations[0],
            DiffOp::Remove { path } if *path == vec![0]
        ));
    }

    #[test]
    fn test_diff_keyed_children_reordered() {
        let type_id = make_type_id::<u32>();

        let old = DiffNode::new(type_id, 0)
            .with_child(DiffNode::new(type_id, 1).with_key("a"))
            .with_child(DiffNode::new(type_id, 2).with_key("b"));

        let new = DiffNode::new(type_id, 0)
            .with_child(DiffNode::new(type_id, 2).with_key("b"))
            .with_child(DiffNode::new(type_id, 1).with_key("a"));

        let result = diff_trees(&old, &new);

        // Should have move operations
        let move_ops: Vec<_> = result
            .operations
            .iter()
            .filter(|op| matches!(op, DiffOp::Move { .. }))
            .collect();
        assert!(!move_ops.is_empty());
    }

    #[test]
    fn test_diff_keyed_child_updated() {
        let type_id = make_type_id::<u32>();

        let old = DiffNode::new(type_id, 0).with_child(DiffNode::new(type_id, 1).with_key("item"));
        let new = DiffNode::new(type_id, 0).with_child(DiffNode::new(type_id, 2).with_key("item"));

        let result = diff_trees(&old, &new);

        let update_ops: Vec<_> = result
            .operations
            .iter()
            .filter(|op| matches!(op, DiffOp::Update { .. }))
            .collect();
        assert_eq!(update_ops.len(), 1);
    }

    #[test]
    fn test_diff_nested_changes() {
        let type_id = make_type_id::<u32>();

        let old = DiffNode::new(type_id, 0)
            .with_child(DiffNode::new(type_id, 1).with_child(DiffNode::new(type_id, 2)));

        let new = DiffNode::new(type_id, 0)
            .with_child(DiffNode::new(type_id, 1).with_child(DiffNode::new(type_id, 3)));

        let result = diff_trees(&old, &new);

        // Should have update at path [0, 0]
        let update_ops: Vec<_> = result
            .operations
            .iter()
            .filter(|op| matches!(op, DiffOp::Update { path, .. } if *path == vec![0, 0]))
            .collect();
        assert_eq!(update_ops.len(), 1);
    }

    #[test]
    fn test_diff_multiple_children_mixed() {
        let type_id = make_type_id::<u32>();
        let string_type = make_type_id::<String>();

        let old = DiffNode::new(type_id, 0)
            .with_child(DiffNode::new(type_id, 1))
            .with_child(DiffNode::new(string_type, 2))
            .with_child(DiffNode::new(type_id, 3));

        let new = DiffNode::new(type_id, 0)
            .with_child(DiffNode::new(type_id, 1))
            .with_child(DiffNode::new(type_id, 4)); // Changed type and removed one

        let result = diff_trees(&old, &new);

        // Should have remove operations for removed children
        let remove_ops: Vec<_> = result
            .operations
            .iter()
            .filter(|op| matches!(op, DiffOp::Remove { .. }))
            .collect();
        assert!(!remove_ops.is_empty());
    }

    #[test]
    fn test_tree_differ_reuse() {
        let type_id = make_type_id::<u32>();
        let mut differ = TreeDiffer::new();

        let old1 = DiffNode::new(type_id, 1);
        let new1 = DiffNode::new(type_id, 2);
        let result1 = differ.diff(&old1, &new1);

        let old2 = DiffNode::new(type_id, 3);
        let new2 = DiffNode::new(type_id, 3);
        let result2 = differ.diff(&old2, &new2);

        assert_eq!(result1.len(), 1);
        assert!(result2.is_empty());
    }

    #[test]
    fn test_diff_empty_to_tree() {
        let type_id = make_type_id::<u32>();

        let old = DiffNode::new(type_id, 0);
        let new = DiffNode::new(type_id, 0)
            .with_child(DiffNode::new(type_id, 1))
            .with_child(DiffNode::new(type_id, 2));

        let result = diff_trees(&old, &new);

        let insert_ops: Vec<_> = result
            .operations
            .iter()
            .filter(|op| matches!(op, DiffOp::Insert { .. }))
            .collect();
        assert_eq!(insert_ops.len(), 2);
    }

    #[test]
    fn test_diff_tree_to_empty() {
        let type_id = make_type_id::<u32>();

        let old = DiffNode::new(type_id, 0)
            .with_child(DiffNode::new(type_id, 1))
            .with_child(DiffNode::new(type_id, 2));
        let new = DiffNode::new(type_id, 0);

        let result = diff_trees(&old, &new);

        let remove_ops: Vec<_> = result
            .operations
            .iter()
            .filter(|op| matches!(op, DiffOp::Remove { .. }))
            .collect();
        assert_eq!(remove_ops.len(), 2);
    }

    #[test]
    fn test_diff_deeply_nested() {
        let type_id = make_type_id::<u32>();

        let old = DiffNode::new(type_id, 0).with_child(
            DiffNode::new(type_id, 1)
                .with_child(DiffNode::new(type_id, 2).with_child(DiffNode::new(type_id, 3))),
        );

        let new = DiffNode::new(type_id, 0).with_child(
            DiffNode::new(type_id, 1)
                .with_child(DiffNode::new(type_id, 2).with_child(DiffNode::new(type_id, 99))),
        );

        let result = diff_trees(&old, &new);

        // Should update the deeply nested node
        let update_ops: Vec<_> = result
            .operations
            .iter()
            .filter(|op| {
                matches!(op, DiffOp::Update { path, new_props_hash: 99 } if *path == vec![0, 0, 0])
            })
            .collect();
        assert_eq!(update_ops.len(), 1);
    }

    #[test]
    fn test_diff_op_debug() {
        let op = DiffOp::Insert {
            path: vec![0, 1],
            index: 2,
            type_id: make_type_id::<u32>(),
            props_hash: 123,
        };
        let debug_str = format!("{op:?}");
        assert!(debug_str.contains("Insert"));
    }

    #[test]
    fn test_diff_result_push() {
        let mut result = DiffResult::new();
        result.push(DiffOp::Remove { path: vec![0] });
        assert_eq!(result.len(), 1);
        assert!(!result.is_empty());
    }
}