BREP_app 0.3.0

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//! The dockable / tabbed side-panel layout — an `egui_tiles` tree that hosts
//! every side-panel section AND the 3D viewport as tiles the user can split,
//! tab, resize, and drag-rearrange (IDE-style), with the layout persisted.
//!
//! This is **workbench-agnostic**: the same tree hosts whatever sections a
//! workbench exposes. Which side panes are *visible* is filtered per-workbench
//! by [`workbench::panel_visible`] (e.g. the two Assembly panes show only under
//! the Assembly workbench); positions / tabs / splits come from one shared,
//! persisted layout. New workbench panes plug in with one [`PaneKind`] arm.
//!
//! Structure:
//! * [`PaneKind`] — the serde discriminant of a tile; carries NO state.
//! * [`DockState`] — owns the `Tree<PaneKind>`, load/save/reconcile, and the
//!   per-frame workbench visibility pass. One field on `BrepApp`.
//! * [`DockBehavior`] — a transient, per-frame `egui_tiles::Behavior` built from
//!   disjoint `&mut` borrows of the app's panels + engine (see [`DockContext`]);
//!   its `pane_ui` just delegates to each panel's existing `show(...)`.
//!
//! The shell draws the tree ONLY in normal modeling mode. In sketch / ref-select
//! mode it bypasses the tree and draws the viewport directly (see `app.rs`), so
//! the side panes simply don't appear — no reliance on container-visibility
//! edge cases.

use eframe::egui;
use egui_tiles::{
    Behavior, Container, EditAction, TabState, Tile, TileId, Tiles, Tree, UiResponse,
};
use serde::{Deserialize, Serialize};

use crate::document::Documents;
use crate::panels::assembly_constraints::AssemblyConstraintsPanel;
use crate::panels::component_actions::ComponentActionRequest;
use crate::panels::bom::BomPanel;
use crate::panels::document_tabs::TabsOutcome;
use crate::panels::expressions::ExpressionsPanel;
use crate::panels::history::HistoryPanel;
use crate::panels::scene::ScenePanel;
use crate::panels::update_components::UpdateComponents;
use crate::store::{ModelStore, DOCK_LAYOUT_KEY};
use crate::viewport::Viewport;
use crate::workbench;

/// One tile in the dock tree. A pure discriminant — every panel's real state
/// lives on its own struct (a field of `BrepApp`), reached in `pane_ui`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub enum PaneKind {
    /// ONE OPEN MODEL's 3D view, keyed by [`crate::document::Document::id`].
    ///
    /// These are the document tabs: they all live in a single `Tabs` container
    /// — the DOCUMENT GROUP — whose tab bar IS the model switcher, so the pane
    /// showing 3D views is tabbed by egui_tiles itself rather than carrying a
    /// second hand-drawn strip inside it.
    ///
    /// The id is process-unique and therefore meaningless in a RELOADED layout;
    /// [`DockState::sync_document_panes`] renumbers whatever it finds onto the
    /// live documents, which is what makes the persisted layout survive.
    Document(u64),
    History,
    AssemblyConstraints,
    Bom,
    Scene,
    Expressions,
}

impl PaneKind {
    /// The side panes in default top-to-bottom order (excludes the viewport).
    const SIDE: [PaneKind; 5] = [
        PaneKind::History,
        PaneKind::Bom,
        PaneKind::AssemblyConstraints,
        PaneKind::Scene,
        PaneKind::Expressions,
    ];

    /// Side panes that are ALWAYS in the tree (unclaimed by any workbench). The
    /// THREE Assembly panes (Structure, Constraints, BOM) are excluded — they're
    /// added/removed by workbench membership
    /// ([`DockState::apply_workbench_membership`]).
    const ALWAYS: [PaneKind; 3] = [
        PaneKind::History,
        PaneKind::Scene,
        PaneKind::Expressions,
    ];

    /// Human tab title.
    fn title(self) -> &'static str {
        match self {
            // Only a fallback: the real per-document title (file name + dirty
            // marker) comes from `DockBehavior::tab_title_for_pane`, which can
            // reach the open documents.
            PaneKind::Document(_) => "3D View",
            PaneKind::History => "History",
            // The component TREE. It was titled "BOM" before the BOM
            // existed; now that there is a real columned parts list next to
            // it, the honest name is what it draws.
            PaneKind::Bom => "BOM",
            PaneKind::AssemblyConstraints => "Constraints",
            PaneKind::Scene => "Scene",
            PaneKind::Expressions => "Expressions",
        }
    }

    /// The workbench-registry panel id this pane is claimed under, or `None` for
    /// the viewport (which is not a workbench-filterable panel). Must match the
    /// ids used in `app.rs`'s old `panel_visible` gates + `workbench::assembly`.
    fn panel_id(self) -> Option<&'static str> {
        match self {
            PaneKind::Document(_) => None,
            PaneKind::History => Some("history"),
            PaneKind::Bom => Some(workbench::assembly::BOM_PANEL_ID),
            PaneKind::AssemblyConstraints => Some(workbench::assembly::CONSTRAINTS_PANEL_ID),
            PaneKind::Scene => Some("scene"),
            PaneKind::Expressions => Some("expressions"),
        }
    }

    /// Whether this pane is visible under workbench `wb`. The viewport is always
    /// visible; side panes defer to the workbench claim system.
    fn visible_in(self, wb: &str) -> bool {
        match self.panel_id() {
            None => true,
            Some(id) => workbench::panel_visible(wb, id),
        }
    }
}

/// The dock layout: the tile tree + a dirty flag so a user layout edit persists.
/// One field on `BrepApp`.
pub struct DockState {
    tree: Tree<PaneKind>,
    /// Set by [`DockBehavior::on_edit`] when the user drags / resizes a tile;
    /// drained in [`DockState::ui`] to persist the new layout.
    dirty: bool,
    /// The workbench id membership was last reconciled against. Workbench-claimed
    /// panes (the two Assembly panels) are added to / removed from the tree
    /// *structurally* when the workbench changes — NOT hidden via `set_visible`,
    /// because a hidden pane still owns an (empty) tab bar once panes are tabbed.
    /// Reconciling only on change avoids per-frame tree churn.
    last_wb: Option<String>,
    /// Per-pane `(kind, present, rendered-this-frame)` from the last `ui()` — the
    /// source for the `__brepDock` verifier global. `rendered` is false for a pane
    /// sitting behind an inactive tab (egui_tiles skips its `pane_ui`), so an e2e
    /// script knows to activate that tab before asserting on its widgets.
    snapshot: Vec<(PaneKind, bool, bool)>,
}

/// The disjoint `&mut` borrows the dock needs to draw a frame — assembled by the
/// shell from `BrepApp`'s fields (all distinct, so the borrow checker allows it).
pub struct DockContext<'a> {
    /// The open documents. The dock reaches the ACTIVE engine through
    /// `docs.engine_mut()` — a borrow of one FIELD, so it still composes with
    /// the disjoint panel borrows beside it (see `crate::document`).
    pub docs: &'a mut Documents,
    pub viewport: &'a mut Viewport,
    pub history: &'a mut HistoryPanel,
    pub bom: &'a mut BomPanel,
    pub assembly_constraints: &'a mut AssemblyConstraintsPanel,
    pub scene: &'a mut ScenePanel,
    pub expressions: &'a mut ExpressionsPanel,
    pub update_components: &'a mut UpdateComponents,
    pub model_store: &'a dyn ModelStore,
}

/// What a dock frame hands back to the shell — the SAME cross-panel requests the
/// old left-panel closure bubbled out (borrows inside prevent acting there).
#[derive(Default)]
pub struct DockOutcome {
    /// The ACOMP palette pick asked to open the component-selector modal.
    pub insert_component_requested: bool,
    /// A structure-tree Edit asked to expand this feature in the history tree.
    pub feature_focus: Option<String>,
    /// Structure-tree row interactions (Move / Edit-in-place / Open Part).
    /// A document-level component flow a pane's row menu asked for (the BOM's;
    /// the engine-mutating half already ran in the shared dispatcher).
    pub component_request: Option<ComponentActionRequest>,
    /// What the DOCUMENT TAB STRIP inside the viewport tile was clicked for —
    /// acted on by the shell, which owns the unsaved-changes prompt (close) and
    /// the shared-panel reset (activate).
    pub document_tabs: TabsOutcome,
}

impl DockState {
    /// Load the persisted layout (reconciled against the current pane set), or
    /// fall back to the default layout.
    pub fn new(store: &dyn ModelStore) -> Self {
        let tree = store
            .read(DOCK_LAYOUT_KEY)
            .and_then(|json| serde_json::from_str::<Tree<PaneKind>>(&json).ok())
            .and_then(|mut t| reconcile(&mut t).then_some(t))
            .unwrap_or_else(default_tree);
        Self {
            tree,
            dirty: false,
            last_wb: None,
            snapshot: Vec::new(),
        }
    }

    /// Draw the dock tree, delegating each visible pane to its panel's `show`.
    /// Applies workbench visibility first, then persists if the user re-laid it.
    pub fn ui(&mut self, ui: &mut egui::Ui, ctx: DockContext<'_>) -> DockOutcome {
        let wb = ctx.docs.engine().settings.workbench.clone();
        self.apply_workbench_membership(&wb);
        // One tab per open model, active tab = active model. Must run BEFORE the
        // draw so a document opened or closed last frame is already reflected in
        // the bar the user is about to see.
        if self.sync_document_panes(ctx.docs) {
            self.dirty = true;
        }
        // Restore the group's exclusivity, so a pane the user dropped in there
        // last frame never gets a second frame among the document tabs.
        if self.evict_foreign_panes_from_document_group() {
            self.dirty = true;
        }

        // Snapshot the document identity before the behavior takes `&mut docs`,
        // so the post-draw tab-click read has something to compare against.
        let active_id = ctx.docs.active_id();
        let document_ids: Vec<u64> = ctx.docs.iter().map(|d| d.id()).collect();

        let store = ctx.model_store;
        let mut behavior = DockBehavior {
            docs: ctx.docs,
            viewport: ctx.viewport,
            history: ctx.history,
            bom: ctx.bom,
            assembly_constraints: ctx.assembly_constraints,
            scene: ctx.scene,
            expressions: ctx.expressions,
            update_components: ctx.update_components,
            model_store: ctx.model_store,
            insert_component_requested: false,
            feature_focus: None,
            component_request: None,
            document_tabs: TabsOutcome::default(),
            tab_title_spacing: 0.0,
            layout_changed: false,
            rendered: Vec::new(),
        };
        behavior.tab_title_spacing = behavior.tab_title_spacing(ui.visuals());
        self.tree.ui(&mut behavior, ui);

        // A tab CLICK shows up as egui_tiles' own active tab disagreeing with
        // `Documents`; the shell resolves it by activating that document.
        behavior.document_tabs.activate = self.tab_bar_selection(active_id, &document_ids);

        let outcome = DockOutcome {
            insert_component_requested: behavior.insert_component_requested,
            feature_focus: behavior.feature_focus.take(),
            component_request: behavior.component_request.take(),
            document_tabs: std::mem::take(&mut behavior.document_tabs),
        };
        if behavior.layout_changed {
            self.dirty = true;
        }
        let rendered = std::mem::take(&mut behavior.rendered);
        drop(behavior);

        // Snapshot for the `__brepDock` verifier global (in-tree order).
        self.snapshot = self
            .tree
            .tiles
            .iter()
            .filter_map(|(id, tile)| match tile {
                Tile::Pane(kind) => Some((
                    *kind,
                    self.tree.tiles.is_visible(*id),
                    rendered.contains(kind),
                )),
                Tile::Container(_) => None,
            })
            .collect();

        // Persist the layout, but DEBOUNCED: `on_edit` fires every frame while a
        // tile is being drag-resized (the shares change per mouse-move), so only
        // serialize once the pointer is released — mirrors how the shell defers
        // `applied_ui_scale`. A dirty flag set mid-drag simply waits for release.
        if self.dirty && !ui.ctx().input(|i| i.pointer.any_down()) {
            self.save(store);
            self.dirty = false;
        }
        outcome
    }

    /// The `__brepDock` verifier global: `{active, panes:[{kind,visible,rendered}]}`.
    /// `active` is whether the dock owns the layout right now (false in sketch /
    /// ref-select mode, where the shell draws the viewport directly). When
    /// inactive, no side pane is rendered — the caller passes `active=false`.
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    pub fn state_json(&self, active: bool) -> String {
        let panes: Vec<serde_json::Value> = self
            .snapshot
            .iter()
            .map(|(kind, visible, rendered)| {
                serde_json::json!({
                    "kind": format!("{kind:?}"),
                    "visible": visible,
                    "rendered": active && *rendered,
                })
            })
            .collect();
        serde_json::json!({ "active": active, "panes": panes }).to_string()
    }

    /// Surface the pane of `kind` — make it the ACTIVE tab in its tab group so a
    /// pane sitting behind another tab becomes visible. No-op if it is already
    /// active. Used to bring the History tab forward when a feature is added (a
    /// context-bar create can happen while another side tab is showing), so the
    /// new row is actually seen (`app.rs`, paired with `history.focus_feature`).
    pub fn show_pane(&mut self, kind: PaneKind) {
        self.tree
            .make_active(|_id, tile| matches!(tile, Tile::Pane(k) if *k == kind));
    }

    /// Reconcile which workbench-claimed panes EXIST in the tree against the
    /// active workbench (only when it changed). Claimed panes present in a
    /// workbench that doesn't claim them are removed; ones that should show but
    /// are absent are (re)inserted into the side column. Unclaimed panes
    /// (History / Scene / Expressions / Viewport) are never touched here — they
    /// live in the tree permanently and are arranged only by the user.
    fn apply_workbench_membership(&mut self, wb: &str) {
        if self.last_wb.as_deref() == Some(wb) {
            return;
        }
        self.last_wb = Some(wb.to_string());

        for kind in [PaneKind::AssemblyConstraints, PaneKind::Bom] {
            let should_show = kind.visible_in(wb);
            match (should_show, self.find_pane(kind)) {
                (true, None) => self.insert_side_pane(kind),
                (false, Some(id)) => {
                    self.tree.remove_recursively(id);
                }
                _ => {}
            }
        }
    }

    /// The tile id of the pane of `kind`, if present.
    fn find_pane(&self, kind: PaneKind) -> Option<TileId> {
        self.tree.tiles.iter().find_map(|(id, tile)| match tile {
            Tile::Pane(k) if *k == kind => Some(*id),
            _ => None,
        })
    }

    /// The DOCUMENT GROUP: the `Tabs` container whose tab bar is the model
    /// switcher. Identified by content — the container holding document panes —
    /// so it survives the user re-docking it anywhere in the tree.
    fn document_group(&self) -> Option<TileId> {
        let pane = self.tree.tiles.iter().find_map(|(id, tile)| {
            matches!(tile, Tile::Pane(PaneKind::Document(_))).then_some(*id)
        })?;
        let parent = self.tree.tiles.parent_of(pane)?;
        matches!(self.tree.tiles.get(parent), Some(Tile::Container(Container::Tabs(_))))
            .then_some(parent)
    }

    /// Match the document panes to the OPEN DOCUMENTS: one pane per document, in
    /// the documents' own order, with the active document's pane as the active
    /// tab.
    ///
    /// This is what lets the tab bar be egui_tiles' own rather than a strip drawn
    /// inside a pane. It also absorbs the id problem: `Document` ids are
    /// process-unique, so the panes in a RELOADED layout carry ids from a dead
    /// session. Rather than special-casing that, the pass simply rewrites
    /// whatever it finds onto the live documents — a restored layout keeps its
    /// shape (where the group sits, how wide it is) and gets this session's
    /// documents in it.
    ///
    /// Returns whether the tree changed, so the caller can persist.
    fn sync_document_panes(&mut self, docs: &Documents) -> bool {
        let Some(group) = self.document_group() else {
            return false;
        };
        let wanted: Vec<u64> = docs.iter().map(|d| d.id()).collect();
        let present: Vec<(TileId, u64)> = match self.tree.tiles.get(group) {
            Some(Tile::Container(Container::Tabs(tabs))) => tabs
                .children
                .iter()
                .filter_map(|id| match self.tree.tiles.get(*id) {
                    Some(Tile::Pane(PaneKind::Document(doc))) => Some((*id, *doc)),
                    _ => None,
                })
                .collect(),
            _ => return false,
        };

        let mut changed = false;

        // Re-key the panes we already have onto the wanted documents, in order.
        // A reloaded layout hits this path for every pane; a steady-state frame
        // hits it for none.
        for ((tile, current), want) in present.iter().zip(wanted.iter()) {
            if current != want {
                if let Some(Tile::Pane(kind)) = self.tree.tiles.get_mut(*tile) {
                    *kind = PaneKind::Document(*want);
                    changed = true;
                }
            }
        }

        // Too few panes: a document was opened. Too many: one was closed.
        for want in wanted.iter().skip(present.len()) {
            let tile = self.tree.tiles.insert_pane(PaneKind::Document(*want));
            if let Some(Tile::Container(container)) = self.tree.tiles.get_mut(group) {
                container.add_child(tile);
                changed = true;
            }
        }
        for (tile, _) in present.iter().skip(wanted.len()) {
            self.tree.remove_recursively(*tile);
            changed = true;
        }

        // Point the tab bar at the active document. Done every frame (not only
        // on change) because egui_tiles also moves `active` itself — when a tab
        // is closed, say — and the two must not drift apart.
        let active_id = docs.active_id();
        let active_tile = self.tree.tiles.iter().find_map(|(id, tile)| {
            matches!(tile, Tile::Pane(PaneKind::Document(d)) if *d == active_id).then_some(*id)
        });
        if let (Some(active_tile), Some(Tile::Container(Container::Tabs(tabs)))) =
            (active_tile, self.tree.tiles.get_mut(group))
        {
            if tabs.active != Some(active_tile) {
                tabs.set_active(active_tile);
            }
        }
        changed
    }

    /// Which document the tab bar is currently showing, if it disagrees with
    /// `Documents`. That disagreement is exactly how a TAB CLICK reaches us:
    /// egui_tiles moves its own `active` when the user clicks, and the shell
    /// then activates that document (which `sync_document_panes` will agree with
    /// on the next frame).
    /// Takes an id SNAPSHOT rather than `&Documents` because the live
    /// `Documents` is mutably borrowed by the behavior while the tree draws.
    fn tab_bar_selection(&self, active_id: u64, ids: &[u64]) -> Option<usize> {
        let group = self.document_group()?;
        let Some(Tile::Container(Container::Tabs(tabs))) = self.tree.tiles.get(group) else {
            return None;
        };
        let Some(Tile::Pane(PaneKind::Document(id))) = self.tree.tiles.get(tabs.active?) else {
            return None;
        };
        (*id != active_id).then(|| ids.iter().position(|d| d == id))?
    }

    /// Turf any pane that is not a document out of the DOCUMENT GROUP.
    ///
    /// The group's tab bar must list open models and nothing else. egui_tiles
    /// offers no hook to refuse a drop into a container — `Behavior` can say a
    /// tile is not draggable, which stops a document tab being torn OUT, but
    /// nothing stops a side pane being dropped IN. So the invariant is restored
    /// after the fact instead: a pane dropped in there is moved back to the side
    /// column on the very same frame, before anything is drawn or persisted.
    ///
    /// Returns whether it moved anything, so the caller can persist the layout —
    /// otherwise the eviction would silently repeat on every reload.
    fn evict_foreign_panes_from_document_group(&mut self) -> bool {
        let Some(group) = self.document_group() else {
            return false;
        };
        let intruders: Vec<TileId> = match self.tree.tiles.get(group) {
            Some(Tile::Container(Container::Tabs(tabs))) => tabs
                .children
                .iter()
                .copied()
                .filter(|id| {
                    !matches!(self.tree.tiles.get(*id), Some(Tile::Pane(PaneKind::Document(_))))
                })
                .collect(),
            _ => return false,
        };
        if intruders.is_empty() {
            return false;
        }

        // Detach first, then re-home. The side column is looked up AFTER
        // detaching so it can never resolve to the group itself.
        if let Some(Tile::Container(container)) = self.tree.tiles.get_mut(group) {
            for id in &intruders {
                container.remove_child(*id);
            }
        }
        let target = self.side_column().or_else(|| self.tree.root());
        match target {
            Some(target) if target != group => {
                if let Some(Tile::Container(container)) = self.tree.tiles.get_mut(target) {
                    for id in &intruders {
                        container.add_child(*id);
                    }
                    return true;
                }
                self.put_back(group, &intruders);
                false
            }
            _ => {
                self.put_back(group, &intruders);
                false
            }
        }
    }

    /// Return detached panes to `group`. Losing a pane the user can no longer
    /// reach would be a worse outcome than the layout violation being fixed.
    fn put_back(&mut self, group: TileId, panes: &[TileId]) {
        if let Some(Tile::Container(container)) = self.tree.tiles.get_mut(group) {
            for id in panes {
                container.add_child(*id);
            }
        }
    }

    /// Insert a side pane into the vertical side column (the first vertical
    /// `Linear` container), or the root as a fallback. `all_panes_must_have_tabs`
    /// wraps it in its own tab group on the next frame.
    fn insert_side_pane(&mut self, kind: PaneKind) {
        let id = self.tree.tiles.insert_pane(kind);
        let target = self.side_column().or_else(|| self.tree.root());
        if let Some(target) = target {
            if let Some(Tile::Container(container)) = self.tree.tiles.get_mut(target) {
                container.add_child(id);
            }
        }
    }

    /// The first vertical `Linear` container (the side stack), if any.
    fn side_column(&self) -> Option<TileId> {
        self.tree.tiles.iter().find_map(|(id, tile)| match tile {
            Tile::Container(Container::Linear(lin))
                if lin.dir == egui_tiles::LinearDir::Vertical =>
            {
                Some(*id)
            }
            _ => None,
        })
    }

    /// Serialize the layout through the unified persistence seam (best-effort).
    fn save(&self, store: &dyn ModelStore) {
        if let Ok(json) = serde_json::to_string(&self.tree) {
            let _ = store.write(DOCK_LAYOUT_KEY, &json);
        }
    }
}

/// The default layout: a horizontal split of `[ vertical(side panes) | viewport ]`
/// with the side column biased to ≈ the old 320 px width.
fn default_tree() -> Tree<PaneKind> {
    let mut tiles = Tiles::default();
    let side: Vec<TileId> = PaneKind::SIDE
        .into_iter()
        .map(|k| tiles.insert_pane(k))
        .collect();
    let side_container = tiles.insert_vertical_tile(side);
    // A placeholder document: ids are process-unique, so the real one is put in
    // by `sync_document_panes` on the first frame. It lives in a `Tabs`
    // container from the start — that container IS the document tab bar.
    let placeholder = tiles.insert_pane(PaneKind::Document(0));
    let viewport = tiles.insert_tab_tile(vec![placeholder]);
    let root = tiles.insert_horizontal_tile(vec![side_container, viewport]);
    // Bias the root split so the side column starts narrow (relative shares).
    if let Some(Tile::Container(Container::Linear(linear))) = tiles.get_mut(root) {
        linear.shares.set_share(side_container, 0.30);
        linear.shares.set_share(viewport, 0.70);
    }
    Tree::new("brep-dock", root, tiles)
}

/// Bring a deserialized (possibly stale) tree in line with the current pane set:
/// require exactly one viewport (else the layout is unusable → rebuild default),
/// and append any side pane the saved layout predates. Returns `false` when the
/// tree can't be salvaged, so the caller uses [`default_tree`].
fn reconcile(tree: &mut Tree<PaneKind>) -> bool {
    use std::collections::HashSet;
    let mut document_panes = 0usize;
    let mut present: HashSet<PaneKind> = HashSet::new();
    for tile in tree.tiles.tiles() {
        if let Tile::Pane(kind) = tile {
            if matches!(kind, PaneKind::Document(_)) {
                document_panes += 1;
            }
            present.insert(*kind);
        }
    }
    // A layout with no document pane has nowhere to put the 3D views and no
    // record of where the group belonged, so it is not salvageable — fall back
    // to the default tree. (The COUNT is not checked: a saved layout legitimately
    // holds as many document panes as were open, and `sync_document_panes`
    // renumbers them onto this session's documents.)
    if document_panes == 0 {
        return false;
    }
    let Some(root) = tree.root() else {
        return false;
    };
    // Only the ALWAYS-present panes are required; the workbench-claimed Assembly
    // panes are managed per-workbench and may legitimately be absent.
    for kind in PaneKind::ALWAYS {
        if !present.contains(&kind) {
            let id = tree.tiles.insert_pane(kind);
            if let Some(Tile::Container(container)) = tree.tiles.get_mut(root) {
                container.add_child(id);
            }
        }
    }
    true
}

/// The per-frame `egui_tiles::Behavior`: draws each pane by delegating to the
/// owning panel's existing `show(...)`, and collects the cross-panel requests +
/// a layout-edit flag for the shell to act on after `Tree::ui`.
struct DockBehavior<'a> {
    docs: &'a mut Documents,
    viewport: &'a mut Viewport,
    history: &'a mut HistoryPanel,
    bom: &'a mut BomPanel,
    assembly_constraints: &'a mut AssemblyConstraintsPanel,
    scene: &'a mut ScenePanel,
    expressions: &'a mut ExpressionsPanel,
    update_components: &'a mut UpdateComponents,
    model_store: &'a dyn ModelStore,
    // --- outputs, drained after Tree::ui -----------------------------------
    insert_component_requested: bool,
    feature_focus: Option<String>,
    component_request: Option<ComponentActionRequest>,
    document_tabs: TabsOutcome,
    /// The tab bar's own title spacing, captured at construction from the live
    /// visuals. `on_tab_button` gets no `Ui`, and it needs this to reproduce
    /// egui_tiles' close-button geometry for the verifier's hit rect.
    tab_title_spacing: f32,
    layout_changed: bool,
    /// Panes whose `pane_ui` ran this frame (drawn = visible AND, if tabbed, the
    /// active tab) — feeds the `__brepDock` snapshot.
    rendered: Vec<PaneKind>,
}

/// Whether `tile_id` is a DOCUMENT tab. That single predicate is the whole rule
/// for the document group: such a tab closes (its `✕` shuts the model) and
/// cannot be dragged (tearing it out would put a 3D view outside the group).
fn is_document_tile(tiles: &Tiles<PaneKind>, tile_id: TileId) -> bool {
    matches!(tiles.get(tile_id), Some(Tile::Pane(PaneKind::Document(_))))
}

impl<'a> Behavior<PaneKind> for DockBehavior<'a> {
    fn pane_ui(
        &mut self,
        ui: &mut egui::Ui,
        _tile_id: TileId,
        pane: &mut PaneKind,
    ) -> UiResponse {
        self.rendered.push(*pane);
        // Paint the side-pane background with the SAME fill the old
        // `Panel::left("brep-controls")` used (`visuals().panel_fill`), so the
        // docked panels read exactly like the previous side panel — not the
        // egui_tiles default (which leaves the pane transparent over the darker
        // central fill). The viewport paints its own 3D, so skip it.
        if !matches!(*pane, PaneKind::Document(_)) {
            let visuals = ui.visuals();
            ui.painter()
                .rect_filled(ui.max_rect(), 0.0, visuals.panel_fill);
        }
        match *pane {
            // Only the ACTIVE document's pane is ever drawn — egui_tiles shows
            // one tab at a time, and the tab bar was pointed at the active
            // document by `sync_document_panes` before this ran. The 3D body
            // keeps its own click/drag (camera orbit + picking), so we NEVER
            // report a pane drag here.
            PaneKind::Document(_) => {
                self.viewport.show(ui, self.docs.engine_mut());
            }
            PaneKind::History => scroll(ui, "dock-history", |ui| {
                self.history.show(ui, self.docs.engine_mut());
                // The ACOMP palette pick opens the COMPONENT SELECTOR, not a bare
                // feature dialog — bubbled to the shell (the file dialog is shell-owned).
                self.insert_component_requested |= self.history.take_insert_component_request();
            }),
            PaneKind::Bom => {
                // VERTICAL only, even though a BOM is as wide as its configured
                // columns: the column tree owns its own HORIZONTAL scrolling,
                // because a scroll area out here would carry the frozen columns
                // away with everything else. (The shared `scroll` helper is
                // vertical-only too, but the BOM wants `auto_shrink` off.)
                egui::ScrollArea::vertical()
                    .id_salt("dock-bom")
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        let outcome = self.bom.show(
                            ui,
                            self.docs.engine_mut(),
                            self.model_store,
                            self.update_components,
                        );
                        if outcome.focus.is_some() {
                            // The BOM's Edit action: roll to the owning feature
                            // and open it in the history panel.
                            self.feature_focus = outcome.focus;
                        }
                        if outcome.component.is_some() {
                            self.component_request = outcome.component;
                        }
                    });
            }
            PaneKind::AssemblyConstraints => scroll(ui, "dock-constraints", |ui| {
                self.assembly_constraints.show(
                    ui,
                    self.docs.engine_mut(),
                    self.model_store,
                    self.update_components,
                );
            }),
            PaneKind::Scene => scroll(ui, "dock-scene", |ui| {
                self.scene.show(ui, self.docs.engine_mut());
            }),
            PaneKind::Expressions => {
                // Expressions self-scrolls (its own ScrollArea) — no outer wrap.
                self.expressions.show(ui, self.docs.engine_mut());
            }
        }
        UiResponse::None
    }

    /// A document tab is titled by its FILE, with a bullet while it has unsaved
    /// changes — the tab bar is the only place that state is visible now that
    /// several models are open at once. Every other pane keeps its fixed title.
    fn tab_title_for_pane(&mut self, pane: &PaneKind) -> egui::WidgetText {
        match pane {
            PaneKind::Document(id) => match self.docs.iter().find(|d| d.id() == *id) {
                Some(doc) => {
                    let title = doc.title();
                    // U+2022, not U+25CF: the icon font draws the latter as a
                    // hollow ring, which reads as a status light rather than
                    // "unsaved".
                    if doc.dirty_marker() {
                        format!("{title} \u{2022}").into()
                    } else {
                        title.into()
                    }
                }
                // A pane whose document is gone is about to be removed by
                // `sync_document_panes`; it must not panic in the meantime.
                None => pane.title().into(),
            },
            _ => pane.title().into(),
        }
    }

    /// Only a DOCUMENT tab closes — that is the model's `✕`. Side panels have no
    /// re-open affordance, so they are shown/hidden by workbench and rearranged
    /// by drag, never destroyed.
    fn is_tab_closable(&self, tiles: &Tiles<PaneKind>, tile_id: TileId) -> bool {
        is_document_tile(tiles, tile_id)
    }

    /// A `✕` click. We REFUSE the removal (`false`) and hand the request to the
    /// shell instead: closing a model has to run the unsaved-changes prompt and
    /// drop the document, and only then does its pane go — removed by
    /// `sync_document_panes`. Letting egui_tiles delete the tile here would
    /// close the tab while leaving the document open.
    fn on_tab_close(&mut self, tiles: &mut Tiles<PaneKind>, tile_id: TileId) -> bool {
        if let Some(Tile::Pane(PaneKind::Document(id))) = tiles.get(tile_id) {
            if let Some(index) = self.docs.iter().position(|d| d.id() == *id) {
                self.document_tabs.close = Some(index);
            }
        }
        false
    }

    /// Publish each document tab's screen rect for the headed verifier, keyed
    /// `doctab:<index>` exactly as the old hand-drawn strip did, so the existing
    /// browser checks drive the real tab bar unchanged. This is the hook the
    /// default tab renderer offers for precisely this — it hands back the tab
    /// button's own `Response`, so we keep egui_tiles' native tab drawing.
    fn on_tab_button(
        &mut self,
        tiles: &mut Tiles<PaneKind>,
        tile_id: TileId,
        button_response: egui::Response,
    ) -> egui::Response {
        if let Some(Tile::Pane(PaneKind::Document(id))) = tiles.get(tile_id) {
            if let Some(index) = self.docs.iter().position(|d| d.id() == *id) {
                let tab = button_response.rect;
                // The `✕` is not routed through this hook (egui_tiles calls it
                // once per tab, with the whole tab), so its rect is DERIVED the
                // same way the default tab renderer lays it out: a
                // `close_button_outer_size` square, right-centered in the tab
                // inset by the title spacing. Both inputs come from this same
                // `Behavior`, so an override moves the published rect with it.
                let close = egui::Align2::RIGHT_CENTER.align_size_within_rect(
                    egui::Vec2::splat(self.close_button_outer_size()),
                    tab.shrink(self.tab_title_spacing),
                );
                self.document_tabs.hits.push((format!("doctab:{index}"), tab));
                self.document_tabs
                    .hits
                    .push((format!("doctab:{index}:close"), close));
            }
        }
        button_response
    }

    /// A document tab can't be picked up: dragging one out would tear a 3D view
    /// into its own container somewhere else in the tree, which is the mirror
    /// image of the violation `evict_foreign_panes_from_document_group` guards —
    /// the group must be the ONLY home for 3D views, as well as holding nothing
    /// but them. Side panes drag freely to re-dock.
    fn is_tile_draggable(&self, tiles: &Tiles<PaneKind>, tile_id: TileId) -> bool {
        !is_document_tile(tiles, tile_id)
    }

    fn on_edit(&mut self, _edit_action: EditAction) {
        self.layout_changed = true;
    }

    /// Every pane gets its own tab bar — that tab is the label AND the drag
    /// handle, so a default vertical stack still reads as titled, re-dockable
    /// panes (egui_tiles gives bare linear panes neither). Other simplifications
    /// stay at their defaults so the tree tidies itself after a drag / a
    /// workbench-membership removal.
    fn simplification_options(&self) -> egui_tiles::SimplificationOptions {
        egui_tiles::SimplificationOptions {
            all_panes_must_have_tabs: true,
            ..Default::default()
        }
    }

    /// Match the tab strip to the old side panel's fill (`panel_fill`) so a docked
    /// panel reads as one continuous surface (tab bar + body) in the SAME colour
    /// the previous `Panel::left` used — not the egui_tiles default strip colour.
    fn tab_bar_color(&self, visuals: &egui::Visuals) -> egui::Color32 {
        visuals.panel_fill
    }

    /// Give EVERY tab a visible chip so it reads as a tab — egui_tiles' default
    /// leaves inactive tabs fully transparent (they vanish into the strip). Reuse
    /// egui's standard widget fills: the active tab uses the "active" fill (it
    /// stands out as selected), inactive tabs the "inactive" resting fill (a muted
    /// but clearly-there chip). No hand-picked colours — same DRY rule as the rest.
    fn tab_bg_color(
        &self,
        visuals: &egui::Visuals,
        _tiles: &Tiles<PaneKind>,
        _tile_id: TileId,
        state: &TabState,
    ) -> egui::Color32 {
        if state.active {
            visuals.widgets.active.bg_fill
        } else {
            visuals.widgets.inactive.bg_fill
        }
    }
}

/// Wrap a pane body in its own vertical scroll area (unique id per pane so egui
/// never conflates their scroll state). Panels that self-scroll skip this.
fn scroll(ui: &mut egui::Ui, salt: &str, add: impl FnOnce(&mut egui::Ui)) {
    egui::ScrollArea::vertical()
        .id_salt(salt)
        .auto_shrink([false, false])
        .show(ui, add);
}

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

    fn active_tab(tree: &Tree<PaneKind>) -> Option<TileId> {
        tree.tiles.iter().find_map(|(_, tile)| match tile {
            Tile::Container(Container::Tabs(t)) => t.active,
            _ => None,
        })
    }

    /// `show_pane` makes a BACKGROUNDED pane the active tab — the History-surfacing
    /// behavior the shell pairs with `history.focus_feature` when a feature is
    /// added (`app.rs`), so the new row is actually seen.
    #[test]
    fn show_pane_activates_a_backgrounded_tab() {
        let mut tiles = Tiles::default();
        let history = tiles.insert_pane(PaneKind::History);
        let scene = tiles.insert_pane(PaneKind::Scene);
        let tabs = tiles.insert_tab_tile(vec![history, scene]);
        // Scene in front, History behind it.
        if let Some(Tile::Container(Container::Tabs(t))) = tiles.get_mut(tabs) {
            t.set_active(scene);
        }
        let tree = Tree::new("test-dock", tabs, tiles);
        let mut dock = DockState { tree, dirty: false, last_wb: None, snapshot: Vec::new() };
        assert_eq!(active_tab(&dock.tree), Some(scene), "precondition: History is behind");

        dock.show_pane(PaneKind::History);
        assert_eq!(
            active_tab(&dock.tree),
            Some(history),
            "show_pane brings the History tab to the front"
        );

        // Idempotent + doesn't disturb an already-active pane.
        dock.show_pane(PaneKind::History);
        assert_eq!(active_tab(&dock.tree), Some(history));
    }

    /// A tiny `Documents` for the layout tests: N untitled documents, `active`
    /// selected. The engine is the real one — `Documents` owns it — but nothing
    /// here draws, so no GPU is involved.
    fn docs_with(count: usize, active: usize) -> Documents {
        let mut docs = Documents::new(Box::new(EngineState::new));
        for _ in 1..count {
            let doc = crate::document::Document::new(docs.spawn_engine());
            docs.open_document(doc);
        }
        docs.activate(active);
        docs
    }

    fn document_ids_in_group(dock: &DockState) -> Vec<u64> {
        let group = dock.document_group().expect("document group");
        match dock.tree.tiles.get(group) {
            Some(Tile::Container(Container::Tabs(tabs))) => tabs
                .children
                .iter()
                .filter_map(|id| match dock.tree.tiles.get(*id) {
                    Some(Tile::Pane(PaneKind::Document(d))) => Some(*d),
                    _ => None,
                })
                .collect(),
            _ => panic!("the group must be a Tabs container"),
        }
    }

    fn fresh_dock() -> DockState {
        DockState { tree: default_tree(), dirty: false, last_wb: None, snapshot: Vec::new() }
    }

    /// One tab per open model, in the documents' order — this IS the tab bar.
    #[test]
    fn sync_gives_the_group_one_pane_per_open_document() {
        let docs = docs_with(3, 0);
        let mut dock = fresh_dock();
        assert!(dock.sync_document_panes(&docs), "the placeholder must be re-keyed");
        assert_eq!(
            document_ids_in_group(&dock),
            docs.iter().map(|d| d.id()).collect::<Vec<_>>()
        );
        // Idempotent: a steady-state frame must not report a change, or the
        // layout would be re-serialized forever.
        assert!(!dock.sync_document_panes(&docs), "second pass must be a no-op");
    }

    /// Opening and closing models add and remove tabs.
    #[test]
    fn sync_tracks_documents_opening_and_closing() {
        let mut docs = docs_with(1, 0);
        let mut dock = fresh_dock();
        dock.sync_document_panes(&docs);
        assert_eq!(document_ids_in_group(&dock).len(), 1);

        let doc = crate::document::Document::new(docs.spawn_engine());
        docs.open_document(doc);
        assert!(dock.sync_document_panes(&docs));
        assert_eq!(document_ids_in_group(&dock), docs.iter().map(|d| d.id()).collect::<Vec<_>>());

        docs.close(1);
        assert!(dock.sync_document_panes(&docs));
        assert_eq!(document_ids_in_group(&dock), docs.iter().map(|d| d.id()).collect::<Vec<_>>());
    }

    /// The active document is the active TAB — that is how the bar shows which
    /// model you are looking at.
    #[test]
    fn sync_points_the_tab_bar_at_the_active_document() {
        let docs = docs_with(3, 2);
        let mut dock = fresh_dock();
        dock.sync_document_panes(&docs);
        let group = dock.document_group().unwrap();
        let active = match dock.tree.tiles.get(group) {
            Some(Tile::Container(Container::Tabs(tabs))) => tabs.active.unwrap(),
            _ => panic!("group"),
        };
        assert!(
            matches!(dock.tree.tiles.get(active), Some(Tile::Pane(PaneKind::Document(d))) if *d == docs.active_id())
        );
    }

    /// A RELOADED layout carries document ids from a dead session. They must be
    /// re-keyed onto this session's documents rather than leaving empty tabs.
    #[test]
    fn a_reloaded_layout_is_rekeyed_onto_the_live_documents() {
        let docs = docs_with(2, 0);
        let mut dock = fresh_dock();
        // Stand in for a persisted layout: panes carrying ids nothing owns.
        let group = dock.document_group().unwrap();
        let stale = dock.tree.tiles.insert_pane(PaneKind::Document(9_999));
        if let Some(Tile::Container(container)) = dock.tree.tiles.get_mut(group) {
            container.add_child(stale);
        }
        assert!(dock.sync_document_panes(&docs));
        assert_eq!(
            document_ids_in_group(&dock),
            docs.iter().map(|d| d.id()).collect::<Vec<_>>(),
            "stale ids must be replaced, not appended to"
        );
    }

    /// A tab click reaches the shell as egui_tiles' active tab disagreeing with
    /// `Documents` — and only then.
    #[test]
    fn a_tab_click_is_reported_once_and_not_when_in_sync() {
        let docs = docs_with(3, 0);
        let mut dock = fresh_dock();
        dock.sync_document_panes(&docs);
        let ids: Vec<u64> = docs.iter().map(|d| d.id()).collect();
        assert_eq!(dock.tab_bar_selection(docs.active_id(), &ids), None, "in sync: nothing to report");

        // The user clicks the third tab; egui_tiles moves its own active tab.
        let group = dock.document_group().unwrap();
        let third = match dock.tree.tiles.get(group) {
            Some(Tile::Container(Container::Tabs(tabs))) => tabs.children[2],
            _ => panic!("group"),
        };
        if let Some(Tile::Container(Container::Tabs(tabs))) = dock.tree.tiles.get_mut(group) {
            tabs.set_active(third);
        }
        assert_eq!(dock.tab_bar_selection(docs.active_id(), &ids), Some(2));
    }

    /// The bar must hold models and nothing else. egui_tiles cannot refuse the
    /// drop, so this simulates one — putting a side pane into the document
    /// group, exactly as dropping History onto the tab bar would — and asserts
    /// the next frame throws it back out.
    #[test]
    fn a_pane_dropped_into_the_document_group_is_evicted() {
        let docs = docs_with(1, 0);
        let mut dock = fresh_dock();
        dock.sync_document_panes(&docs);
        let group = dock.document_group().expect("group");
        let history = dock.find_pane(PaneKind::History).expect("history");
        let side = dock.side_column().expect("side column");

        if let Some(Tile::Container(container)) = dock.tree.tiles.get_mut(side) {
            container.remove_child(history);
        }
        if let Some(Tile::Container(container)) = dock.tree.tiles.get_mut(group) {
            container.add_child(history);
        }
        assert_eq!(dock.tree.tiles.parent_of(history), Some(group), "setup");

        assert!(dock.evict_foreign_panes_from_document_group(), "should report a change");
        assert_ne!(
            dock.tree.tiles.parent_of(history),
            Some(group),
            "History must not share the document tab bar"
        );
        // Evicted, not lost — a pane the user can no longer reach would be worse
        // than the violation it fixes.
        assert!(dock.find_pane(PaneKind::History).is_some(), "History must survive");
        assert_eq!(
            document_ids_in_group(&dock).len(),
            1,
            "the document itself must not be disturbed"
        );
    }

    /// The common case: nothing to do, and it must say so — a pass that reported
    /// a change every frame would mark the layout dirty and re-save forever.
    #[test]
    fn a_healthy_tree_is_left_alone() {
        let docs = docs_with(2, 0);
        let mut dock = fresh_dock();
        dock.sync_document_panes(&docs);
        let before = document_ids_in_group(&dock);
        assert!(!dock.evict_foreign_panes_from_document_group(), "nothing to evict");
        assert_eq!(document_ids_in_group(&dock), before);
    }

    /// A document tab must not be draggable: tearing one out would put a 3D view
    /// in a container outside the group, the mirror of a foreign pane landing in.
    #[test]
    fn document_tabs_cannot_be_dragged_out_but_side_panes_can() {
        let docs = docs_with(1, 0);
        let mut dock = fresh_dock();
        dock.sync_document_panes(&docs);
        let doc_pane = dock.tree.tiles.iter().find_map(|(id, tile)| {
            matches!(tile, Tile::Pane(PaneKind::Document(_))).then_some(*id)
        }).expect("document pane");
        let history = dock.find_pane(PaneKind::History).expect("history");

        // `is_document_tile` is what both `is_tile_draggable` and
        // `is_tab_closable` are defined in terms of.
        assert!(is_document_tile(&dock.tree.tiles, doc_pane), "a model tab is a document tile");
        assert!(!is_document_tile(&dock.tree.tiles, history), "a side pane is not");
    }
}