ratatui-spatial-splits 0.1.0

Pure geometry engine for spatial split management in ratatui applications
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
//! Split manager: binary tree of splits with area caching.

use ratatui::layout::Rect;

use crate::navigation;
use crate::types::{AreaId, CloseResult, SplitNode, SplitResult};

/// A computed area for a leaf in the split tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SplitArea {
    /// The unique identifier for this area.
    pub id: AreaId,
    /// The computed pixel rectangle.
    pub rect: Rect,
}

/// Pure geometry engine for managing spatial splits.
///
/// Manages a binary tree of horizontal and vertical splits, computing
/// pixel-accurate [`Rect`] areas for each leaf. The tree is mutated via
/// [`split_horizontal`](SplitManager::split_horizontal),
/// [`split_vertical`](SplitManager::split_vertical),
/// [`close`](SplitManager::close), and
/// [`resize`](SplitManager::resize).
///
/// Areas are cached and automatically recalculated when the tree is mutated
/// or the viewport changes.
#[derive(Debug, Clone)]
pub struct SplitManager {
    /// Root of the split tree.
    root: SplitNode,
    /// Next ID counter for new AreaIds.
    next_id: u64,
    /// Cached areas (recalculated when dirty).
    cached_areas: Vec<SplitArea>,
    /// Cached viewport rect.
    total_area: Rect,
    /// Whether the cache is dirty and needs recalculation.
    dirty: bool,
}

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

impl SplitManager {
    /// Creates a new split manager with a single leaf.
    ///
    /// The initial leaf gets `AreaId(1)`. The viewport defaults to zero-sized,
    /// so you must call [`set_viewport`](Self::set_viewport) before areas are meaningful.
    #[must_use]
    pub fn new() -> Self {
        let initial_id = AreaId(1);
        Self {
            root: SplitNode::Leaf { id: initial_id },
            next_id: 2,
            cached_areas: Vec::new(),
            total_area: Rect::default(),
            dirty: true,
        }
    }

    // ── Geometry ──────────────────────────────────────────────────────

    /// Returns the computed areas for all leaves.
    ///
    /// Triggers a recalculation if the cache is dirty.
    pub fn areas(&mut self) -> &[SplitArea] {
        self.recalculate_if_dirty();
        &self.cached_areas
    }

    /// Returns the area for a specific leaf ID, if it exists.
    pub fn area_for_id(&mut self, id: AreaId) -> Option<Rect> {
        self.recalculate_if_dirty();
        self.cached_areas
            .iter()
            .find(|a| a.id == id)
            .map(|a| a.rect)
    }

    /// Updates the viewport rect and marks the cache as dirty.
    pub fn set_viewport(&mut self, rect: Rect) -> &[SplitArea] {
        if rect != self.total_area {
            self.total_area = rect;
            self.dirty = true;
        }
        self.areas()
    }

    // ── Navigation ────────────────────────────────────────────────────

    /// Finds the neighboring leaf in the given direction from `current_id`.
    ///
    /// Uses beam/raycasting against cached areas.
    pub fn navigate(
        &mut self,
        current_id: AreaId,
        direction: crate::navigation::Direction,
    ) -> Option<AreaId> {
        self.recalculate_if_dirty();
        navigation::navigate(&self.cached_areas, current_id, direction)
    }

    // ── Mutations ─────────────────────────────────────────────────────

    /// Splits the leaf with the given ID horizontally (top/bottom).
    ///
    /// The original leaf becomes the top child, and a new leaf is created
    /// as the bottom child. Returns `None` if the ID is not a leaf.
    pub fn split_horizontal(&mut self, id: AreaId) -> Option<SplitResult> {
        let new_id = AreaId(self.next_id);
        self.next_id += 1;

        let new_leaf = SplitNode::Leaf { id: new_id };
        let found = self.replace_leaf(id, |old| SplitNode::Horizontal {
            top: Box::new(old),
            bottom: Box::new(new_leaf.clone()),
            ratio: 0.5,
        });

        if found {
            self.dirty = true;
            Some(SplitResult {
                original: id,
                new: new_id,
            })
        } else {
            None
        }
    }

    /// Splits the leaf with the given ID vertically (left/right).
    ///
    /// The original leaf becomes the left child, and a new leaf is created
    /// as the right child. Returns `None` if the ID is not a leaf.
    pub fn split_vertical(&mut self, id: AreaId) -> Option<SplitResult> {
        let new_id = AreaId(self.next_id);
        self.next_id += 1;

        let new_leaf = SplitNode::Leaf { id: new_id };
        let found = self.replace_leaf(id, |old| SplitNode::Vertical {
            left: Box::new(old),
            right: Box::new(new_leaf.clone()),
            ratio: 0.5,
        });

        if found {
            self.dirty = true;
            Some(SplitResult {
                original: id,
                new: new_id,
            })
        } else {
            None
        }
    }

    /// Closes (removes) the leaf with the given ID.
    ///
    /// The sibling of the closed leaf replaces their parent node.
    /// Returns `None` if the ID is not found or is the only leaf.
    pub fn close(&mut self, id: AreaId) -> Option<CloseResult> {
        if self.is_single_leaf() {
            return None;
        }

        let sibling_id = self.find_sibling_id(id)?;
        let found = self.remove_leaf(id);

        if found {
            self.dirty = true;
            Some(CloseResult {
                removed: id,
                surviving: sibling_id,
            })
        } else {
            None
        }
    }

    /// Resizes the split containing the given leaf by adjusting the ratio.
    ///
    /// `amount` is in character units (positive = grow first child, negative = shrink).
    /// Returns `true` if a resize was actually performed.
    pub fn resize(
        &mut self,
        id: AreaId,
        direction: crate::navigation::Direction,
        amount: i16,
    ) -> bool {
        let total_size = match direction {
            crate::navigation::Direction::Left | crate::navigation::Direction::Right => {
                self.total_area.width
            }
            crate::navigation::Direction::Up | crate::navigation::Direction::Down => {
                self.total_area.height
            }
        };

        if total_size == 0 {
            return false;
        }

        let adjusted = self.adjust_parent_ratio(id, direction, amount, total_size);
        if adjusted {
            self.dirty = true;
        }
        adjusted
    }

    // ── Queries ───────────────────────────────────────────────────────

    /// Returns all leaf AreaIds in the tree.
    pub fn leaves(&self) -> Vec<AreaId> {
        let mut result = Vec::new();
        Self::collect_leaves(&self.root, &mut result);
        result
    }

    /// Returns `true` if the tree contains a leaf with the given ID.
    pub fn contains(&self, id: AreaId) -> bool {
        Self::contains_recursive(&self.root, id)
    }

    /// Returns `true` if the tree consists of a single leaf.
    pub fn is_single_leaf(&self) -> bool {
        self.root.is_leaf()
    }

    /// Returns the AreaId of the root leaf (only valid for single-leaf trees).
    ///
    /// # Panics
    ///
    /// Panics if the tree is not a single leaf.
    pub fn root_id(&self) -> AreaId {
        self.root
            .leaf_id()
            .expect("root should always be a leaf when called on single-leaf tree")
    }

    // ── Private helpers ───────────────────────────────────────────────

    fn recalculate_if_dirty(&mut self) {
        if !self.dirty {
            return;
        }
        self.cached_areas.clear();
        Self::compute_areas(&self.root, self.total_area, &mut self.cached_areas);
        self.dirty = false;
    }

    fn compute_areas(node: &SplitNode, rect: Rect, out: &mut Vec<SplitArea>) {
        match node {
            SplitNode::Leaf { id } => {
                out.push(SplitArea { id: *id, rect });
            }
            SplitNode::Horizontal { top, bottom, ratio } => {
                let total_height = f64::from(rect.height);
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                let top_height = (total_height * ratio).round() as u16;
                let bottom_height = rect.height.saturating_sub(top_height);
                let top_rect = Rect::new(rect.x, rect.y, rect.width, top_height);
                let bottom_rect = Rect::new(
                    rect.x,
                    rect.y.saturating_add(top_height),
                    rect.width,
                    bottom_height,
                );
                Self::compute_areas(top, top_rect, out);
                Self::compute_areas(bottom, bottom_rect, out);
            }
            SplitNode::Vertical { left, right, ratio } => {
                let total_width = f64::from(rect.width);
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                let left_width = (total_width * ratio).round() as u16;
                let right_width = rect.width.saturating_sub(left_width);
                let left_rect = Rect::new(rect.x, rect.y, left_width, rect.height);
                let right_rect = Rect::new(
                    rect.x.saturating_add(left_width),
                    rect.y,
                    right_width,
                    rect.height,
                );
                Self::compute_areas(left, left_rect, out);
                Self::compute_areas(right, right_rect, out);
            }
        }
    }

    fn collect_leaves(node: &SplitNode, out: &mut Vec<AreaId>) {
        match node {
            SplitNode::Leaf { id } => out.push(*id),
            SplitNode::Horizontal { top, bottom, .. } => {
                Self::collect_leaves(top, out);
                Self::collect_leaves(bottom, out);
            }
            SplitNode::Vertical { left, right, .. } => {
                Self::collect_leaves(left, out);
                Self::collect_leaves(right, out);
            }
        }
    }

    fn contains_recursive(node: &SplitNode, id: AreaId) -> bool {
        match node {
            SplitNode::Leaf { id: leaf_id } => *leaf_id == id,
            SplitNode::Horizontal { top, bottom, .. } => {
                Self::contains_recursive(top, id) || Self::contains_recursive(bottom, id)
            }
            SplitNode::Vertical { left, right, .. } => {
                Self::contains_recursive(left, id) || Self::contains_recursive(right, id)
            }
        }
    }

    /// Replaces a leaf node identified by `id` with the result of `f`.
    /// Returns `true` if a replacement was made.
    fn replace_leaf(&mut self, id: AreaId, mut f: impl FnMut(SplitNode) -> SplitNode) -> bool {
        Self::replace_leaf_recursive(&mut self.root, id, &mut f)
    }

    fn replace_leaf_recursive(
        node: &mut SplitNode,
        id: AreaId,
        f: &mut dyn FnMut(SplitNode) -> SplitNode,
    ) -> bool {
        match node {
            SplitNode::Leaf { id: leaf_id } if *leaf_id == id => {
                let old = std::mem::replace(node, SplitNode::Leaf { id: AreaId(0) });
                *node = f(old);
                true
            }
            SplitNode::Horizontal { top, bottom, .. } => {
                Self::replace_leaf_recursive(top, id, f)
                    || Self::replace_leaf_recursive(bottom, id, f)
            }
            SplitNode::Vertical { left, right, .. } => {
                Self::replace_leaf_recursive(left, id, f)
                    || Self::replace_leaf_recursive(right, id, f)
            }
            _ => false,
        }
    }

    /// Finds the sibling AreaId of the given leaf.
    fn find_sibling_id(&self, id: AreaId) -> Option<AreaId> {
        Self::find_sibling_recursive(&self.root, id)
    }

    fn find_sibling_recursive(node: &SplitNode, id: AreaId) -> Option<AreaId> {
        match node {
            SplitNode::Leaf { .. } => None,
            SplitNode::Horizontal { top, bottom, .. } => {
                if Self::contains_recursive(top, id) {
                    if top.is_leaf() && top.leaf_id() == Some(id) {
                        Self::first_leaf(bottom)
                    } else {
                        Self::find_sibling_recursive(top, id)
                    }
                } else if bottom.is_leaf() && bottom.leaf_id() == Some(id) {
                    Self::first_leaf(top)
                } else {
                    Self::find_sibling_recursive(bottom, id)
                }
            }
            SplitNode::Vertical { left, right, .. } => {
                if Self::contains_recursive(left, id) {
                    if left.is_leaf() && left.leaf_id() == Some(id) {
                        Self::first_leaf(right)
                    } else {
                        Self::find_sibling_recursive(left, id)
                    }
                } else if right.is_leaf() && right.leaf_id() == Some(id) {
                    Self::first_leaf(left)
                } else {
                    Self::find_sibling_recursive(right, id)
                }
            }
        }
    }

    fn first_leaf(node: &SplitNode) -> Option<AreaId> {
        match node {
            SplitNode::Leaf { id } => Some(*id),
            SplitNode::Horizontal { top, .. } => Self::first_leaf(top),
            SplitNode::Vertical { left, .. } => Self::first_leaf(left),
        }
    }

    /// Removes a leaf and promotes its sibling to replace the parent.
    fn remove_leaf(&mut self, id: AreaId) -> bool {
        Self::remove_leaf_recursive(&mut self.root, id)
    }

    fn remove_leaf_recursive(node: &mut SplitNode, id: AreaId) -> bool {
        match node {
            SplitNode::Leaf { .. } => false,
            SplitNode::Horizontal { top, bottom, .. } => {
                if top.is_leaf() && top.leaf_id() == Some(id) {
                    let sibling =
                        std::mem::replace(bottom.as_mut(), SplitNode::Leaf { id: AreaId(0) });
                    *node = sibling;
                    true
                } else if bottom.is_leaf() && bottom.leaf_id() == Some(id) {
                    let sibling =
                        std::mem::replace(top.as_mut(), SplitNode::Leaf { id: AreaId(0) });
                    *node = sibling;
                    true
                } else {
                    Self::remove_leaf_recursive(top.as_mut(), id)
                        || Self::remove_leaf_recursive(bottom.as_mut(), id)
                }
            }
            SplitNode::Vertical { left, right, .. } => {
                if left.is_leaf() && left.leaf_id() == Some(id) {
                    let sibling =
                        std::mem::replace(right.as_mut(), SplitNode::Leaf { id: AreaId(0) });
                    *node = sibling;
                    true
                } else if right.is_leaf() && right.leaf_id() == Some(id) {
                    let sibling =
                        std::mem::replace(left.as_mut(), SplitNode::Leaf { id: AreaId(0) });
                    *node = sibling;
                    true
                } else {
                    Self::remove_leaf_recursive(left.as_mut(), id)
                        || Self::remove_leaf_recursive(right.as_mut(), id)
                }
            }
        }
    }

    /// Adjusts the parent split ratio for the given leaf in the given direction.
    fn adjust_parent_ratio(
        &mut self,
        id: AreaId,
        direction: crate::navigation::Direction,
        amount: i16,
        total_size: u16,
    ) -> bool {
        Self::adjust_ratio_recursive(&mut self.root, id, direction, amount, total_size)
    }

    #[allow(clippy::too_many_lines)]
    fn adjust_ratio_recursive(
        node: &mut SplitNode,
        id: AreaId,
        direction: crate::navigation::Direction,
        amount: i16,
        total_size: u16,
    ) -> bool {
        match node {
            SplitNode::Leaf { .. } => false,
            SplitNode::Horizontal { top, bottom, ratio } => {
                // Check direct-leaf matches first, regardless of which subtree contains id
                if top.is_leaf() && top.leaf_id() == Some(id) {
                    match direction {
                        crate::navigation::Direction::Down => {
                            let delta = f64::from(amount) / f64::from(total_size);
                            *ratio = (*ratio + delta).clamp(0.1, 0.9);
                            true
                        }
                        crate::navigation::Direction::Up => {
                            let delta = f64::from(amount) / f64::from(total_size);
                            *ratio = (*ratio - delta).clamp(0.1, 0.9);
                            true
                        }
                        _ => Self::adjust_ratio_recursive(top, id, direction, amount, total_size),
                    }
                } else if bottom.is_leaf() && bottom.leaf_id() == Some(id) {
                    match direction {
                        crate::navigation::Direction::Up => {
                            let delta = f64::from(amount) / f64::from(total_size);
                            *ratio = (*ratio + delta).clamp(0.1, 0.9);
                            true
                        }
                        crate::navigation::Direction::Down => {
                            let delta = f64::from(amount) / f64::from(total_size);
                            *ratio = (*ratio - delta).clamp(0.1, 0.9);
                            true
                        }
                        _ => {
                            Self::adjust_ratio_recursive(bottom, id, direction, amount, total_size)
                        }
                    }
                } else if Self::contains_recursive(top, id) {
                    Self::adjust_ratio_recursive(top, id, direction, amount, total_size)
                } else {
                    Self::adjust_ratio_recursive(bottom, id, direction, amount, total_size)
                }
            }
            SplitNode::Vertical { left, right, ratio } => {
                // Check direct-leaf matches first, regardless of which subtree contains id
                if left.is_leaf() && left.leaf_id() == Some(id) {
                    match direction {
                        crate::navigation::Direction::Right => {
                            let delta = f64::from(amount) / f64::from(total_size);
                            *ratio = (*ratio + delta).clamp(0.1, 0.9);
                            true
                        }
                        crate::navigation::Direction::Left => {
                            let delta = f64::from(amount) / f64::from(total_size);
                            *ratio = (*ratio - delta).clamp(0.1, 0.9);
                            true
                        }
                        _ => Self::adjust_ratio_recursive(left, id, direction, amount, total_size),
                    }
                } else if right.is_leaf() && right.leaf_id() == Some(id) {
                    match direction {
                        crate::navigation::Direction::Left => {
                            let delta = f64::from(amount) / f64::from(total_size);
                            *ratio = (*ratio + delta).clamp(0.1, 0.9);
                            true
                        }
                        crate::navigation::Direction::Right => {
                            let delta = f64::from(amount) / f64::from(total_size);
                            *ratio = (*ratio - delta).clamp(0.1, 0.9);
                            true
                        }
                        _ => Self::adjust_ratio_recursive(right, id, direction, amount, total_size),
                    }
                } else if Self::contains_recursive(left, id) {
                    Self::adjust_ratio_recursive(left, id, direction, amount, total_size)
                } else {
                    Self::adjust_ratio_recursive(right, id, direction, amount, total_size)
                }
            }
        }
    }
}

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

    #[test]
    fn new_creates_single_leaf() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));
        let areas = mgr.areas();
        assert_eq!(areas.len(), 1);
        assert_eq!(areas[0].id, AreaId(1));
        assert_eq!(areas[0].rect, Rect::new(0, 0, 100, 100));
    }

    #[test]
    fn split_vertical_creates_two_areas() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));

        let result = mgr.split_vertical(AreaId(1)).unwrap();
        assert_eq!(result.original, AreaId(1));
        assert_eq!(result.new, AreaId(2));

        let areas = mgr.areas();
        assert_eq!(areas.len(), 2);
        assert_eq!(areas[0].id, AreaId(1));
        assert_eq!(areas[0].rect, Rect::new(0, 0, 50, 100));
        assert_eq!(areas[1].id, AreaId(2));
        assert_eq!(areas[1].rect, Rect::new(50, 0, 50, 100));
    }

    #[test]
    fn split_horizontal_creates_two_areas() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));

        let result = mgr.split_horizontal(AreaId(1)).unwrap();
        assert_eq!(result.new, AreaId(2));

        let areas = mgr.areas();
        assert_eq!(areas.len(), 2);
        assert_eq!(areas[0].rect, Rect::new(0, 0, 100, 50));
        assert_eq!(areas[1].rect, Rect::new(0, 50, 100, 50));
    }

    #[test]
    fn nested_splits() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));

        mgr.split_vertical(AreaId(1)).unwrap();
        mgr.split_horizontal(AreaId(2)).unwrap();

        let areas = mgr.areas();
        assert_eq!(areas.len(), 3);

        assert_eq!(areas[0].id, AreaId(1));
        assert_eq!(areas[0].rect, Rect::new(0, 0, 50, 100));

        assert_eq!(areas[1].id, AreaId(2));
        assert_eq!(areas[1].rect, Rect::new(50, 0, 50, 50));

        assert_eq!(areas[2].id, AreaId(3));
        assert_eq!(areas[2].rect, Rect::new(50, 50, 50, 50));
    }

    #[test]
    fn close_promotes_sibling() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));
        mgr.split_vertical(AreaId(1)).unwrap();

        let result = mgr.close(AreaId(2)).unwrap();
        assert_eq!(result.removed, AreaId(2));
        assert_eq!(result.surviving, AreaId(1));

        let areas = mgr.areas();
        assert_eq!(areas.len(), 1);
        assert_eq!(areas[0].rect, Rect::new(0, 0, 100, 100));
    }

    #[test]
    fn close_only_leaf_returns_none() {
        let mut mgr = SplitManager::new();
        assert!(mgr.close(AreaId(1)).is_none());
    }

    #[test]
    fn resize_changes_proportions() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));
        mgr.split_vertical(AreaId(1)).unwrap();

        assert!(mgr.resize(AreaId(1), Direction::Right, 10));

        let areas = mgr.areas();
        assert!(areas[0].rect.width > 50);
        assert!(areas[1].rect.width < 50);
    }

    #[test]
    fn cache_invalidated_on_mutation() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));

        let areas = mgr.areas();
        assert_eq!(areas.len(), 1);

        mgr.split_vertical(AreaId(1)).unwrap();
        let areas = mgr.areas();
        assert_eq!(areas.len(), 2);
    }

    #[test]
    fn leaves_returns_all_ids() {
        let mut mgr = SplitManager::new();
        mgr.split_vertical(AreaId(1)).unwrap();
        mgr.split_horizontal(AreaId(2)).unwrap();

        let mut leaves = mgr.leaves();
        leaves.sort();
        assert_eq!(leaves, vec![AreaId(1), AreaId(2), AreaId(3)]);
    }

    #[test]
    fn contains_checks_existence() {
        let mgr = SplitManager::new();
        assert!(mgr.contains(AreaId(1)));
        assert!(!mgr.contains(AreaId(99)));
    }

    #[test]
    fn is_single_leaf() {
        let mut mgr = SplitManager::new();
        assert!(mgr.is_single_leaf());
        mgr.split_vertical(AreaId(1)).unwrap();
        assert!(!mgr.is_single_leaf());
    }

    #[test]
    fn navigate_between_splits() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));
        mgr.split_vertical(AreaId(1)).unwrap();

        assert_eq!(mgr.navigate(AreaId(1), Direction::Right), Some(AreaId(2)));
        assert_eq!(mgr.navigate(AreaId(2), Direction::Left), Some(AreaId(1)));
        assert_eq!(mgr.navigate(AreaId(1), Direction::Left), None);
    }

    #[test]
    fn navigate_nested_splits() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));
        mgr.split_vertical(AreaId(1)).unwrap();
        mgr.split_horizontal(AreaId(2)).unwrap();

        assert_eq!(mgr.navigate(AreaId(1), Direction::Right), Some(AreaId(2)));
        assert_eq!(mgr.navigate(AreaId(2), Direction::Left), Some(AreaId(1)));
        assert_eq!(mgr.navigate(AreaId(3), Direction::Up), Some(AreaId(2)));
        assert_eq!(mgr.navigate(AreaId(2), Direction::Down), Some(AreaId(3)));
    }

    #[test]
    fn area_for_id_returns_correct_rect() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));
        mgr.split_vertical(AreaId(1)).unwrap();

        assert_eq!(mgr.area_for_id(AreaId(1)), Some(Rect::new(0, 0, 50, 100)));
        assert_eq!(mgr.area_for_id(AreaId(2)), Some(Rect::new(50, 0, 50, 100)));
        assert_eq!(mgr.area_for_id(AreaId(99)), None);
    }

    #[test]
    fn split_nonexistent_returns_none() {
        let mut mgr = SplitManager::new();
        assert!(mgr.split_vertical(AreaId(99)).is_none());
    }

    #[test]
    fn four_way_split_scenario() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));

        mgr.split_vertical(AreaId(1)).unwrap();
        mgr.split_horizontal(AreaId(1)).unwrap();
        mgr.split_horizontal(AreaId(2)).unwrap();

        let areas = mgr.areas();
        assert_eq!(areas.len(), 4);

        for area in areas {
            assert!(area.rect.width > 0);
            assert!(area.rect.height > 0);
        }
    }

    #[test]
    fn resize_works_from_right_child() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));
        mgr.split_vertical(AreaId(1)).unwrap();

        assert!(mgr.resize(AreaId(2), Direction::Right, 10));

        let areas = mgr.areas();
        assert!(areas[0].rect.width < 50);
        assert!(areas[1].rect.width > 50);
    }

    #[test]
    fn resize_works_from_bottom_child() {
        let mut mgr = SplitManager::new();
        mgr.set_viewport(Rect::new(0, 0, 100, 100));
        mgr.split_horizontal(AreaId(1)).unwrap();

        assert!(mgr.resize(AreaId(2), Direction::Down, 10));

        let areas = mgr.areas();
        assert!(areas[0].rect.height < 50);
        assert!(areas[1].rect.height > 50);
    }
}