Skip to main content

gpui_base/dock/
state_convert.rs

1use gpui::{Axis, Pixels};
2
3use super::layout::{NodeKind, PaneNode, PaneRef, PaneTree, PanelId, RootKind, TilePanel};
4use super::state::{PanelInfo, PanelState, TileMeta};
5
6/// The names written to persisted layouts. These are contract, not type names:
7/// they must keep their values even if the Rust types are renamed.
8pub(crate) const STACK_PANEL_NAME: &str = "StackPanel";
9pub(crate) const TAB_PANEL_NAME: &str = "TabPanel";
10pub(crate) const TILES_PANEL_NAME: &str = "Tiles";
11
12/// How the layout tree reads properties of panels it only knows by id.
13///
14/// Keeping this behind a trait is what lets the whole layout algebra be tested
15/// without an `App`.
16pub trait PanelSource {
17    fn panel_name(&self, id: PanelId) -> &'static str;
18    fn is_visible(&self, id: PanelId) -> bool;
19    fn dump(&self, id: PanelId) -> PanelState;
20}
21
22impl PaneTree {
23    pub fn to_state(&self, source: &dyn PanelSource) -> PanelState {
24        node_to_state(self.root(), source)
25    }
26}
27
28fn node_to_state(node: &PaneNode, source: &dyn PanelSource) -> PanelState {
29    match node.kind() {
30        PaneRef::Split {
31            axis,
32            children,
33            sizes,
34        } => PanelState {
35            panel_name: STACK_PANEL_NAME.to_string(),
36            children: children
37                .iter()
38                .map(|child| node_to_state(child, source))
39                .collect(),
40            // `None` is a representation this rewrite introduces, not
41            // something the old writer ever produced: the schema's `sizes`
42            // field is `Vec<Pixels>`, with no slot for "unconstrained". `0.0`
43            // is the sentinel this writer chooses for that case, and the
44            // corresponding reader maps a `0.0` it loads back to `None`.
45            //
46            // That makes a `None` slot safe to persist only transiently: a
47            // caller building a tree meant to be written out must resolve
48            // every slot to concrete pixels first. An older build reading a
49            // persisted `0.0` back has no notion of the sentinel and
50            // constructs a real, zero-pixel-wide panel from it.
51            info: PanelInfo::stack(
52                sizes.iter().map(|size| size.unwrap_or_default()).collect(),
53                axis,
54            ),
55        },
56        PaneRef::Tabs { panels, active_ix } => PanelState {
57            panel_name: TAB_PANEL_NAME.to_string(),
58            children: panels.iter().map(|panel| source.dump(*panel)).collect(),
59            // Unconditional, unlike the old writer which assigned this inside
60            // its loop and left an empty group looking like a bare panel.
61            info: PanelInfo::tabs(active_ix),
62        },
63        PaneRef::Tiles { panels } => PanelState {
64            panel_name: TILES_PANEL_NAME.to_string(),
65            children: panels
66                .iter()
67                .map(|tile| source.dump(tile.panel()))
68                .collect(),
69            info: PanelInfo::tiles(
70                panels
71                    .iter()
72                    .map(|tile| TileMeta {
73                        bounds: tile.bounds(),
74                        z_index: tile.z_index(),
75                    })
76                    .collect(),
77            ),
78        },
79    }
80}
81
82/// Turns a persisted leaf into a live panel id.
83///
84/// The production implementation (at the `gpui-component` layer, above this
85/// crate) consults `PanelRegistry` and falls back to an invalid-panel
86/// placeholder that retains the original `PanelState`, so a panel type this
87/// build does not know about survives a load/save round trip instead of
88/// being erased.
89pub trait PanelBuilder {
90    fn build(&mut self, state: &PanelState, info: &PanelInfo) -> PanelId;
91}
92
93impl PaneTree {
94    /// Read a persisted layout.
95    ///
96    /// Compatibility rules, all previously implicit in `PanelState::to_item`:
97    ///
98    /// - a `Tabs` whose children are themselves `Tabs` is flattened;
99    /// - a bare `Panel` leaf appearing where a container belongs is wrapped in
100    ///   a `Tabs`;
101    /// - a node named `TabPanel` carrying `PanelInfo::Panel` is read as an
102    ///   empty tab group, recovering data written by the old dump defect (an
103    ///   empty `TabPanel` never entered the loop that set its `info` to
104    ///   `Tabs`, so it kept `PanelState`'s default `Panel(Value::Null)`). The
105    ///   old reader had no such rule: it looked "TabPanel" up in the panel
106    ///   registry, found nothing, and rendered an `InvalidPanel` placeholder
107    ///   where an empty tab group belonged. This rule is a genuine fix, not a
108    ///   preserved behavior;
109    /// - a `Tiles` child without a matching meta keeps the default placement.
110    ///   The old writer's counterpart (`DockItem::tiles`) hard-asserted
111    ///   `items.len() == metas.len()` and panicked the whole load on a short
112    ///   `metas` list, so this rule is a new safety net, not a preserved
113    ///   graceful-degradation path.
114    pub fn from_state(
115        state: &PanelState,
116        root_kind: RootKind,
117        builder: &mut dyn PanelBuilder,
118    ) -> Self {
119        let mut tree = PaneTree::new(root_kind);
120        let root = build_node(&mut tree, state, builder);
121
122        let root = match (root_kind, &root) {
123            (RootKind::Split, node) if !matches!(node.kind_ref(), NodeKind::Split { .. }) => {
124                let id = tree.allocate_node_id();
125                PaneNode::new(
126                    id,
127                    NodeKind::Split {
128                        axis: Axis::Horizontal,
129                        children: vec![node.clone()],
130                        sizes: vec![None],
131                    },
132                )
133            }
134            _ => root,
135        };
136
137        tree.replace_root(root);
138        tree.normalize();
139        tree
140    }
141}
142
143fn build_node(tree: &mut PaneTree, state: &PanelState, builder: &mut dyn PanelBuilder) -> PaneNode {
144    let id = tree.allocate_node_id();
145
146    match &state.info {
147        PanelInfo::Stack { sizes, axis } => {
148            let axis = if *axis == 0 {
149                Axis::Horizontal
150            } else {
151                Axis::Vertical
152            };
153            let children: Vec<PaneNode> = state
154                .children
155                .iter()
156                .map(|child| build_node(tree, child, builder))
157                .collect();
158            let sizes = (0..children.len())
159                .map(|ix| sizes.get(ix).copied().filter(|size| *size > Pixels::ZERO))
160                .collect();
161            PaneNode::new(
162                id,
163                NodeKind::Split {
164                    axis,
165                    children,
166                    sizes,
167                },
168            )
169        }
170        PanelInfo::Tabs { active_index } => {
171            let panels = collect_tab_panels(&state.children, builder);
172            PaneNode::new(
173                id,
174                NodeKind::Tabs {
175                    panels,
176                    active_ix: *active_index,
177                },
178            )
179        }
180        PanelInfo::Tiles { metas } => {
181            let mut panels = Vec::new();
182            for (ix, child) in state.children.iter().enumerate() {
183                // Keyed by the *child* index, not by the output index: a
184                // child that expands to several tiles must not shift the
185                // metas of the children after it.
186                let meta = metas.get(ix).copied().unwrap_or_default();
187                for panel in tile_panels(child, builder) {
188                    panels.push(TilePanel::new(panel, meta.bounds).with_z_index(meta.z_index));
189                }
190            }
191            PaneNode::new(id, NodeKind::Tiles { panels })
192        }
193        PanelInfo::Panel(_) => {
194            // A container name carrying a leaf info means the writer that
195            // produced this file had the empty-group defect.
196            let panels = if state.panel_name == TAB_PANEL_NAME {
197                Vec::new()
198            } else {
199                vec![builder.build(state, &state.info)]
200            };
201            PaneNode::new(
202                id,
203                NodeKind::Tabs {
204                    panels,
205                    active_ix: 0,
206                },
207            )
208        }
209    }
210}
211
212/// The panels one persisted `Tiles` child stands for.
213///
214/// Every tile the old dock ever wrote is `TabPanel`-shaped: `DockItem::tiles`
215/// wraps each child in a `TabPanel`, `DockItem::add_panel`'s tiles arm wraps
216/// every UI-added panel in a fresh one, and `PanelState::to_item` converts a
217/// plain-panel child into a `TabPanel` on the next save. In the tree model a
218/// tile *is* a panel, so the group has to be unwrapped — building the
219/// `"TabPanel"` leaf directly would miss the registry, fall to a placeholder,
220/// and never build the user's real panels at all, restoring a saved tiles
221/// canvas as blank tiles.
222///
223/// A group holding several panels expands to one tile per panel, sharing the
224/// group's meta. That is not merely defensive: the UI cannot produce it
225/// (tiles groups are locked, so they can never gain a tab), but
226/// `DockItem::tiles(vec![DockItem::tabs(vec![a, b])], ..)` can, and a tiles
227/// canvas has no way to show a second tab.
228fn tile_panels(child: &PanelState, builder: &mut dyn PanelBuilder) -> Vec<PanelId> {
229    match &child.info {
230        PanelInfo::Tabs { .. } => {
231            let panels = collect_tab_panels(&child.children, builder);
232            if panels.len() > 1 {
233                tracing::warn!(
234                    panels = panels.len(),
235                    "a tiles child held a tab group with more than one panel; \
236                     expanding it to one tile per panel, all sharing the group's placement"
237                );
238            }
239            panels
240        }
241        // The legacy empty-group form: a `TabPanel` name carrying leaf info.
242        // It stands for no panel, so it contributes no tile.
243        PanelInfo::Panel(_) if child.panel_name == TAB_PANEL_NAME => Vec::new(),
244        _ => vec![builder.build(child, &child.info)],
245    }
246}
247
248/// Flatten one level of tab nesting, which the old writer could produce.
249fn collect_tab_panels(children: &[PanelState], builder: &mut dyn PanelBuilder) -> Vec<PanelId> {
250    children
251        .iter()
252        .flat_map(|child| match &child.info {
253            PanelInfo::Tabs { .. } => collect_tab_panels(&child.children, builder),
254            PanelInfo::Panel(_) if child.panel_name == TAB_PANEL_NAME => Vec::new(),
255            _ => vec![builder.build(child, &child.info)],
256        })
257        .collect()
258}
259
260#[cfg(test)]
261mod tests {
262    use gpui::{Bounds, point, px, size};
263
264    use super::super::layout::{RootKind, TilePanel};
265    use super::super::state::DockAreaState;
266    use super::*;
267
268    /// A `PanelSource` backed by a fixed map, so conversion is testable
269    /// without an `App`.
270    struct FakePanels(Vec<(PanelId, &'static str)>);
271
272    impl PanelSource for FakePanels {
273        fn panel_name(&self, id: PanelId) -> &'static str {
274            self.0
275                .iter()
276                .find(|(p, _)| *p == id)
277                .map(|(_, n)| *n)
278                .unwrap_or("Unknown")
279        }
280        fn is_visible(&self, _: PanelId) -> bool {
281            true
282        }
283        fn dump(&self, id: PanelId) -> PanelState {
284            PanelState {
285                panel_name: self.panel_name(id).to_string(),
286                children: Vec::new(),
287                info: PanelInfo::panel(serde_json::Value::Null),
288            }
289        }
290    }
291
292    #[test]
293    fn a_split_serializes_as_a_stack_panel() {
294        let mut tree = PaneTree::new(RootKind::Split);
295        tree.push_tabs_for_test(tree.root().id(), vec![PanelId::from_u64(1)]);
296        tree.push_tabs_for_test(tree.root().id(), vec![PanelId::from_u64(2)]);
297        tree.normalize();
298
299        let source = FakePanels(vec![
300            (PanelId::from_u64(1), "Alpha"),
301            (PanelId::from_u64(2), "Beta"),
302        ]);
303        let state = tree.to_state(&source);
304
305        assert_eq!(state.panel_name, "StackPanel");
306        let PanelInfo::Stack { sizes, .. } = &state.info else {
307            panic!("expected Stack info");
308        };
309        // Both slots were pushed with no explicit size (`push_tabs_for_test`
310        // always pushes `None`), so both serialize as the zero sentinel.
311        assert_eq!(sizes, &vec![px(0.), px(0.)]);
312        assert_eq!(state.children[0].panel_name, "TabPanel");
313        assert_eq!(state.children[0].children[0].panel_name, "Alpha");
314    }
315
316    #[test]
317    fn an_unresolved_slot_size_serializes_as_the_zero_sentinel() {
318        let mut tree = PaneTree::new(RootKind::Split);
319        let root = tree.root().id();
320        tree.push_sized_tabs_for_test(root, vec![PanelId::from_u64(1)], Some(px(120.)));
321        tree.push_sized_tabs_for_test(root, vec![PanelId::from_u64(2)], None);
322        tree.normalize();
323
324        let source = FakePanels(vec![
325            (PanelId::from_u64(1), "Alpha"),
326            (PanelId::from_u64(2), "Beta"),
327        ]);
328        let state = tree.to_state(&source);
329
330        let PanelInfo::Stack { sizes, .. } = state.info else {
331            panic!("expected Stack info");
332        };
333        // The `Some` slot keeps its concrete value; only the genuinely
334        // unresolved (`None`) slot is written as the `0.0` sentinel.
335        assert_eq!(sizes, vec![px(120.), px(0.)]);
336    }
337
338    #[test]
339    fn an_empty_tab_group_serializes_as_tabs_not_as_a_panel() {
340        let mut tree = PaneTree::new(RootKind::Any);
341        tree.set_root_tabs_for_test(vec![], 0);
342
343        let state = tree.to_state(&FakePanels(vec![]));
344
345        assert_eq!(state.panel_name, "TabPanel");
346        assert!(
347            matches!(state.info, PanelInfo::Tabs { active_index: 0 }),
348            "the old writer emitted PanelInfo::Panel here, which failed to restore"
349        );
350    }
351
352    #[test]
353    fn an_empty_center_still_serializes_as_a_stack_panel() {
354        let tree = PaneTree::new(RootKind::Split);
355        let state = tree.to_state(&FakePanels(vec![]));
356        assert_eq!(state.panel_name, "StackPanel");
357        assert!(matches!(state.info, PanelInfo::Stack { .. }));
358    }
359
360    #[test]
361    fn tiles_serialize_with_their_metas_in_order() {
362        let mut tree = PaneTree::new(RootKind::Any);
363        let bounds = Bounds {
364            origin: point(px(5.), px(6.)),
365            size: size(px(7.), px(8.)),
366        };
367        tree.set_root_tiles_for_test(vec![
368            TilePanel::new(PanelId::from_u64(1), bounds).with_z_index(2),
369        ]);
370
371        let state = tree.to_state(&FakePanels(vec![(PanelId::from_u64(1), "Alpha")]));
372
373        assert_eq!(state.panel_name, "Tiles");
374        let PanelInfo::Tiles { metas } = state.info else {
375            panic!()
376        };
377        assert_eq!(metas[0].bounds, bounds);
378        assert_eq!(metas[0].z_index, 2);
379    }
380
381    /// Assigns each leaf `PanelState` an id in encounter order, so the reader
382    /// can be tested without a registry or an `App`.
383    #[derive(Default)]
384    struct RecordingBuilder {
385        built: Vec<String>,
386    }
387
388    impl PanelBuilder for RecordingBuilder {
389        fn build(&mut self, state: &PanelState, _: &PanelInfo) -> PanelId {
390            self.built.push(state.panel_name.clone());
391            PanelId::from_u64(self.built.len() as u64)
392        }
393    }
394
395    fn tabs_state(children: Vec<PanelState>, active_index: usize) -> PanelState {
396        PanelState {
397            panel_name: TAB_PANEL_NAME.to_string(),
398            children,
399            info: PanelInfo::tabs(active_index),
400        }
401    }
402
403    fn panel_state(name: &str) -> PanelState {
404        PanelState {
405            panel_name: name.to_string(),
406            children: Vec::new(),
407            info: PanelInfo::panel(serde_json::Value::Null),
408        }
409    }
410
411    #[test]
412    fn nested_tab_groups_are_flattened() {
413        let state = tabs_state(
414            vec![
415                tabs_state(vec![panel_state("Alpha")], 0),
416                tabs_state(vec![panel_state("Beta")], 0),
417            ],
418            1,
419        );
420
421        let mut builder = RecordingBuilder::default();
422        let tree = PaneTree::from_state(&state, RootKind::Any, &mut builder);
423
424        assert_eq!(builder.built, vec!["Alpha", "Beta"]);
425        let PaneRef::Tabs { panels, active_ix } = tree.root().kind() else {
426            panic!()
427        };
428        assert_eq!(panels.len(), 2);
429        assert_eq!(active_ix, 1);
430    }
431
432    #[test]
433    fn a_bare_panel_leaf_is_wrapped_in_a_tab_group() {
434        let mut builder = RecordingBuilder::default();
435        let tree = PaneTree::from_state(&panel_state("Alpha"), RootKind::Any, &mut builder);
436
437        assert!(matches!(tree.root().kind(), PaneRef::Tabs { panels, .. } if panels.len() == 1));
438    }
439
440    #[test]
441    fn a_tab_panel_carrying_panel_info_is_read_as_an_empty_group() {
442        // What the old `TabPanel::dump` wrote for an empty tab group.
443        let state = PanelState {
444            panel_name: TAB_PANEL_NAME.to_string(),
445            children: Vec::new(),
446            info: PanelInfo::panel(serde_json::Value::Null),
447        };
448
449        let mut builder = RecordingBuilder::default();
450        let tree = PaneTree::from_state(&state, RootKind::Any, &mut builder);
451
452        assert!(
453            builder.built.is_empty(),
454            "no panel is built for the phantom leaf"
455        );
456        assert!(matches!(tree.root().kind(), PaneRef::Tabs { panels, .. } if panels.is_empty()));
457    }
458
459    #[test]
460    fn a_split_root_is_forced_even_when_the_state_is_a_tab_group() {
461        let state = tabs_state(vec![panel_state("Alpha")], 0);
462        let mut builder = RecordingBuilder::default();
463        let tree = PaneTree::from_state(&state, RootKind::Split, &mut builder);
464
465        assert!(matches!(tree.root().kind(), PaneRef::Split { .. }));
466    }
467
468    #[test]
469    fn tile_metas_are_paired_with_children_by_index() {
470        let bounds = Bounds {
471            origin: point(px(1.), px(2.)),
472            size: size(px(3.), px(4.)),
473        };
474        let state = PanelState {
475            panel_name: TILES_PANEL_NAME.to_string(),
476            children: vec![panel_state("Alpha")],
477            info: PanelInfo::tiles(vec![TileMeta { bounds, z_index: 5 }]),
478        };
479
480        let mut builder = RecordingBuilder::default();
481        let tree = PaneTree::from_state(&state, RootKind::Any, &mut builder);
482
483        let PaneRef::Tiles { panels } = tree.root().kind() else {
484            panic!()
485        };
486        assert_eq!(panels[0].bounds(), bounds);
487        assert_eq!(panels[0].z_index(), 5);
488    }
489
490    #[test]
491    fn a_tile_child_missing_its_meta_falls_back_to_the_default_placement() {
492        let state = PanelState {
493            panel_name: TILES_PANEL_NAME.to_string(),
494            children: vec![panel_state("Alpha"), panel_state("Beta")],
495            info: PanelInfo::tiles(vec![TileMeta::default()]),
496        };
497
498        let mut builder = RecordingBuilder::default();
499        let tree = PaneTree::from_state(&state, RootKind::Any, &mut builder);
500
501        let PaneRef::Tiles { panels } = tree.root().kind() else {
502            panic!()
503        };
504        assert_eq!(panels.len(), 2, "a short metas list must not drop panels");
505    }
506
507    /// Round-trips leaves by remembering the exact `PanelState` each id came
508    /// from, which is what the production invalid-panel path must also do.
509    ///
510    /// `PanelSource::panel_name` returns `&'static str`, which a JSON-sourced
511    /// `String` can only satisfy by leaking. Rather than leak on every call
512    /// to `panel_name` (as many times as the layout is dumped), each leak
513    /// happens once, in `build`, when the id is minted; `panel_name` then
514    /// just indexes into the already-leaked slice. Still a leak, but a
515    /// bounded one, and test-only.
516    #[derive(Default)]
517    struct PreservingPanels {
518        states: Vec<PanelState>,
519        names: Vec<&'static str>,
520    }
521
522    impl PanelBuilder for PreservingPanels {
523        fn build(&mut self, state: &PanelState, _: &PanelInfo) -> PanelId {
524            self.states.push(state.clone());
525            self.names
526                .push(Box::leak(state.panel_name.clone().into_boxed_str()));
527            PanelId::from_u64(self.states.len() as u64)
528        }
529    }
530
531    impl PanelSource for PreservingPanels {
532        fn panel_name(&self, id: PanelId) -> &'static str {
533            self.names[id.as_u64() as usize - 1]
534        }
535        fn is_visible(&self, _: PanelId) -> bool {
536            true
537        }
538        fn dump(&self, id: PanelId) -> PanelState {
539            self.states[id.as_u64() as usize - 1].clone()
540        }
541    }
542
543    fn canonicalize(json: &str) -> PanelState {
544        let state: DockAreaState = serde_json::from_str(json).unwrap();
545        let mut panels = PreservingPanels::default();
546        let tree = PaneTree::from_state(&state.center, RootKind::Split, &mut panels);
547        tree.to_state(&panels)
548    }
549
550    #[test]
551    fn canonicalization_reaches_a_fixpoint_in_one_pass() {
552        for json in [
553            include_str!("fixtures/layout.json"),
554            include_str!("fixtures/tiles.json"),
555            include_str!("fixtures/nested_splits.json"),
556            include_str!("fixtures/legacy_empty_tab_group.json"),
557            include_str!("fixtures/unregistered_panel.json"),
558            include_str!("fixtures/zero_size_sentinel.json"),
559            include_str!("fixtures/tiles_tab_panel_children.json"),
560        ] {
561            let once = canonicalize(json);
562            let twice = {
563                let wrapped = DockAreaState {
564                    center: once.clone(),
565                    ..Default::default()
566                };
567                canonicalize(&serde_json::to_string(&wrapped).unwrap())
568            };
569            assert_eq!(once, twice, "r(r(x)) != r(x)");
570        }
571    }
572
573    #[test]
574    fn an_unregistered_panel_keeps_its_payload_through_a_round_trip() {
575        let state = canonicalize(include_str!("fixtures/unregistered_panel.json"));
576        let leaf = &state.children[0].children[0];
577
578        assert_eq!(leaf.panel_name, "PanelFromTheFuture");
579        assert_eq!(
580            leaf.info,
581            PanelInfo::panel(serde_json::json!({"keep": "me"}))
582        );
583    }
584
585    #[test]
586    fn the_legacy_empty_tab_group_is_rewritten_into_the_tabs_form() {
587        let state = canonicalize(include_str!("fixtures/legacy_empty_tab_group.json"));
588
589        // The empty group collapses, leaving the mandatory split root.
590        assert_eq!(state.panel_name, "StackPanel");
591        assert!(state.children.is_empty());
592    }
593
594    #[test]
595    fn nested_same_axis_splits_are_flattened_and_single_child_splits_collapse() {
596        let state = canonicalize(include_str!("fixtures/nested_splits.json"));
597
598        assert_eq!(state.panel_name, "StackPanel");
599        assert_eq!(
600            state.children.len(),
601            3,
602            "the horizontal inner split splices in and the vertical single-child split collapses"
603        );
604        assert!(
605            state
606                .children
607                .iter()
608                .all(|child| child.panel_name == "TabPanel")
609        );
610        // Order matters as much as count: a splice that reversed the spliced
611        // children, or that put the collapsed single-child split ahead of
612        // them, would still satisfy the two assertions above.
613        assert_eq!(state.children[0].children[0].panel_name, "Alpha");
614        assert_eq!(state.children[1].children[0].panel_name, "Beta");
615        assert_eq!(state.children[2].children[0].panel_name, "Gamma");
616
617        // The fixture's inner slot (50.0 + 150.0 = 200.0) does not equal its
618        // outer slot (400.0), so the scale factor is a genuine 2x, not 1x:
619        // `distribute_slot`'s `slot / total` and a wrongly inverted
620        // `total / slot` would disagree here. The vertical single-child
621        // split's own inner size (300.0) is discarded; its outer slot
622        // (300.0) is what the surviving child inherits.
623        let PanelInfo::Stack { sizes, .. } = &state.info else {
624            panic!("expected Stack info");
625        };
626        assert_eq!(
627            sizes,
628            &vec![px(100.), px(300.), px(300.)],
629            "the spliced-in sizes are scaled by outer/inner (400/200 = 2x), and the \
630             collapsed split hands its own outer slot (300.0) to its surviving child"
631        );
632    }
633
634    /// The shape every persisted tiles canvas actually has: each tile child
635    /// is a `TabPanel` wrapping the real panel. Reading the `"TabPanel"` leaf
636    /// literally would build a placeholder and drop the user's panel.
637    #[test]
638    fn a_tiles_child_that_is_a_tab_group_is_unwrapped_to_its_panels() {
639        let json = include_str!("fixtures/tiles_tab_panel_children.json");
640        let state: DockAreaState = serde_json::from_str(json).unwrap();
641        let mut panels = PreservingPanels::default();
642        let tree = PaneTree::from_state(&state.center, RootKind::Split, &mut panels);
643
644        assert_eq!(
645            panels.names,
646            vec!["Alpha", "Beta", "Gamma"],
647            "the real panels are built; no `TabPanel` leaf is handed to the builder"
648        );
649
650        let dumped = tree.to_state(&panels);
651        let tiles = &dumped.children[0];
652        assert_eq!(tiles.panel_name, "Tiles");
653        assert_eq!(
654            tiles
655                .children
656                .iter()
657                .map(|child| child.panel_name.as_str())
658                .collect::<Vec<_>>(),
659            vec!["Alpha", "Beta", "Gamma"],
660        );
661
662        let PanelInfo::Tiles { metas } = &tiles.info else {
663            panic!("expected Tiles info");
664        };
665        // The two-panel child expands to two tiles sharing its own meta, and
666        // the *next* child still gets the meta at its own child index — an
667        // implementation keyed on the output index would hand Gamma the first
668        // meta and lose the second entirely.
669        assert_eq!(metas.len(), 3);
670        assert_eq!(
671            metas[0].bounds.origin.x,
672            px(10.),
673            "Alpha keeps child 0's meta"
674        );
675        assert_eq!(
676            metas[1].bounds.origin.x,
677            px(10.),
678            "Beta shares child 0's meta"
679        );
680        assert_eq!(metas[1].z_index, 0);
681        assert_eq!(
682            metas[2].bounds.origin.x,
683            px(400.),
684            "Gamma gets child 1's meta"
685        );
686        assert_eq!(metas[2].z_index, 3);
687    }
688
689    #[test]
690    fn an_empty_tab_group_on_a_tiles_canvas_contributes_no_tile() {
691        let state = PanelState {
692            panel_name: TILES_PANEL_NAME.to_string(),
693            children: vec![
694                // The legacy empty-group form.
695                PanelState {
696                    panel_name: TAB_PANEL_NAME.to_string(),
697                    children: Vec::new(),
698                    info: PanelInfo::panel(serde_json::Value::Null),
699                },
700                tabs_state(vec![panel_state("Alpha")], 0),
701            ],
702            info: PanelInfo::tiles(vec![TileMeta::default(), TileMeta::default()]),
703        };
704
705        let mut builder = RecordingBuilder::default();
706        let tree = PaneTree::from_state(&state, RootKind::Any, &mut builder);
707
708        assert_eq!(builder.built, vec!["Alpha"]);
709        let PaneRef::Tiles { panels } = tree.root().kind() else {
710            panic!()
711        };
712        assert_eq!(panels.len(), 1);
713    }
714
715    #[test]
716    fn tile_bounds_and_z_order_survive_a_round_trip() {
717        let state = canonicalize(include_str!("fixtures/tiles.json"));
718        let tiles = &state.children[0];
719
720        assert_eq!(tiles.panel_name, "Tiles");
721        // `metas` and `children` are parallel arrays, matched up by index. A
722        // bug that swapped `children`'s order while leaving `metas` in place
723        // would misattribute bounds to the wrong panel without either array
724        // changing length, so check both arrays' contents *and* that they
725        // still line up by identity, not just that each array is correct in
726        // isolation.
727        assert_eq!(tiles.children[0].panel_name, "Alpha");
728        assert_eq!(tiles.children[1].panel_name, "Beta");
729
730        let PanelInfo::Tiles { metas } = &tiles.info else {
731            panic!()
732        };
733        assert_eq!(metas.len(), 2);
734        assert_eq!(metas[0].z_index, 0, "Alpha's meta");
735        assert_eq!(metas[0].bounds.origin.x, px(10.), "Alpha's meta");
736        assert_eq!(metas[1].z_index, 1, "Beta's meta");
737        assert_eq!(metas[1].bounds.origin.x, px(220.), "Beta's meta");
738    }
739
740    #[test]
741    fn a_tree_survives_a_round_trip_exactly() {
742        let json = include_str!("fixtures/nested_splits.json");
743        let state: DockAreaState = serde_json::from_str(json).unwrap();
744        let mut panels = PreservingPanels::default();
745        let tree = PaneTree::from_state(&state.center, RootKind::Split, &mut panels);
746
747        let dumped = tree.to_state(&panels);
748        let mut rebuilt_panels = PreservingPanels::default();
749        let rebuilt = PaneTree::from_state(&dumped, RootKind::Split, &mut rebuilt_panels);
750
751        assert_eq!(
752            tree.to_state(&panels),
753            rebuilt.to_state(&rebuilt_panels),
754            "load(dump(t)) must describe the same layout as t"
755        );
756    }
757
758    /// Pins the one value in the schema that means something different now
759    /// than it ever did before: a literal `0.0` slot size sits next to a
760    /// genuine, non-collapsing `200.0` sibling, so the fixture cannot pass by
761    /// accident of single-child-split collapse swallowing the slot. The
762    /// reader must map the `0.0` back to `None` (unconstrained) while
763    /// leaving the `200.0` sibling as `Some`, and the writer must round-trip
764    /// `None` back to the literal `0.0` sentinel.
765    #[test]
766    fn a_zero_size_slot_round_trips_through_the_none_sentinel() {
767        let json = include_str!("fixtures/zero_size_sentinel.json");
768        let state: DockAreaState = serde_json::from_str(json).unwrap();
769        let mut panels = PreservingPanels::default();
770        let tree = PaneTree::from_state(&state.center, RootKind::Split, &mut panels);
771
772        let PaneRef::Split { sizes, .. } = tree.root().kind() else {
773            panic!("expected the root to stay a split");
774        };
775        assert_eq!(
776            sizes,
777            &[None, Some(px(200.))],
778            "the 0.0 sentinel reads back as None, not as a real zero-width panel"
779        );
780
781        let dumped = tree.to_state(&panels);
782        let PanelInfo::Stack { sizes, .. } = &dumped.info else {
783            panic!("expected Stack info");
784        };
785        assert_eq!(
786            sizes,
787            &vec![px(0.), px(200.)],
788            "the unconstrained slot writes back out as the 0.0 sentinel"
789        );
790    }
791
792    /// Pins that a bare `TabPanel` root — the shape every dock in the
793    /// shipped `fixtures/layout.json` (`left_dock`, `right_dock`,
794    /// `bottom_dock`) actually stores — survives a round trip under
795    /// `RootKind::Any` as a `Tabs` node, with its one panel intact.
796    ///
797    /// It does *not* pin that the forced-wrap arm in `from_state` is gated
798    /// on `RootKind::Split` and correctly skipped here. It can't: `normalize`
799    /// runs `collapse_root` on every pass, which un-wraps a single-child
800    /// `Split` root for any `root_kind != RootKind::Split` before this test
801    /// (or anything else) can observe the tree. So if the guard were deleted
802    /// and the wrap fired unconditionally, `collapse_root` would strip the
803    /// synthetic split right back off within the same `normalize()` call,
804    /// and this test would still pass — a correctly-guarded arm and a
805    /// missing guard produce byte-identical output here. The half of the
806    /// guard that *is* observable — the wrap firing and surviving — is
807    /// pinned by `a_split_root_is_forced_even_when_the_state_is_a_tab_group`,
808    /// where `RootKind::Split` makes `collapse_root` return early instead of
809    /// undoing it.
810    #[test]
811    fn a_bare_tab_panel_root_is_not_wrapped_under_root_kind_any() {
812        let json = include_str!("fixtures/bare_tab_panel_root.json");
813        let state: PanelState = serde_json::from_str(json).unwrap();
814        let mut panels = PreservingPanels::default();
815        let tree = PaneTree::from_state(&state, RootKind::Any, &mut panels);
816
817        assert!(
818            matches!(tree.root().kind(), PaneRef::Tabs { .. }),
819            "a bare TabPanel root must stay a Tabs node under RootKind::Any, \
820             not get wrapped in a synthetic split"
821        );
822
823        let dumped = tree.to_state(&panels);
824        assert_eq!(dumped.panel_name, "TabPanel");
825    }
826}