reratui 1.1.0

A modern, reactive TUI framework for Rust with React-inspired hooks and components, powered by ratatui
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
//! Fiber tree management for tracking all mounted component instances.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};

use crate::fiber::{Fiber, FiberId};

thread_local! {
    /// Thread-local fiber tree for the current render context
    static FIBER_TREE: RefCell<Option<FiberTree>> = const { RefCell::new(None) };
}

/// Global fiber tree that tracks all mounted component instances
pub struct FiberTree {
    /// All mounted fibers by ID
    pub(crate) fibers: HashMap<FiberId, Fiber>,
    /// Root fiber ID
    pub(crate) root: Option<FiberId>,
    /// Stack of currently rendering fibers (for nested renders)
    pub(crate) render_stack: Vec<FiberId>,
    /// Next available fiber ID
    next_id: AtomicU64,
    /// Fibers scheduled for unmount
    pub(crate) pending_unmount: Vec<FiberId>,
    /// Maps component IDs to their fiber IDs for Component tracking
    component_id_to_fiber: HashMap<u64, FiberId>,
    /// Maps fiber IDs back to component IDs for cleanup
    fiber_to_component_id: HashMap<FiberId, u64>,
    /// Fibers seen during the current render pass (for unmount detection)
    seen_this_render: HashSet<FiberId>,
}

impl FiberTree {
    /// Create a new empty fiber tree
    pub fn new() -> Self {
        Self {
            fibers: HashMap::new(),
            root: None,
            render_stack: Vec::new(),
            next_id: AtomicU64::new(1),
            pending_unmount: Vec::new(),
            component_id_to_fiber: HashMap::new(),
            fiber_to_component_id: HashMap::new(),
            seen_this_render: HashSet::new(),
        }
    }

    /// Mount a new fiber, returning its ID
    pub fn mount(&mut self, parent: Option<FiberId>, key: Option<String>) -> FiberId {
        let id = FiberId(self.next_id.fetch_add(1, Ordering::SeqCst));
        let fiber = Fiber::new(id, parent, key);
        self.fibers.insert(id, fiber);

        // Add to parent's children
        if let Some(parent_id) = parent
            && let Some(parent_fiber) = self.fibers.get_mut(&parent_id)
        {
            parent_fiber.children.push(id);
        }

        // Set as root if no parent
        if parent.is_none() && self.root.is_none() {
            self.root = Some(id);
        }

        id
    }

    /// Get or create a fiber for a Component by its component ID.
    ///
    /// If a fiber already exists for this component ID, returns the existing fiber ID.
    /// Otherwise, creates a new fiber and associates it with the component ID.
    /// The fiber is marked as seen for this render pass.
    pub fn get_or_create_fiber_by_component_id(&mut self, component_id: u64) -> FiberId {
        if let Some(&fiber_id) = self.component_id_to_fiber.get(&component_id) {
            // Existing fiber - mark as seen
            self.seen_this_render.insert(fiber_id);
            fiber_id
        } else {
            // Create new fiber
            let parent = self.current_fiber();
            let fiber_id = self.mount(parent, None);

            // Associate with component ID
            self.component_id_to_fiber.insert(component_id, fiber_id);
            self.fiber_to_component_id.insert(fiber_id, component_id);

            // Mark as seen
            self.seen_this_render.insert(fiber_id);

            fiber_id
        }
    }

    /// Mark fibers not seen this render for unmount and clear the seen set.
    ///
    /// This should be called after the render phase completes. Any fibers that
    /// were associated with Component instances but not rendered this pass
    /// will be scheduled for unmount.
    pub fn mark_unseen_for_unmount(&mut self) {
        // Find fibers that have component IDs but weren't seen this render
        let unseen: Vec<FiberId> = self
            .fiber_to_component_id
            .keys()
            .filter(|fiber_id| !self.seen_this_render.contains(fiber_id))
            .copied()
            .collect();

        // Schedule them for unmount
        for fiber_id in unseen {
            self.schedule_unmount(fiber_id);
        }

        // Clear the seen set for the next render
        self.seen_this_render.clear();
    }

    /// Clean up component ID mappings when a fiber is removed.
    ///
    /// This should be called when a fiber is unmounted to ensure the
    /// component ID mappings are properly cleaned up.
    pub fn cleanup_component_id_mapping(&mut self, fiber_id: FiberId) {
        if let Some(component_id) = self.fiber_to_component_id.remove(&fiber_id) {
            self.component_id_to_fiber.remove(&component_id);
        }
    }

    /// Called when a component starts rendering
    pub fn begin_render(&mut self, id: FiberId) {
        self.render_stack.push(id);
        if let Some(fiber) = self.fibers.get_mut(&id) {
            fiber.hook_index = 0; // Reset hook index for this component
        }
    }

    /// Called when a component finishes rendering
    pub fn end_render(&mut self) {
        if let Some(fiber_id) = self.render_stack.last().copied() {
            #[cfg(debug_assertions)]
            if let Some(fiber) = self.fibers.get(&fiber_id) {
                fiber.check_hook_order();
            }
        }
        self.render_stack.pop();
    }

    /// Get the currently rendering fiber's ID
    pub fn current_fiber(&self) -> Option<FiberId> {
        self.render_stack.last().copied()
    }

    /// Schedule a fiber for unmount (cleanup runs in effect phase)
    pub fn schedule_unmount(&mut self, id: FiberId) {
        self.pending_unmount.push(id);
    }

    /// Prepare all fibers for a new render pass (reset hook indices)
    pub fn prepare_for_render(&mut self) {
        for fiber in self.fibers.values_mut() {
            fiber.reset_hook_index();
        }
    }

    /// Get a reference to a fiber by ID
    pub fn get(&self, id: FiberId) -> Option<&Fiber> {
        self.fibers.get(&id)
    }

    /// Get a mutable reference to a fiber by ID
    pub fn get_mut(&mut self, id: FiberId) -> Option<&mut Fiber> {
        self.fibers.get_mut(&id)
    }

    /// Remove a fiber from the tree
    pub fn remove(&mut self, id: FiberId) -> Option<Fiber> {
        // Remove from parent's children list
        if let Some(fiber) = self.fibers.get(&id)
            && let Some(parent_id) = fiber.parent
            && let Some(parent) = self.fibers.get_mut(&parent_id)
        {
            parent.children.retain(|&child_id| child_id != id);
        }

        // Clear root if this was the root
        if self.root == Some(id) {
            self.root = None;
        }

        // Clean up component ID mappings
        self.cleanup_component_id_mapping(id);

        self.fibers.remove(&id)
    }

    /// Get all dirty fibers that need re-rendering
    pub fn dirty_fibers(&self) -> HashSet<FiberId> {
        self.fibers
            .iter()
            .filter(|(_, fiber)| fiber.dirty)
            .map(|(id, _)| *id)
            .collect()
    }

    /// Mark a fiber as dirty (needs re-render)
    pub fn mark_dirty(&mut self, id: FiberId) {
        if let Some(fiber) = self.fibers.get_mut(&id) {
            fiber.dirty = true;
        }
    }

    /// Mark a fiber as clean (rendered)
    pub fn mark_clean(&mut self, id: FiberId) {
        if let Some(fiber) = self.fibers.get_mut(&id) {
            fiber.dirty = false;
        }
    }

    /// Process all pending unmounts, cleaning up context and removing fibers.
    ///
    /// This should be called during the commit phase after rendering is complete.
    /// It performs the following for each pending unmount:
    /// 1. Queues all sync and async cleanups from the fiber
    /// 2. Pops all context values provided by the fiber
    /// 3. Removes the fiber from the tree
    ///
    /// Returns the list of fiber IDs that were unmounted.
    pub fn process_unmounts(&mut self) -> Vec<FiberId> {
        use crate::context_stack::pop_context_for_fiber;
        use crate::scheduler::effect_queue::{queue_async_cleanup, queue_cleanup};

        let unmounted: Vec<FiberId> = self.pending_unmount.drain(..).collect();

        for fiber_id in &unmounted {
            // Queue all cleanups from the fiber before removing it
            if let Some(fiber) = self.fibers.get_mut(fiber_id) {
                // Queue sync cleanups in reverse order (LIFO)
                let mut sync_cleanups: Vec<_> = fiber.cleanup_by_hook.drain().collect();
                sync_cleanups.sort_by(|a, b| b.0.cmp(&a.0)); // Sort by hook_index descending
                for (_, cleanup) in sync_cleanups {
                    queue_cleanup(cleanup);
                }

                // Queue async cleanups in reverse order (LIFO)
                let mut async_cleanups: Vec<_> = fiber.async_cleanup_by_hook.drain().collect();
                async_cleanups.sort_by(|a, b| b.0.cmp(&a.0)); // Sort by hook_index descending
                for (_, async_cleanup) in async_cleanups {
                    queue_async_cleanup(async_cleanup);
                }
            }

            // Clean up context values provided by this fiber
            pop_context_for_fiber(*fiber_id);

            // Remove the fiber from the tree
            self.remove(*fiber_id);
        }

        unmounted
    }

    /// Check if there are pending unmounts
    pub fn has_pending_unmounts(&self) -> bool {
        !self.pending_unmount.is_empty()
    }

    /// Get the number of pending unmounts
    pub fn pending_unmount_count(&self) -> usize {
        self.pending_unmount.len()
    }
}

impl Default for FiberTree {
    fn default() -> Self {
        Self::new()
    }
}

/// Set the thread-local fiber tree
pub fn set_fiber_tree(tree: FiberTree) {
    FIBER_TREE.with(|t| {
        *t.borrow_mut() = Some(tree);
    });
}

/// Get a reference to the thread-local fiber tree and execute a closure
pub fn with_fiber_tree<R, F: FnOnce(&FiberTree) -> R>(f: F) -> Option<R> {
    FIBER_TREE.with(|t| t.borrow().as_ref().map(f))
}

/// Get a mutable reference to the thread-local fiber tree and execute a closure
pub fn with_fiber_tree_mut<R, F: FnOnce(&mut FiberTree) -> R>(f: F) -> Option<R> {
    FIBER_TREE.with(|t| t.borrow_mut().as_mut().map(f))
}

/// Clear the thread-local fiber tree
pub fn clear_fiber_tree() {
    FIBER_TREE.with(|t| {
        *t.borrow_mut() = None;
    });
}

/// Execute a closure with the current fiber
pub fn with_current_fiber<R, F: FnOnce(&mut Fiber) -> R>(f: F) -> Option<R> {
    FIBER_TREE.with(|t| {
        let mut tree = t.borrow_mut();
        let tree = tree.as_mut()?;
        let current_id = tree.current_fiber()?;
        tree.fibers.get_mut(&current_id).map(f)
    })
}

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

    #[test]
    fn test_fiber_tree_creation() {
        let tree = FiberTree::new();
        assert!(tree.fibers.is_empty());
        assert!(tree.root.is_none());
        assert!(tree.render_stack.is_empty());
    }

    #[test]
    fn test_mount_root_fiber() {
        let mut tree = FiberTree::new();
        let id = tree.mount(None, None);

        assert_eq!(tree.root, Some(id));
        assert!(tree.fibers.contains_key(&id));
    }

    #[test]
    fn test_mount_child_fiber() {
        let mut tree = FiberTree::new();
        let parent_id = tree.mount(None, None);
        let child_id = tree.mount(Some(parent_id), Some("child".to_string()));

        let parent = tree.get(parent_id).unwrap();
        assert!(parent.children.contains(&child_id));

        let child = tree.get(child_id).unwrap();
        assert_eq!(child.parent, Some(parent_id));
        assert_eq!(child.key, Some("child".to_string()));
    }

    #[test]
    fn test_render_stack() {
        let mut tree = FiberTree::new();
        let id1 = tree.mount(None, None);
        let id2 = tree.mount(Some(id1), None);

        assert!(tree.current_fiber().is_none());

        tree.begin_render(id1);
        assert_eq!(tree.current_fiber(), Some(id1));

        tree.begin_render(id2);
        assert_eq!(tree.current_fiber(), Some(id2));

        tree.end_render();
        assert_eq!(tree.current_fiber(), Some(id1));

        tree.end_render();
        assert!(tree.current_fiber().is_none());
    }

    #[test]
    fn test_schedule_unmount() {
        let mut tree = FiberTree::new();
        let id = tree.mount(None, None);

        tree.schedule_unmount(id);
        assert!(tree.pending_unmount.contains(&id));
    }

    #[test]
    fn test_prepare_for_render() {
        let mut tree = FiberTree::new();
        let id = tree.mount(None, None);

        // Simulate some hook calls
        tree.begin_render(id);
        {
            let fiber = tree.get_mut(id).unwrap();
            fiber.next_hook_index();
            fiber.next_hook_index();
        }
        tree.end_render();

        assert_eq!(tree.get(id).unwrap().hook_index, 2);

        tree.prepare_for_render();
        assert_eq!(tree.get(id).unwrap().hook_index, 0);
    }

    #[test]
    fn test_remove_fiber() {
        let mut tree = FiberTree::new();
        let parent_id = tree.mount(None, None);
        let child_id = tree.mount(Some(parent_id), None);

        tree.remove(child_id);

        assert!(!tree.fibers.contains_key(&child_id));
        let parent = tree.get(parent_id).unwrap();
        assert!(!parent.children.contains(&child_id));
    }

    #[test]
    fn test_dirty_fibers() {
        let mut tree = FiberTree::new();
        let id1 = tree.mount(None, None);
        let id2 = tree.mount(Some(id1), None);

        // Both start dirty
        let dirty = tree.dirty_fibers();
        assert!(dirty.contains(&id1));
        assert!(dirty.contains(&id2));

        tree.mark_clean(id1);
        let dirty = tree.dirty_fibers();
        assert!(!dirty.contains(&id1));
        assert!(dirty.contains(&id2));
    }

    #[test]
    fn test_process_unmounts_removes_fibers() {
        let mut tree = FiberTree::new();
        let id1 = tree.mount(None, None);
        let id2 = tree.mount(Some(id1), None);

        tree.schedule_unmount(id2);
        assert!(tree.has_pending_unmounts());
        assert_eq!(tree.pending_unmount_count(), 1);

        let unmounted = tree.process_unmounts();

        assert_eq!(unmounted, vec![id2]);
        assert!(!tree.fibers.contains_key(&id2));
        assert!(!tree.has_pending_unmounts());
    }

    #[test]
    fn test_process_unmounts_cleans_up_context() {
        use crate::context_stack::{clear_context_stack, get_context, push_context};

        clear_context_stack();

        let mut tree = FiberTree::new();
        let fiber_id = tree.mount(None, None);

        // Simulate a context provider
        push_context(fiber_id, "test-context".to_string());
        assert_eq!(get_context::<String>(), Some("test-context".to_string()));

        // Schedule and process unmount
        tree.schedule_unmount(fiber_id);
        tree.process_unmounts();

        // Context should be cleaned up
        assert_eq!(get_context::<String>(), None);

        clear_context_stack();
    }

    #[test]
    fn test_process_unmounts_multiple_fibers() {
        let mut tree = FiberTree::new();
        let id1 = tree.mount(None, None);
        let id2 = tree.mount(Some(id1), None);
        let id3 = tree.mount(Some(id1), None);

        tree.schedule_unmount(id2);
        tree.schedule_unmount(id3);

        assert_eq!(tree.pending_unmount_count(), 2);

        let unmounted = tree.process_unmounts();

        assert_eq!(unmounted.len(), 2);
        assert!(unmounted.contains(&id2));
        assert!(unmounted.contains(&id3));
        assert!(!tree.fibers.contains_key(&id2));
        assert!(!tree.fibers.contains_key(&id3));
        assert!(tree.fibers.contains_key(&id1)); // Parent still exists
    }

    #[test]
    fn test_process_unmounts_nested_context_cleanup() {
        use crate::context_stack::{clear_context_stack, get_context, push_context};

        clear_context_stack();

        let mut tree = FiberTree::new();
        let outer_fiber = tree.mount(None, None);
        let inner_fiber = tree.mount(Some(outer_fiber), None);

        // Outer provider
        push_context(outer_fiber, "outer".to_string());
        // Inner provider shadows outer
        push_context(inner_fiber, "inner".to_string());

        assert_eq!(get_context::<String>(), Some("inner".to_string()));

        // Unmount inner fiber
        tree.schedule_unmount(inner_fiber);
        tree.process_unmounts();

        // Should now get outer value
        assert_eq!(get_context::<String>(), Some("outer".to_string()));

        // Unmount outer fiber
        tree.schedule_unmount(outer_fiber);
        tree.process_unmounts();

        // No context left
        assert_eq!(get_context::<String>(), None);

        clear_context_stack();
    }

    #[test]
    fn test_has_pending_unmounts() {
        let mut tree = FiberTree::new();
        let id = tree.mount(None, None);

        assert!(!tree.has_pending_unmounts());

        tree.schedule_unmount(id);
        assert!(tree.has_pending_unmounts());

        tree.process_unmounts();
        assert!(!tree.has_pending_unmounts());
    }

    #[test]
    fn test_get_or_create_fiber_by_component_id_creates_new() {
        let mut tree = FiberTree::new();

        let fiber_id = tree.get_or_create_fiber_by_component_id(42);

        assert!(tree.fibers.contains_key(&fiber_id));
        assert!(tree.seen_this_render.contains(&fiber_id));
        assert_eq!(tree.component_id_to_fiber.get(&42), Some(&fiber_id));
        assert_eq!(tree.fiber_to_component_id.get(&fiber_id), Some(&42));
    }

    #[test]
    fn test_get_or_create_fiber_by_component_id_returns_existing() {
        let mut tree = FiberTree::new();

        let fiber_id1 = tree.get_or_create_fiber_by_component_id(42);
        let fiber_id2 = tree.get_or_create_fiber_by_component_id(42);

        assert_eq!(fiber_id1, fiber_id2);
        assert_eq!(tree.fibers.len(), 1);
    }

    #[test]
    fn test_get_or_create_fiber_by_component_id_different_ids() {
        let mut tree = FiberTree::new();

        let fiber_id1 = tree.get_or_create_fiber_by_component_id(42);
        let fiber_id2 = tree.get_or_create_fiber_by_component_id(43);

        assert_ne!(fiber_id1, fiber_id2);
        assert_eq!(tree.fibers.len(), 2);
    }

    #[test]
    fn test_get_or_create_fiber_by_component_id_with_parent() {
        let mut tree = FiberTree::new();
        let parent_id = tree.mount(None, None);

        tree.begin_render(parent_id);
        let child_fiber_id = tree.get_or_create_fiber_by_component_id(100);
        tree.end_render();

        let child = tree.get(child_fiber_id).unwrap();
        assert_eq!(child.parent, Some(parent_id));
    }

    #[test]
    fn test_mark_unseen_for_unmount_schedules_unseen() {
        let mut tree = FiberTree::new();

        // Create two fibers via component IDs
        let fiber_id1 = tree.get_or_create_fiber_by_component_id(1);
        let fiber_id2 = tree.get_or_create_fiber_by_component_id(2);

        // Clear seen set and only mark fiber_id1 as seen
        tree.seen_this_render.clear();
        tree.seen_this_render.insert(fiber_id1);

        tree.mark_unseen_for_unmount();

        // fiber_id2 should be scheduled for unmount
        assert!(tree.pending_unmount.contains(&fiber_id2));
        assert!(!tree.pending_unmount.contains(&fiber_id1));
        assert!(tree.seen_this_render.is_empty());
    }

    #[test]
    fn test_mark_unseen_for_unmount_clears_seen_set() {
        let mut tree = FiberTree::new();

        tree.get_or_create_fiber_by_component_id(1);
        assert!(!tree.seen_this_render.is_empty());

        tree.mark_unseen_for_unmount();
        assert!(tree.seen_this_render.is_empty());
    }

    #[test]
    fn test_cleanup_component_id_mapping() {
        let mut tree = FiberTree::new();

        let fiber_id = tree.get_or_create_fiber_by_component_id(42);

        assert!(tree.component_id_to_fiber.contains_key(&42));
        assert!(tree.fiber_to_component_id.contains_key(&fiber_id));

        tree.cleanup_component_id_mapping(fiber_id);

        assert!(!tree.component_id_to_fiber.contains_key(&42));
        assert!(!tree.fiber_to_component_id.contains_key(&fiber_id));
    }

    #[test]
    fn test_remove_cleans_up_component_id_mapping() {
        let mut tree = FiberTree::new();

        let fiber_id = tree.get_or_create_fiber_by_component_id(42);

        tree.remove(fiber_id);

        assert!(!tree.component_id_to_fiber.contains_key(&42));
        assert!(!tree.fiber_to_component_id.contains_key(&fiber_id));
    }

    #[test]
    fn test_fiber_lifecycle_full_cycle() {
        let mut tree = FiberTree::new();

        // First render: create fiber
        let fiber_id = tree.get_or_create_fiber_by_component_id(42);
        tree.mark_unseen_for_unmount();

        // Second render: fiber is seen again
        let fiber_id2 = tree.get_or_create_fiber_by_component_id(42);
        assert_eq!(fiber_id, fiber_id2);
        tree.mark_unseen_for_unmount();

        // Third render: fiber is NOT rendered (component removed)
        // Don't call get_or_create_fiber_by_component_id
        tree.mark_unseen_for_unmount();

        // Fiber should be scheduled for unmount
        assert!(tree.pending_unmount.contains(&fiber_id));
    }
}

#[cfg(test)]
mod property_tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// **Property 2: Fiber Lifecycle Management**
        /// **Validates: Requirements 1.5, 2.1, 2.2, 2.3**
        ///
        /// For any Component render, a fiber is created/retrieved, set as current
        /// during render, and restored after.
        #[test]
        fn prop_fiber_lifecycle_management(
            component_ids in prop::collection::vec(1u64..10000, 1..20),
            render_passes in 1usize..5
        ) {
            let mut tree = FiberTree::new();
            let mut created_fibers: HashMap<u64, FiberId> = HashMap::new();

            for _pass in 0..render_passes {
                // Simulate rendering each component
                for &component_id in &component_ids {
                    let fiber_id = tree.get_or_create_fiber_by_component_id(component_id);

                    // Property: Same component ID always returns same fiber
                    if let Some(&existing_fiber_id) = created_fibers.get(&component_id) {
                        prop_assert_eq!(fiber_id, existing_fiber_id,
                            "Component ID {} should always map to same fiber", component_id);
                    } else {
                        created_fibers.insert(component_id, fiber_id);
                    }

                    // Property: Fiber exists in tree
                    prop_assert!(tree.fibers.contains_key(&fiber_id),
                        "Fiber {} should exist in tree", fiber_id.0);

                    // Property: Fiber is marked as seen
                    prop_assert!(tree.seen_this_render.contains(&fiber_id),
                        "Fiber {} should be marked as seen", fiber_id.0);

                    // Property: begin_render sets current fiber
                    tree.begin_render(fiber_id);
                    prop_assert_eq!(tree.current_fiber(), Some(fiber_id),
                        "Current fiber should be {} during render", fiber_id.0);

                    // Property: end_render restores previous context
                    tree.end_render();
                    prop_assert!(tree.current_fiber().is_none(),
                        "Current fiber should be None after end_render");
                }

                tree.mark_unseen_for_unmount();
            }
        }

        /// Property: Unseen fibers are scheduled for unmount
        /// **Validates: Requirements 2.5**
        #[test]
        fn prop_unseen_fibers_scheduled_for_unmount(
            initial_ids in prop::collection::vec(1u64..10000, 1..10),
            surviving_ids in prop::collection::vec(1u64..10000, 0..5)
        ) {
            let mut tree = FiberTree::new();

            // Create fibers for all initial IDs
            let mut fiber_map: HashMap<u64, FiberId> = HashMap::new();
            for &id in &initial_ids {
                let fiber_id = tree.get_or_create_fiber_by_component_id(id);
                fiber_map.insert(id, fiber_id);
            }
            tree.mark_unseen_for_unmount();

            // Second render: only surviving_ids are rendered
            for &id in &surviving_ids {
                tree.get_or_create_fiber_by_component_id(id);
            }
            tree.mark_unseen_for_unmount();

            // Property: Fibers not in surviving_ids should be scheduled for unmount
            for (&component_id, &fiber_id) in &fiber_map {
                let should_survive = surviving_ids.contains(&component_id);
                let is_pending_unmount = tree.pending_unmount.contains(&fiber_id);

                if !should_survive {
                    prop_assert!(is_pending_unmount,
                        "Fiber for component {} should be scheduled for unmount", component_id);
                }
            }
        }

        /// Property: Component ID mappings are bidirectional and consistent
        /// **Validates: Requirements 2.4**
        #[test]
        fn prop_component_id_mapping_consistency(
            component_ids in prop::collection::vec(1u64..10000, 1..20)
        ) {
            let mut tree = FiberTree::new();

            for &component_id in &component_ids {
                let fiber_id = tree.get_or_create_fiber_by_component_id(component_id);

                // Property: Bidirectional mapping is consistent
                prop_assert_eq!(
                    tree.component_id_to_fiber.get(&component_id),
                    Some(&fiber_id),
                    "component_id_to_fiber should map {} to {:?}", component_id, fiber_id
                );
                prop_assert_eq!(
                    tree.fiber_to_component_id.get(&fiber_id),
                    Some(&component_id),
                    "fiber_to_component_id should map {:?} to {}", fiber_id, component_id
                );
            }
        }
    }
}