gpui-base 0.6.0

Behavior, interaction, and infrastructure foundations for GPUI 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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
use std::collections::HashMap;

use gpui::{Bounds, Pixels};

use crate::Placement;

use super::node::{NodeId, NodeKind, PaneNode, PanelId, TilePanel};
use super::tree::PaneTree;

/// Where a panel should land.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum InsertTarget {
    /// Into an existing tab group, optionally at a specific index.
    Tabs {
        node: NodeId,
        ix: Option<usize>,
        activate: bool,
    },
    /// Beside an existing node, creating a new tab group for the panel.
    Split {
        node: NodeId,
        placement: Placement,
        size: Option<Pixels>,
    },
    /// Onto a tiles canvas at the given bounds.
    Tile {
        node: NodeId,
        bounds: Bounds<Pixels>,
    },
}

/// What one edit changed.
///
/// Only whether anything changed, for now. An earlier revision also carried
/// the created and removed nodes, the removed panels, and the activation
/// edges — but nothing outside tests ever read them, and computing them meant
/// cloning the whole tree on every edit to diff against, on a path that a
/// tile drag walks once per mouse move. Fields are private, so any of them
/// can come back the day something needs one.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EditResult {
    changed: bool,
}

impl EditResult {
    pub fn changed(&self) -> bool {
        self.changed
    }
}

impl PaneTree {
    pub fn insert_panel(&mut self, panel: PanelId, target: InsertTarget) -> EditResult {
        self.edit(|tree| tree.apply_insert(panel, target))
    }

    pub fn remove_panel(&mut self, panel: PanelId) -> EditResult {
        self.edit(|tree| tree.detach_panel(panel))
    }

    /// Move a panel to a new home without ever removing it from the tree's
    /// perspective, so the caller never fires `on_removed` for a drag.
    pub fn move_panel(&mut self, panel: PanelId, target: InsertTarget) -> EditResult {
        self.edit(|tree| {
            let detached = tree.detach_panel(panel);
            let inserted = tree.apply_insert(panel, target);
            detached || inserted
        })
    }

    pub fn split(
        &mut self,
        at: NodeId,
        panel: PanelId,
        placement: Placement,
        size: Option<Pixels>,
    ) -> EditResult {
        self.insert_panel(
            panel,
            InsertTarget::Split {
                node: at,
                placement,
                size,
            },
        )
    }

    pub fn set_active(&mut self, node: NodeId, ix: usize) -> EditResult {
        self.edit(|tree| {
            let Some(path) = tree.path_of_node(node) else {
                return false;
            };
            let NodeKind::Tabs { active_ix, .. } = tree.node_at_mut(&path).kind_mut() else {
                return false;
            };
            if *active_ix == ix {
                return false;
            }
            *active_ix = ix;
            true
        })
    }

    /// Replace a split's slot sizes wholesale.
    ///
    /// A no-op, like every other operation given input it cannot resolve, if
    /// `new_sizes.len()` does not match the split's child count: no rule in
    /// `normalize` repairs a length mismatch, so applying it would otherwise
    /// leave `children.len() != sizes.len()` and trip `normalize`'s
    /// `debug_assert!`.
    pub fn set_sizes(&mut self, node: NodeId, new_sizes: Vec<Option<Pixels>>) -> EditResult {
        self.edit(|tree| {
            let Some(path) = tree.path_of_node(node) else {
                return false;
            };
            let NodeKind::Split {
                children, sizes, ..
            } = tree.node_at_mut(&path).kind_mut()
            else {
                return false;
            };
            if new_sizes.len() != children.len() || *sizes == new_sizes {
                return false;
            }
            *sizes = new_sizes;
            true
        })
    }

    pub fn set_tile_bounds(&mut self, panel: PanelId, bounds: Bounds<Pixels>) -> EditResult {
        self.edit(|tree| {
            let mut changed = false;
            tree.with_tile(panel, |tile| {
                if tile.bounds() != bounds {
                    *tile = tile.with_bounds(bounds);
                    changed = true;
                }
            });
            changed
        })
    }

    pub fn bring_to_front(&mut self, panel: PanelId) -> EditResult {
        self.edit(|tree| {
            let top = tree.max_z_index();
            let mut changed = false;
            tree.with_tile(panel, |tile| {
                // Already on top is a no-op rather than another increment, so
                // repeatedly grabbing the front tile neither churns the tree
                // nor lets z-indices climb forever.
                if tile.z_index() < top {
                    *tile = tile.with_z_index(top + 1);
                    changed = true;
                }
            });
            changed
        })
    }
}

impl PaneTree {
    /// Replace every split's slot sizes with what that split is actually drawn
    /// at.
    ///
    /// A layout is usually built with unconstrained slots, and `None` stays
    /// `None` in the tree no matter how the split is later measured or
    /// dragged. That is fine until an edit has to divide space — dropping a
    /// panel beside another one has to halve *something*, and it cannot halve
    /// an unknown. Adopting the measured sizes first turns the question into
    /// arithmetic on real pixels, and it matches what the person dragging
    /// sees: the layout on screen is the layout being divided.
    pub(crate) fn adopt_measured_sizes(&mut self, measured: &HashMap<NodeId, Vec<Pixels>>) {
        fn walk(node: &mut PaneNode, measured: &HashMap<NodeId, Vec<Pixels>>) {
            let id = node.id();
            let NodeKind::Split {
                children, sizes, ..
            } = node.kind_mut()
            else {
                return;
            };

            if let Some(actual) = measured.get(&id) {
                if actual.len() == sizes.len() {
                    for (slot, size) in sizes.iter_mut().zip(actual) {
                        // A zero means the split has not been laid out yet, so
                        // the slot keeps whatever it already had.
                        if *size > Pixels::ZERO {
                            *slot = Some(*size);
                        }
                    }
                }
            }

            for child in children.iter_mut() {
                walk(child, measured);
            }
        }

        walk(self.root_mut(), measured);
    }
}

impl PaneTree {
    /// Apply one mutation, then collapse.
    ///
    /// `apply` reports whether it changed anything and normalization reports
    /// the same, so no snapshot of the previous tree is needed to answer the
    /// only question a caller asks. A mutation that cannot resolve its target
    /// returns `false` and the whole edit is a no-op.
    fn edit(&mut self, apply: impl FnOnce(&mut Self) -> bool) -> EditResult {
        let mutated = apply(self);
        let collapsed = self.normalize_reporting();

        EditResult {
            changed: mutated || collapsed,
        }
    }

    /// Whether `panel` is anywhere in this tree.
    pub fn contains_panel(&self, panel: PanelId) -> bool {
        self.panels().any(|candidate| candidate == panel)
    }
}

impl PaneTree {
    /// Returns whether the panel actually landed. A target this tree cannot
    /// resolve — a stale node id, or one whose kind does not match the
    /// target — is a no-op rather than an error, and reports `false`.
    fn apply_insert(&mut self, panel: PanelId, target: InsertTarget) -> bool {
        match target {
            InsertTarget::Tabs { node, ix, activate } => {
                let Some(path) = self.path_of_node(node) else {
                    return false;
                };
                let NodeKind::Tabs { panels, active_ix } = self.node_at_mut(&path).kind_mut()
                else {
                    return false;
                };
                let ix = ix.unwrap_or(panels.len()).min(panels.len());
                panels.insert(ix, panel);
                if activate {
                    *active_ix = ix;
                } else if ix <= *active_ix && panels.len() > 1 {
                    // Keep the displayed panel displayed.
                    *active_ix += 1;
                }
                true
            }
            InsertTarget::Split {
                node,
                placement,
                size,
            } => self.insert_beside(node, panel, placement, size),
            InsertTarget::Tile { node, bounds } => {
                let Some(path) = self.path_of_node(node) else {
                    return false;
                };
                let top = self.max_z_index();
                let NodeKind::Tiles { panels } = self.node_at_mut(&path).kind_mut() else {
                    return false;
                };
                panels.push(TilePanel::new(panel, bounds).with_z_index(top + 1));
                true
            }
        }
    }

    /// Place `panel` in a new tab group beside `node`.
    ///
    /// When the parent split already runs along the placement's axis the new
    /// group becomes a sibling. Otherwise `node` is wrapped in a fresh split of
    /// the placement's axis. Rule 3 of `normalize` then flattens any redundant
    /// nesting this creates, which is why no "reuse the parent split" special
    /// case is needed here.
    fn insert_beside(
        &mut self,
        node: NodeId,
        panel: PanelId,
        placement: Placement,
        size: Option<Pixels>,
    ) -> bool {
        let Some(path) = self.path_of_node(node) else {
            return false;
        };
        let group_id = self.allocate_node_id();
        let group = PaneNode::new(
            group_id,
            NodeKind::Tabs {
                panels: vec![panel],
                active_ix: 0,
            },
        );
        let before = matches!(placement, Placement::Left | Placement::Top);

        if let Some((parent_path, ix)) = split_parent_of(&path) {
            let parent_axis = match self.node_at(&parent_path).kind_ref() {
                NodeKind::Split { axis, .. } => Some(*axis),
                _ => None,
            };

            if parent_axis == Some(placement.axis()) {
                let NodeKind::Split {
                    children, sizes, ..
                } = self.node_at_mut(&parent_path).kind_mut()
                else {
                    return false;
                };
                // The new group splits the slot it landed beside, rather
                // than the whole row being re-divided: drop a panel next to
                // one neighbour and it is that neighbour's space you take.
                // A caller that named a size gets exactly it, and the
                // neighbour is left alone.
                //
                // An unconstrained neighbour halves to another `None`, which
                // is right for the same reason — the two of them go on
                // sharing whatever the fixed slots leave over, now between
                // themselves.
                let share = match size {
                    Some(size) => Some(size),
                    None => {
                        let half = sizes[ix].map(|slot| slot / 2.);
                        sizes[ix] = half;
                        half
                    }
                };
                let at = if before { ix } else { ix + 1 };
                children.insert(at, group);
                sizes.insert(at, share);
                return true;
            }
        }

        // Wrap the target in a new split of the placement's axis. The target
        // is swapped out rather than cloned: it can be a whole subtree, and
        // the placeholder left behind is overwritten two statements later.
        let wrapper_id = self.allocate_node_id();
        let target = std::mem::replace(
            self.node_at_mut(&path),
            PaneNode::new(
                wrapper_id,
                NodeKind::Tabs {
                    panels: Vec::new(),
                    active_ix: 0,
                },
            ),
        );
        let (children, sizes) = if before {
            (vec![group, target], vec![size, None])
        } else {
            (vec![target, group], vec![None, size])
        };
        let wrapper = PaneNode::new(
            wrapper_id,
            NodeKind::Split {
                axis: placement.axis(),
                children,
                sizes,
            },
        );
        *self.node_at_mut(&path) = wrapper;
        true
    }

    /// Remove `panel` wherever it lives. Returns whether it was found.
    fn detach_panel(&mut self, panel: PanelId) -> bool {
        let Some(node) = self.find_panel_node(panel) else {
            return false;
        };
        let Some(path) = self.path_of_node(node) else {
            return false;
        };

        match self.node_at_mut(&path).kind_mut() {
            NodeKind::Tabs { panels, active_ix } => {
                let Some(ix) = panels.iter().position(|p| *p == panel) else {
                    return false;
                };
                panels.remove(ix);
                if ix < *active_ix {
                    *active_ix -= 1;
                }
                true
            }
            NodeKind::Tiles { panels } => {
                let Some(ix) = panels.iter().position(|p| p.panel() == panel) else {
                    return false;
                };
                panels.remove(ix);
                true
            }
            NodeKind::Split { .. } => false,
        }
    }

    fn with_tile(&mut self, panel: PanelId, f: impl FnOnce(&mut TilePanel)) {
        let Some(node) = self.find_panel_node(panel) else {
            return;
        };
        let Some(path) = self.path_of_node(node) else {
            return;
        };
        if let NodeKind::Tiles { panels } = self.node_at_mut(&path).kind_mut() {
            if let Some(tile) = panels.iter_mut().find(|tile| tile.panel() == panel) {
                f(tile);
            }
        }
    }

    /// Highest z-index across every tiles canvas in the tree.
    fn max_z_index(&self) -> usize {
        let mut top = 0;
        self.root().walk(&mut |node| {
            if let NodeKind::Tiles { panels } = node.kind_ref() {
                top = top.max(panels.iter().map(TilePanel::z_index).max().unwrap_or(0));
            }
        });
        top
    }
}

/// Split the path into its parent path and the child index, or `None` at the root.
fn split_parent_of(path: &super::tree::NodePath) -> Option<(super::tree::NodePath, usize)> {
    let (&ix, parent) = path.split_last()?;
    Some((parent.iter().copied().collect(), ix))
}

#[cfg(test)]
mod tests {
    use super::super::*;
    use crate::Placement;
    use gpui::{Axis, Bounds, Pixels, point, px, size};

    fn panel(n: u64) -> PanelId {
        PanelId::from_u64(n)
    }

    fn tree_with_one_group() -> (PaneTree, NodeId) {
        let mut tree = PaneTree::new(RootKind::Split);
        let tabs = tree.push_tabs_for_test(tree.root().id(), vec![panel(1)]);
        tree.normalize();
        (tree, tabs)
    }

    #[test]
    fn inserting_into_a_tab_group_appends_and_can_activate() {
        let (mut tree, tabs) = tree_with_one_group();
        let result = tree.insert_panel(
            panel(2),
            InsertTarget::Tabs {
                node: tabs,
                ix: None,
                activate: true,
            },
        );

        assert!(result.changed());
        let PaneRef::Tabs { panels, active_ix } = tree.find_node(tabs).unwrap().kind() else {
            panic!()
        };
        assert_eq!(panels, [panel(1), panel(2)]);
        assert_eq!(active_ix, 1, "the inserted panel becomes the displayed one");
    }

    #[test]
    fn a_background_insert_leaves_the_active_panel_alone() {
        let (mut tree, tabs) = tree_with_one_group();
        let result = tree.insert_panel(
            panel(2),
            InsertTarget::Tabs {
                node: tabs,
                ix: None,
                activate: false,
            },
        );

        assert!(result.changed());
        let PaneRef::Tabs { panels, active_ix } = tree.find_node(tabs).unwrap().kind() else {
            panic!()
        };
        assert_eq!(panels, [panel(1), panel(2)]);
        assert_eq!(active_ix, 0, "the displayed panel is left alone");
    }

    #[test]
    fn removing_the_last_panel_collapses_the_group_and_reports_it() {
        let (mut tree, tabs) = tree_with_one_group();
        let result = tree.remove_panel(panel(1));

        assert!(result.changed());
        assert!(!tree.contains_panel(panel(1)), "the panel left the tree");
        assert!(tree.find_node(tabs).is_none(), "its empty group collapsed");
        assert!(
            matches!(tree.root().kind(), PaneRef::Split { children, .. } if children.is_empty())
        );
    }

    #[test]
    fn splitting_creates_a_sibling_group_on_the_requested_side() {
        let (mut tree, tabs) = tree_with_one_group();
        let result = tree.split(tabs, panel(2), Placement::Right, Some(px(240.)));

        assert!(result.changed());
        let PaneRef::Split {
            axis,
            children,
            sizes,
        } = tree.root().kind()
        else {
            panic!()
        };
        assert_eq!(axis, Axis::Horizontal);
        assert_eq!(children.len(), 2);
        assert_eq!(sizes[1], Some(px(240.)));

        let PaneRef::Tabs { panels, .. } = children[0].kind() else {
            panic!()
        };
        assert_eq!(panels, [panel(1)]);
        let PaneRef::Tabs { panels, .. } = children[1].kind() else {
            panic!()
        };
        assert_eq!(panels, [panel(2)]);
    }

    #[test]
    fn splitting_left_puts_the_new_group_first() {
        let (mut tree, tabs) = tree_with_one_group();
        tree.split(tabs, panel(2), Placement::Left, None);

        let PaneRef::Split { children, .. } = tree.root().kind() else {
            panic!()
        };
        let PaneRef::Tabs { panels, .. } = children[0].kind() else {
            panic!()
        };
        assert_eq!(panels, [panel(2)]);
    }

    #[test]
    fn splitting_across_the_parent_axis_nests_a_new_split() {
        let (mut tree, tabs) = tree_with_one_group();
        tree.push_tabs_for_test(tree.root().id(), vec![panel(9)]);
        tree.normalize();

        tree.split(tabs, panel(2), Placement::Bottom, None);

        let PaneRef::Split { axis, children, .. } = tree.root().kind() else {
            panic!()
        };
        assert_eq!(axis, Axis::Horizontal);
        let PaneRef::Split {
            axis: inner,
            children: inner_children,
            ..
        } = children[0].kind()
        else {
            panic!("the split target is wrapped in a vertical split")
        };
        assert_eq!(inner, Axis::Vertical);
        assert_eq!(inner_children.len(), 2);

        // `Bottom` puts the new group after the original target: the
        // wrapper's first child is still the target, the second is new.
        let PaneRef::Tabs { panels, .. } = inner_children[0].kind() else {
            panic!()
        };
        assert_eq!(panels, [panel(1)], "the original target stays first");
        let PaneRef::Tabs { panels, .. } = inner_children[1].kind() else {
            panic!()
        };
        assert_eq!(panels, [panel(2)], "the new group lands second, below");
    }

    #[test]
    fn splitting_top_across_the_parent_axis_puts_the_new_group_first() {
        let (mut tree, tabs) = tree_with_one_group();
        tree.push_tabs_for_test(tree.root().id(), vec![panel(9)]);
        tree.normalize();

        tree.split(tabs, panel(2), Placement::Top, None);

        let PaneRef::Split { children, .. } = tree.root().kind() else {
            panic!()
        };
        let PaneRef::Split {
            axis: inner,
            children: inner_children,
            ..
        } = children[0].kind()
        else {
            panic!("the split target is wrapped in a vertical split")
        };
        assert_eq!(inner, Axis::Vertical);
        assert_eq!(inner_children.len(), 2);

        // `Top` is the mirror of `Bottom`: the new group lands first, above
        // the original target.
        let PaneRef::Tabs { panels, .. } = inner_children[0].kind() else {
            panic!()
        };
        assert_eq!(panels, [panel(2)], "the new group lands first, above");
        let PaneRef::Tabs { panels, .. } = inner_children[1].kind() else {
            panic!()
        };
        assert_eq!(panels, [panel(1)], "the original target moves second");
    }

    #[test]
    fn the_split_target_keeps_its_node_id_so_its_entity_survives() {
        let (mut tree, tabs) = tree_with_one_group();
        tree.split(tabs, panel(2), Placement::Right, None);

        assert!(
            tree.find_node(tabs).is_some(),
            "the target group is reused, not rebuilt"
        );
    }

    #[test]
    fn moving_a_panel_between_groups_preserves_its_identity() {
        let (mut tree, tabs) = tree_with_one_group();
        assert!(tree.split(tabs, panel(2), Placement::Right, None).changed());
        let other = tree
            .find_panel_node(panel(2))
            .expect("the split put panel 2 in a group of its own");

        let result = tree.move_panel(
            panel(1),
            InsertTarget::Tabs {
                node: other,
                ix: None,
                activate: true,
            },
        );

        assert!(result.changed());
        assert_eq!(
            tree.panels().collect::<Vec<_>>(),
            vec![panel(2), panel(1)],
            "a move is not a removal; both panels are still in the tree"
        );
        assert!(
            tree.find_node(tabs).is_none(),
            "the emptied group collapses"
        );
    }

    #[test]
    fn a_no_op_edit_reports_no_change() {
        let (mut tree, tabs) = tree_with_one_group();
        let result = tree.set_active(tabs, 0);
        assert!(!result.changed());
    }

    #[test]
    fn set_sizes_replaces_a_matching_length_vector() {
        let (mut tree, tabs) = tree_with_one_group();
        tree.split(tabs, panel(2), Placement::Right, None);
        let root = tree.root().id();

        let result = tree.set_sizes(root, vec![Some(px(100.)), Some(px(200.))]);

        assert!(result.changed());
        let PaneRef::Split { sizes, .. } = tree.root().kind() else {
            panic!()
        };
        assert_eq!(sizes, &[Some(px(100.)), Some(px(200.))]);
    }

    #[test]
    fn set_sizes_ignores_a_mismatched_length_vector() {
        let (mut tree, tabs) = tree_with_one_group();
        tree.split(tabs, panel(2), Placement::Right, None);
        let root = tree.root().id();
        let PaneRef::Split {
            sizes: before_sizes,
            ..
        } = tree.root().kind()
        else {
            panic!()
        };
        let before_sizes = before_sizes.to_vec();

        // The split has 2 children; hand it 3 sizes.
        let result = tree.set_sizes(root, vec![Some(px(10.)), Some(px(20.)), Some(px(30.))]);

        assert!(
            !result.changed(),
            "a mismatched vector must not report a change"
        );
        let PaneRef::Split { sizes, .. } = tree.root().kind() else {
            panic!()
        };
        assert_eq!(
            sizes,
            before_sizes.as_slice(),
            "the mismatched vector is rejected"
        );
    }

    fn tile_bounds(x: f32) -> Bounds<Pixels> {
        Bounds {
            origin: point(px(x), px(0.)),
            size: size(px(10.), px(10.)),
        }
    }

    #[test]
    fn inserting_a_tile_places_it_at_the_given_bounds_on_top() {
        let mut tree = PaneTree::new(RootKind::Any);
        let canvas = tree.set_root_tiles_for_test(vec![
            TilePanel::new(panel(1), tile_bounds(0.)).with_z_index(4),
        ]);

        let result = tree.insert_panel(
            panel(2),
            InsertTarget::Tile {
                node: canvas,
                bounds: tile_bounds(70.),
            },
        );

        assert!(result.changed());
        let PaneRef::Tiles { panels } = tree.root().kind() else {
            panic!("the canvas stays a canvas rather than being split")
        };
        assert_eq!(panels.len(), 2);
        let added = panels.iter().find(|tile| tile.panel() == panel(2)).unwrap();
        assert_eq!(added.bounds(), tile_bounds(70.), "the bounds are honoured");
        assert!(
            added.z_index() > panels[0].z_index(),
            "a new tile lands on top of the ones already there"
        );
    }

    #[test]
    fn set_tile_bounds_moves_one_tile_and_leaves_its_peers_alone() {
        let mut tree = PaneTree::new(RootKind::Any);
        tree.set_root_tiles_for_test(vec![
            TilePanel::new(panel(1), tile_bounds(0.)).with_z_index(1),
            TilePanel::new(panel(2), tile_bounds(40.)).with_z_index(2),
        ]);

        let result = tree.set_tile_bounds(panel(1), tile_bounds(90.));

        assert!(result.changed());
        let PaneRef::Tiles { panels } = tree.root().kind() else {
            panic!()
        };
        let moved = panels.iter().find(|tile| tile.panel() == panel(1)).unwrap();
        let other = panels.iter().find(|tile| tile.panel() == panel(2)).unwrap();
        assert_eq!(moved.bounds(), tile_bounds(90.));
        assert_eq!(
            moved.z_index(),
            1,
            "moving a tile does not raise it; that is `bring_to_front`'s job"
        );
        assert_eq!(other.bounds(), tile_bounds(40.), "its peer does not move");
    }

    #[test]
    fn bring_to_front_raises_the_tile_above_its_peers() {
        let mut tree = PaneTree::new(RootKind::Any);
        let bounds = Bounds {
            origin: point(px(0.), px(0.)),
            size: size(px(10.), px(10.)),
        };
        tree.set_root_tiles_for_test(vec![
            TilePanel::new(panel(1), bounds).with_z_index(0),
            TilePanel::new(panel(2), bounds).with_z_index(1),
        ]);

        tree.bring_to_front(panel(1));

        let PaneRef::Tiles { panels } = tree.root().kind() else {
            panic!()
        };
        let raised = panels.iter().find(|p| p.panel() == panel(1)).unwrap();
        let other = panels.iter().find(|p| p.panel() == panel(2)).unwrap();
        assert!(raised.z_index() > other.z_index());
    }

    #[test]
    fn every_edit_leaves_the_tree_normalized() {
        let (mut tree, tabs) = tree_with_one_group();
        tree.split(tabs, panel(2), Placement::Bottom, None);
        tree.insert_panel(
            panel(3),
            InsertTarget::Tabs {
                node: tabs,
                ix: None,
                activate: false,
            },
        );
        tree.remove_panel(panel(2));
        tree.remove_panel(panel(3));

        assert!(tree.is_normalized());
    }
}