Skip to main content

gpui_component/dock/
tab_panel.rs

1//! The gpui-component appearance for a tab group.
2//!
3//! `gpui_base::dock::TabGroup` owns the behavior — membership, the displayed
4//! tab, drag hit-testing, the zoom flag — and draws none of it. Everything
5//! visible is here: the tab bar, the toolbar, the ellipsis menu, the dock
6//! collapse affordances, the drop placeholder, and the styled drag preview.
7
8use std::{
9    cell::{Cell, RefCell},
10    collections::HashSet,
11    rc::Rc,
12    sync::Arc,
13};
14
15use gpui::{
16    Anchor, AnyElement, AnyView, App, AppContext as _, Context, Div, Empty,
17    InteractiveElement as _, IntoElement, ParentElement as _, Render, ScrollHandle, SharedString,
18    Stateful, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div,
19    prelude::FluentBuilder as _, px, rems,
20};
21use gpui_base::{
22    LogicalStyledExt as _,
23    dock::{
24        AnyDrag, DockPlacement, DragPanel, DropIndicator, NodeId, PaneNode, PaneRef, PanelId,
25        TabGroupContext, TabGroupRenderer,
26    },
27    spring,
28};
29use rust_i18n::t;
30
31use crate::{
32    ActiveTheme as _, IconName, Selectable as _, Sizable as _,
33    button::{Button, ButtonCustomVariant, ButtonVariants as _},
34    dock::{
35        ClosePanel, PanelControl, PanelHandle, PanelStyle, SkinShared, ToggleZoom,
36        toggle_dock_by_user,
37    },
38    h_flex,
39    menu::DropdownMenu as _,
40    tab::{Tab, TabBar},
41};
42
43/// Names the tab bar's zoom button in the debug-bounds map, so a test can ask
44/// a really-drawn frame whether the control was offered.
45const ZOOM_CONTROL_SELECTOR: &str = "dock-tab-bar-zoom-control";
46
47/// Debug-bounds selector for a tab's close (X) button, for tests.
48const CLOSE_BUTTON_SELECTOR: &str = "dock-tab-close-button";
49
50/// Debug-bounds selector prefix for a tab, suffixed with its panel index.
51const TAB_SELECTOR: &str = "dock-tab";
52
53/// Debug-bounds selector prefix for a dock's collapse button, suffixed with
54/// its placement.
55const DOCK_TOGGLE_SELECTOR: &str = "dock-toggle";
56
57/// The size the styled drag preview occupies, reported to base so a drop
58/// placeholder knows where to fly in from.
59const DRAG_PREVIEW_SIZE: gpui::Size<gpui::Pixels> = gpui::size(px(96.), px(30.));
60
61/// The preview that follows the cursor while a panel is dragged.
62///
63/// `gpui_base::dock::DragPanel` is the payload and draws nothing; this is the
64/// appearance half, reintroduced here.
65pub struct DragPanelPreview {
66    panel: Arc<dyn gpui_base::dock::PanelView>,
67}
68
69impl Render for DragPanelPreview {
70    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
71        div()
72            .id("drag-panel")
73            .cursor_grab()
74            .py_1()
75            .px_3()
76            .w_24()
77            .overflow_hidden()
78            .whitespace_nowrap()
79            .border_1()
80            .border_color(cx.theme().border)
81            .rounded(cx.theme().radius)
82            .text_color(cx.theme().tab_foreground)
83            .bg(cx.theme().tokens.tab_active)
84            .opacity(0.75)
85            .child(panel_title(&self.panel, window, cx))
86    }
87}
88
89/// A panel's title, or its registered name when it reached base without this
90/// crate's handle and so carries no presentation. See [`PanelHandle::of`].
91pub(crate) fn panel_title(
92    panel: &Arc<dyn gpui_base::dock::PanelView>,
93    window: &mut Window,
94    cx: &mut App,
95) -> AnyElement {
96    let Some(handle) = PanelHandle::of(panel) else {
97        let name = panel.panel_name(cx);
98        warn_unwrapped_once(panel.panel_id(cx), name);
99        return SharedString::from(name).into_any_element();
100    };
101    handle.title(window, cx)
102}
103
104thread_local! {
105    /// Panels already warned about. `panel_title` sits on the render path, so
106    /// an unguarded warning would repeat at frame rate and bury the very
107    /// signal it exists to give.
108    ///
109    /// Keyed by panel rather than a bare `Once` so a second wrongly installed
110    /// panel is still named, and a runtime set rather than a `debug_assert!`
111    /// so a release build says it too — the consequence is a shipped app whose
112    /// tabs are titleless, which is exactly when someone needs to be told.
113    /// Thread-local because rendering happens on one thread, so no lock is
114    /// needed.
115    static WARNED_UNWRAPPED: RefCell<HashSet<PanelId>> = RefCell::new(HashSet::new());
116}
117
118/// Say once, per panel, that a panel reached the skin without its
119/// presentation handle. Silent otherwise, and visual-only: the panel docks,
120/// drags and persists, it just has no title. The shorter method is the wrong
121/// one — `DockLayout::panel` and `DockArea::add_panel` accept a
122/// `gpui_component::dock::Panel` and store the bare entity — so this says
123/// which panel and what to call instead.
124fn warn_unwrapped_once(panel: PanelId, name: &'static str) {
125    if !WARNED_UNWRAPPED.with(|warned| warned.borrow_mut().insert(panel)) {
126        return;
127    }
128    tracing::warn!(
129        panel = name,
130        "dock panel reached the skin without its presentation handle, so it \
131         draws its panel name instead of its title; install it with \
132         `gpui_component::dock::panel_handle(..)` and `DockLayout::panel_view` \
133         / `DockArea::add_panel_view` rather than `DockLayout::panel` / \
134         `DockArea::add_panel`"
135    );
136}
137
138/// Where the zoom affordance goes for the group's displayed panel, or `None`
139/// when there is none to offer.
140///
141/// Two questions, and both have to be asked. [`Panel::zoom_control`] says
142/// *where* the control appears; [`gpui_base::dock::Panel::zoomable`] says
143/// whether zooming happens at all, and base refuses a zoom that fails it. The
144/// old dock had a single `zoomable() -> Option<PanelControl>` that could not
145/// disagree with itself; split across the seam it can, and a panel answering
146/// `zoomable() == false` with `zoom_control() == Some(Toolbar)` would
147/// otherwise draw a button that does nothing.
148fn zoom_control(group: &TabGroupContext, cx: &App) -> Option<PanelControl> {
149    let panel = group.active_panel()?;
150    panel
151        .zoomable(cx)
152        .then(|| PanelHandle::of(panel).and_then(|handle| handle.zoom_control(cx)))
153        .flatten()
154}
155
156/// The payload for dragging the tab at `ix` out of its group, or `None` when
157/// this group must not be rearranged.
158///
159/// The guard is the skin's. [`TabGroupContext::drag_panel`] answers for any
160/// tab in range whether or not the group may be rearranged, so a tab bar that
161/// forgets to ask [`TabGroupContext::is_draggable`] makes a group that has
162/// nowhere to go — a dock's last group, a locked dock — draggable anyway. The
163/// old dock asked the same question, spelled `state.draggable`.
164fn tab_drag(group: &TabGroupContext, ix: usize, cx: &App) -> Option<DragPanel> {
165    group
166        .is_draggable()
167        .then(|| group.drag_panel(ix, cx))
168        .flatten()
169}
170
171/// The left-most, top-most tab group in a container — where a left dock's
172/// collapse affordance goes. Mirrors the old `StackPanel::left_top_tab_panel`.
173fn left_top_group(node: &PaneNode) -> Option<NodeId> {
174    match node.kind() {
175        PaneRef::Tabs { .. } => Some(node.id()),
176        PaneRef::Split { children, .. } => children.first().and_then(left_top_group),
177    }
178}
179
180/// The right-most, top-most tab group. A vertical split stacks its children,
181/// so its *first* child is the top one; a horizontal split's last child is the
182/// right-most. Mirrors the old `StackPanel::right_top_tab_panel`.
183fn right_top_group(node: &PaneNode) -> Option<NodeId> {
184    match node.kind() {
185        PaneRef::Tabs { .. } => Some(node.id()),
186        PaneRef::Split { axis, children, .. } => match axis {
187            gpui::Axis::Vertical => children.first(),
188            gpui::Axis::Horizontal => children.last(),
189        }
190        .and_then(right_top_group),
191    }
192}
193
194/// One tab group's appearance.
195///
196/// Built per group — `DockAreaRenderer::tab_group_renderer` is called once per
197/// container — so the tab bar's scroll position belongs to the group whose
198/// tabs it scrolls.
199pub(crate) struct TabGroupSkin {
200    shared: Rc<SkinShared>,
201    scroll_handle: ScrollHandle,
202    /// The displayed tab the last frame drew, so a change scrolls the new tab
203    /// into view. The old dock recorded this at the moment of selection; the
204    /// group now owns selection, so the skin notices instead of being told.
205    last_active_ix: Rc<Cell<Option<usize>>>,
206}
207
208impl TabGroupSkin {
209    pub(crate) fn new(shared: Rc<SkinShared>) -> Self {
210        Self {
211            shared,
212            scroll_handle: ScrollHandle::default(),
213            last_active_ix: Rc::new(Cell::new(None)),
214        }
215    }
216
217    /// Whether a dock's collapse affordance belongs in *this* group's tab bar,
218    /// and which way it points. `None` means this group draws none.
219    fn dock_toggle_button(
220        &self,
221        placement: DockPlacement,
222        group: &TabGroupContext,
223        cx: &mut App,
224    ) -> Option<Button> {
225        if group.is_zoomed() || !self.shared.is_toggle_button_visible() {
226            return None;
227        }
228
229        let area = self.shared.area().upgrade()?;
230        let area = area.read(cx);
231        // A dock that does not exist is not collapsible, so this covers the
232        // old `left_dock.is_some()` test too.
233        if !area.is_dock_collapsible(placement) {
234            return None;
235        }
236
237        let designated = match placement {
238            DockPlacement::Left => area
239                .layout(DockPlacement::Center)
240                .and_then(|tree| left_top_group(tree.root())),
241            DockPlacement::Right => area
242                .layout(DockPlacement::Center)
243                .and_then(|tree| right_top_group(tree.root())),
244            DockPlacement::Bottom => area
245                .layout(DockPlacement::Bottom)
246                .and_then(|tree| left_top_group(tree.root())),
247            DockPlacement::Center => None,
248        };
249        if designated != Some(group.node()) {
250            return None;
251        }
252
253        let is_open = area.is_dock_open(placement);
254        // The icon shows the physical side the dock sits on.
255        let icon = match (
256            placement.physical(gpui_base::LayoutDirection::global(cx)),
257            is_open,
258        ) {
259            (DockPlacement::Left, true) => IconName::PanelLeft,
260            (DockPlacement::Left, false) => IconName::PanelLeftOpen,
261            (DockPlacement::Right, true) => IconName::PanelRight,
262            (DockPlacement::Right, false) => IconName::PanelRightOpen,
263            (DockPlacement::Bottom, true) => IconName::PanelBottom,
264            (DockPlacement::Bottom, false) => IconName::PanelBottomOpen,
265            (DockPlacement::Center, _) => return None,
266        };
267
268        let area = self.shared.area().clone();
269        Some(
270            Button::new(SharedString::from(format!("toggle-dock:{:?}", placement)))
271                .icon(icon)
272                .xsmall()
273                .ghost()
274                .tab_stop(false)
275                .tooltip(match is_open {
276                    true => t!("Dock.Collapse"),
277                    false => t!("Dock.Expand"),
278                })
279                .debug_selector(move || format!("{DOCK_TOGGLE_SELECTOR}-{placement:?}"))
280                .on_click(move |_, window, cx| {
281                    _ = area.update(cx, |area, cx| {
282                        toggle_dock_by_user(area, placement, window, cx)
283                    });
284                }),
285        )
286    }
287
288    /// The trailing controls: the panel's own buttons, the zoom affordance,
289    /// and the ellipsis menu.
290    fn render_toolbar(
291        &self,
292        group: &TabGroupContext,
293        window: &mut Window,
294        cx: &mut App,
295    ) -> impl IntoElement {
296        if group.is_collapsed() {
297            return div();
298        }
299
300        let zoomed = group.is_zoomed();
301        let handle = group.active_panel().and_then(PanelHandle::of);
302        let control = zoom_control(group, cx);
303        let toolbar_zoom = control.is_some_and(|control| control.toolbar_visible());
304        let menu_zoom = control.is_some_and(|control| control.menu_visible());
305        let closable = group.is_closable();
306        let buttons = handle.and_then(|handle| handle.toolbar_buttons(window, cx));
307        let panel = handle.map(|handle| handle.panel());
308
309        h_flex()
310            .gap_1()
311            .occlude()
312            .when_some(buttons, |this, buttons| {
313                this.children(
314                    buttons
315                        .into_iter()
316                        .map(|button| button.xsmall().ghost().tab_stop(false)),
317                )
318            })
319            .when_some(
320                match (zoomed, toolbar_zoom) {
321                    (true, _) => Some(("zoom-out", IconName::Minimize, t!("Dock.Zoom Out"))),
322                    (false, true) => Some(("zoom-in", IconName::Maximize, t!("Dock.Zoom In"))),
323                    (false, false) => None,
324                },
325                |this, (id, icon, tooltip)| {
326                    this.child(
327                        Button::new(id)
328                            .icon(icon)
329                            .xsmall()
330                            .ghost()
331                            .tab_stop(false)
332                            .tooltip_with_action(tooltip, &ToggleZoom, None)
333                            .selected(zoomed)
334                            // Whether this button was drawn is the whole of
335                            // the `zoom_control` decision, and there is no
336                            // other way to ask a drawn tree about it. A no-op
337                            // outside test builds; see `debug_selector`.
338                            .debug_selector(|| ZOOM_CONTROL_SELECTOR.to_string())
339                            .on_click({
340                                let group = group.clone();
341                                move |_, window, cx| group.toggle_zoom(window, cx)
342                            }),
343                    )
344                },
345            )
346            .child(
347                Button::new("menu")
348                    .icon(IconName::Ellipsis)
349                    .xsmall()
350                    .ghost()
351                    .tab_stop(false)
352                    .dropdown_menu(move |menu, window, cx| {
353                        menu.when_some(panel.clone(), |menu, panel| {
354                            panel.dropdown_menu(menu, window, cx)
355                        })
356                        .separator()
357                        .menu_with_disabled(
358                            match zoomed {
359                                true => t!("Dock.Zoom Out"),
360                                false => t!("Dock.Zoom In"),
361                            },
362                            Box::new(ToggleZoom),
363                            !menu_zoom,
364                        )
365                        .when(closable, |menu| {
366                            menu.separator()
367                                .menu(t!("Dock.Close"), Box::new(ClosePanel))
368                        })
369                    })
370                    .anchor(Anchor::TopRight),
371            )
372    }
373
374    /// The one-panel title bar: no tabs, just the title and the controls.
375    fn render_title(
376        &self,
377        group: &TabGroupContext,
378        ix: usize,
379        window: &mut Window,
380        cx: &mut App,
381    ) -> AnyElement {
382        let panel = &group.panels()[ix];
383        let left_button = self.dock_toggle_button(DockPlacement::Left, group, cx);
384        let bottom_button = self.dock_toggle_button(DockPlacement::Bottom, group, cx);
385        let right_button = self.dock_toggle_button(DockPlacement::Right, group, cx);
386        let has_leading = left_button.is_some() || bottom_button.is_some();
387        let handle = PanelHandle::of(panel);
388        let title_style = handle.and_then(|handle| handle.title_style(cx));
389        let drag = tab_drag(group, ix, cx);
390
391        h_flex()
392            .flex_row_dir(cx)
393            .justify_between()
394            .h(px(30.))
395            .py_2()
396            .ps(rems(0.75), cx)
397            .pe(rems(0.5), cx)
398            .when(left_button.is_some(), |this| this.ps(rems(0.5), cx))
399            .when(right_button.is_some(), |this| this.pe(rems(0.5), cx))
400            .when_some(title_style, |this, style| {
401                this.bg(style.background).text_color(style.foreground)
402            })
403            .when(has_leading, |this| {
404                this.child(
405                    h_flex()
406                        .flex_shrink_0()
407                        .me(rems(0.25), cx)
408                        .gap_1()
409                        .children(left_button)
410                        .children(bottom_button),
411                )
412            })
413            .child(
414                div()
415                    .id("tab")
416                    .flex_1()
417                    .min_w_16()
418                    .overflow_hidden()
419                    .text_ellipsis()
420                    .whitespace_nowrap()
421                    .child(panel_title(panel, window, cx))
422                    .when_some(drag, |this, drag| {
423                        this.on_drag(drag, {
424                            let panel = panel.clone();
425                            move |drag, offset, _, cx| {
426                                cx.stop_propagation();
427                                drag.set_drag_offset(offset);
428                                drag.set_preview_size(DRAG_PREVIEW_SIZE);
429                                cx.new(|_| DragPanelPreview {
430                                    panel: panel.clone(),
431                                })
432                            }
433                        })
434                    }),
435            )
436            .children(handle.and_then(|handle| handle.title_suffix(window, cx)))
437            .child(
438                h_flex()
439                    .flex_shrink_0()
440                    .ms(rems(0.25), cx)
441                    .gap_1()
442                    .child(self.render_toolbar(group, window, cx))
443                    .children(right_button),
444            )
445            .into_any_element()
446    }
447
448    /// The full tab bar.
449    fn render_tabs(
450        &self,
451        group: &TabGroupContext,
452        window: &mut Window,
453        cx: &mut App,
454    ) -> AnyElement {
455        let left_button = self.dock_toggle_button(DockPlacement::Left, group, cx);
456        let bottom_button = self.dock_toggle_button(DockPlacement::Bottom, group, cx);
457        let right_button = self.dock_toggle_button(DockPlacement::Right, group, cx);
458        let has_leading = left_button.is_some() || bottom_button.is_some();
459        let is_bottom_dock = bottom_button.is_some();
460        let collapsed = group.is_collapsed();
461
462        let droppable = group.is_droppable();
463        let tabs_count = group.panels().len();
464        let active_ix = group.active_ix();
465        let displayed = group.active_panel().map(|panel| panel.panel_id(cx));
466        let visible: Vec<usize> = group
467            .panels()
468            .iter()
469            .enumerate()
470            .filter(|(_, panel)| panel.visible(cx))
471            .map(|(ix, _)| ix)
472            .collect();
473        let displayed_ix = displayed.and_then(|displayed| {
474            group
475                .panels()
476                .iter()
477                .position(|panel| panel.panel_id(cx) == displayed)
478        });
479
480        // Bring a newly displayed tab into view. The group owns selection now,
481        // so the skin notices the change rather than being told about it.
482        if self.last_active_ix.replace(Some(active_ix)) != Some(active_ix) {
483            if let Some(visible_ix) = visible.iter().position(|ix| *ix == active_ix) {
484                self.scroll_handle.scroll_to_item(visible_ix);
485            }
486        }
487
488        TabBar::new("tab-bar")
489            .track_scroll(&self.scroll_handle)
490            .when(has_leading, |this| {
491                this.prefix(
492                    h_flex()
493                        .items_center()
494                        .top_0()
495                        // Overlap the first tab by 1px so their borders don't double up.
496                        .inset_e(-px(1.), cx)
497                        .border_e(px(1.), cx)
498                        .border_b_1()
499                        .h_full()
500                        .border_color(cx.theme().border)
501                        .bg(cx.theme().tokens.tab_bar)
502                        .px_2()
503                        .children(left_button)
504                        .children(bottom_button),
505                )
506            })
507            .children(
508                visible
509                    .into_iter()
510                    .map(|ix| {
511                        let panel = &group.panels()[ix];
512                        let handle = PanelHandle::of(panel);
513                        let drag = tab_drag(group, ix, cx);
514
515                        Tab::new()
516                            .ix(ix)
517                            .debug_selector(move || format!("{TAB_SELECTOR}-{ix}"))
518                            .tab_bar_prefix(has_leading)
519                            .map(|this| match handle.and_then(|handle| handle.tab_name(cx)) {
520                                Some(tab_name) => this.child(tab_name),
521                                None => this.child(panel_title(panel, window, cx)),
522                            })
523                            // Per-tab close (X) button. The gate mirrors
524                            // `TabGroup::close_panel`, plus `!collapsed`, since a
525                            // collapsed strip is a way back in, not a place to
526                            // close. Stops propagation so the click closes by id
527                            // without also selecting the tab.
528                            .when(
529                                !collapsed
530                                    && self.shared.close_button_visible.get()
531                                    && group.is_panel_closable(panel.panel_id(cx), cx),
532                                |this| {
533                                    this.suffix(
534                                        Button::new(("close-tab", ix))
535                                            .icon(IconName::Close)
536                                            .xsmall()
537                                            // The regular ghost hover matches the
538                                            // inactive tab bar background in the
539                                            // default theme. Use a stronger theme
540                                            // surface while keeping a transparent
541                                            // idle background and no border.
542                                            .custom(
543                                                ButtonCustomVariant::new(cx)
544                                                    .foreground(cx.theme().secondary_foreground)
545                                                    .hover(*cx.theme().tokens.secondary_hover)
546                                                    .active(*cx.theme().tokens.secondary_active),
547                                            )
548                                            // The 20px XS button has a 12px icon:
549                                            // 4px inside plus 8px outside matches
550                                            // the label's 12px leading padding.
551                                            // Offset the label's own 12px right
552                                            // padding and the tab's 4px gap so the
553                                            // text-to-icon distance is also 12px.
554                                            .ms(-px(8.), cx)
555                                            .me(rems(0.5), cx)
556                                            .tab_stop(false)
557                                            .debug_selector(|| CLOSE_BUTTON_SELECTOR.to_string())
558                                            .on_click({
559                                                let group = group.clone();
560                                                let panel_id = panel.panel_id(cx);
561                                                move |_, window, cx| {
562                                                    cx.stop_propagation();
563                                                    group.close(panel_id, window, cx);
564                                                }
565                                            }),
566                                    )
567                                },
568                            )
569                            // A collapsed group shows no tab as active: the
570                            // strip is a way back in, not a selection. The
571                            // comparison is against the panel on screen, not
572                            // the stored index: a hidden displayed tab falls
573                            // back to the first visible one.
574                            .selected(!collapsed && Some(ix) == displayed_ix)
575                            .on_click({
576                                let group = group.clone();
577                                let area = self.shared.area().clone();
578                                let last_active_ix = self.last_active_ix.clone();
579                                move |_, window, cx| {
580                                    // The tab bar reveals a clicked tab itself,
581                                    // so the change must not snap it into view.
582                                    last_active_ix.set(Some(ix));
583                                    group.select_tab(ix, window, cx);
584
585                                    // Clicking the strip of a collapsed bottom
586                                    // dock is how it is opened again.
587                                    if is_bottom_dock && collapsed {
588                                        _ = area.update(cx, |area, cx| {
589                                            toggle_dock_by_user(
590                                                area,
591                                                DockPlacement::Bottom,
592                                                window,
593                                                cx,
594                                            )
595                                        });
596                                    }
597                                }
598                            })
599                            // A collapsed group is a strip of tabs with no
600                            // content, so there is nothing to rearrange in it.
601                            .when(!collapsed, |this| {
602                                this.when_some(drag, |this, drag| {
603                                    this.on_drag(drag, {
604                                        let panel = panel.clone();
605                                        move |drag, offset, _, cx| {
606                                            cx.stop_propagation();
607                                            drag.set_drag_offset(offset);
608                                            drag.set_preview_size(DRAG_PREVIEW_SIZE);
609                                            cx.new(|_| DragPanelPreview {
610                                                panel: panel.clone(),
611                                            })
612                                        }
613                                    })
614                                })
615                                .when(droppable, |this| {
616                                    this.drag_over::<DragPanel>(|this, _, _, cx| {
617                                        this.rounded_s(px(0.), cx)
618                                            .border_s(px(2.), cx)
619                                            .border_e(px(0.), cx)
620                                            .border_color(cx.theme().drag_border)
621                                    })
622                                    .on_drop({
623                                        let group = group.clone();
624                                        move |drag: &DragPanel, window, cx| {
625                                            group.drop_panel(
626                                                drag.clone(),
627                                                Some(ix),
628                                                true,
629                                                window,
630                                                cx,
631                                            );
632                                        }
633                                    })
634                                    .drag_over::<AnyDrag>(|this, _, _, cx| {
635                                        this.rounded_s(px(0.), cx)
636                                            .border_s(px(2.), cx)
637                                            .border_e(px(0.), cx)
638                                            .border_color(cx.theme().drag_border)
639                                    })
640                                    .on_drop({
641                                        let group = group.clone();
642                                        move |item: &AnyDrag, window, cx| {
643                                            group.drop_item(item.clone(), None, window, cx);
644                                        }
645                                    })
646                                })
647                            })
648                    })
649                    .collect::<Vec<_>>(),
650            )
651            .last_empty_space(
652                // Empty space so a panel can be moved past the last tab.
653                div()
654                    .id("tab-bar-empty-space")
655                    .h_full()
656                    .flex_grow_1()
657                    .min_w_16()
658                    .when(droppable, |this| {
659                        this.drag_over::<DragPanel>(|this, _, _, cx| {
660                            this.bg(cx.theme().tokens.drop_target)
661                        })
662                        .on_drop({
663                            let group = group.clone();
664                            let node = group.node();
665                            move |drag: &DragPanel, window, cx| {
666                                // A panel dropped past its own last tab lands
667                                // in the final slot; one from elsewhere is
668                                // appended in the background.
669                                let ix = (drag.source() == node).then(|| tabs_count - 1);
670                                group.drop_panel(drag.clone(), ix, false, window, cx);
671                            }
672                        })
673                        .drag_over::<AnyDrag>(|this, _, _, cx| {
674                            this.bg(cx.theme().tokens.drop_target)
675                        })
676                        .on_drop({
677                            let group = group.clone();
678                            move |item: &AnyDrag, window, cx| {
679                                group.drop_item(item.clone(), None, window, cx);
680                            }
681                        })
682                    }),
683            )
684            .when(!collapsed, |this| {
685                this.suffix(
686                    h_flex()
687                        .items_center()
688                        .top_0()
689                        .inset_e(px(0.), cx)
690                        .border_s(px(1.), cx)
691                        .border_b_1()
692                        .h_full()
693                        .border_color(cx.theme().border)
694                        .bg(cx.theme().tokens.tab_bar)
695                        .px_2()
696                        .gap_1()
697                        .children(
698                            group
699                                .active_panel()
700                                .and_then(PanelHandle::of)
701                                .and_then(|handle| handle.title_suffix(window, cx)),
702                        )
703                        .child(self.render_toolbar(group, window, cx))
704                        .children(right_button),
705                )
706            })
707            .into_any_element()
708    }
709}
710
711impl TabGroupRenderer for TabGroupSkin {
712    fn frame(&self, group: &TabGroupContext, _: &mut Window, cx: &mut App) -> Stateful<Div> {
713        let control = zoom_control(group, cx);
714
715        // The column, the fill and the clip are base's now, applied around
716        // this. What is left is the background and the two actions.
717        div()
718            .id("tab-panel")
719            .bg(cx.theme().tokens.background)
720            // A collapsed group is a strip of tabs with no content, and the
721            // actions act on content. The old dock gated them the same way.
722            .when(!group.is_collapsed(), |this| {
723                this.on_action({
724                    let group = group.clone();
725                    move |_: &ToggleZoom, window, cx| {
726                        // The affordance decides the control, so a panel that
727                        // offers none is not zoomed *in* by the keybinding
728                        // either. Zooming out is never refused: a panel that
729                        // stopped offering the control while zoomed would
730                        // otherwise strand the user with no way back.
731                        if !group.is_zoomed() && control.is_none() {
732                            return;
733                        }
734                        group.toggle_zoom(window, cx);
735                    }
736                })
737                .on_action({
738                    let group = group.clone();
739                    move |_: &ClosePanel, window, cx| {
740                        let Some(panel) = group.active_panel() else {
741                            return;
742                        };
743                        let panel = panel.panel_id(cx);
744                        group.close(panel, window, cx);
745                    }
746                })
747            })
748    }
749
750    fn content_frame(
751        &self,
752        group: &TabGroupContext,
753        _: &mut Window,
754        cx: &mut App,
755    ) -> Stateful<Div> {
756        let padded = group.panels().len() > 1
757            && group
758                .active_panel()
759                .and_then(PanelHandle::of)
760                .is_none_or(|handle| handle.inner_padding(cx));
761
762        // The fill and the collapsed-group exception are base's; the padding
763        // is this skin's, and is the only reason this hook is implemented.
764        div().id("active-panel").when(padded, |this| this.pt_2())
765    }
766
767    fn render_tab_bar(
768        &self,
769        group: &TabGroupContext,
770        window: &mut Window,
771        cx: &mut App,
772    ) -> AnyElement {
773        let visible: Vec<usize> = group
774            .panels()
775            .iter()
776            .enumerate()
777            .filter(|(_, panel)| panel.visible(cx))
778            .map(|(ix, _)| ix)
779            .collect();
780
781        match visible.as_slice() {
782            [] => Empty.into_any_element(),
783            [ix] if self.shared.panel_style() == PanelStyle::Auto => {
784                // A panel that draws its own chrome declines the title bar.
785                let panel = &group.panels()[*ix];
786                if PanelHandle::of(panel).is_some_and(|handle| !handle.title_bar(cx)) {
787                    return Empty.into_any_element();
788                }
789                self.render_title(group, *ix, window, cx)
790            }
791            _ => self.render_tabs(group, window, cx),
792        }
793    }
794
795    fn render_active_panel(
796        &self,
797        panel: AnyView,
798        group: &TabGroupContext,
799        _: &mut Window,
800        _: &mut App,
801    ) -> AnyElement {
802        if group.is_collapsed() {
803            return Empty.into_any_element();
804        }
805
806        div()
807            .id("tab-content")
808            .overflow_y_scroll()
809            .overflow_x_hidden()
810            .flex_1()
811            .child(panel.cached(StyleRefinement::default().absolute().size_full()))
812            .into_any_element()
813    }
814
815    fn render_drop_indicator(
816        &self,
817        indicator: DropIndicator,
818        window: &mut Window,
819        cx: &mut App,
820    ) -> Option<AnyElement> {
821        let to = indicator.to();
822        // The placeholder chases the drop it would land in. Its rect was
823        // previously replayed from the drag source on every epoch, so crossing
824        // several drop zones in one drag restarted the walk at each one; the
825        // springs carry it through instead, and the element no longer needs an
826        // outer frame to hold the destination while an inner one walks to it.
827        let id = "drop-placeholder";
828        let placeholder_spring = cx.theme().motion_tokens().spring_move.with_epsilon(0.5);
829        let left = spring((id, "left"), to.origin().x, placeholder_spring, window, cx);
830        let top = spring((id, "top"), to.origin().y, placeholder_spring, window, cx);
831        let width = spring(
832            (id, "width"),
833            to.size().width,
834            placeholder_spring,
835            window,
836            cx,
837        );
838        let height = spring(
839            (id, "height"),
840            to.size().height,
841            placeholder_spring,
842            window,
843            cx,
844        );
845
846        Some(
847            div()
848                .absolute()
849                .bg(cx.theme().tokens.drop_target)
850                .left(left)
851                .top(top)
852                .w(width)
853                .h(height)
854                .into_any_element(),
855        )
856    }
857}
858
859#[cfg(test)]
860mod tests {
861    use std::{
862        cell::{Cell, RefCell},
863        sync::Arc,
864    };
865
866    use gpui::{
867        Entity, EventEmitter, FocusHandle, Focusable, Modifiers, MouseButton, Pixels,
868        TestAppContext, VisualTestContext,
869    };
870    use gpui_base::dock::{DockArea, DockAreaRenderer, DockLayout, DockPlacement, PanelEvent};
871
872    use super::*;
873    use crate::{
874        ElementExt as _,
875        dock::{
876            DockSkin, Panel, panel_handle,
877            test_support::{HideableProbe, MeasuredProbe},
878        },
879    };
880
881    struct Probe {
882        focus_handle: FocusHandle,
883    }
884
885    impl Probe {
886        fn new(cx: &mut App) -> Entity<Self> {
887            cx.new(|cx| Self {
888                focus_handle: cx.focus_handle(),
889            })
890        }
891    }
892
893    impl gpui_base::dock::Panel for Probe {
894        fn panel_name(&self) -> &'static str {
895            "Probe"
896        }
897    }
898
899    impl Panel for Probe {}
900    impl EventEmitter<PanelEvent> for Probe {}
901
902    impl Focusable for Probe {
903        fn focus_handle(&self, _: &App) -> FocusHandle {
904            self.focus_handle.clone()
905        }
906    }
907
908    impl Render for Probe {
909        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
910            Empty
911        }
912    }
913
914    /// Draws nothing, but runs the real gates the skin's tab bar runs and
915    /// records what they decided for every group it was asked to draw.
916    #[derive(Default)]
917    struct Recorded {
918        /// One entry per tab: whether its tab would start a drag.
919        draggable: Vec<bool>,
920    }
921
922    struct Recorder {
923        log: Rc<RefCell<Recorded>>,
924    }
925
926    impl TabGroupRenderer for Recorder {
927        fn render_tab_bar(
928            &self,
929            group: &TabGroupContext,
930            _: &mut Window,
931            cx: &mut App,
932        ) -> AnyElement {
933            let mut log = self.log.borrow_mut();
934            for ix in 0..group.panels().len() {
935                log.draggable.push(tab_drag(group, ix, cx).is_some());
936            }
937            Empty.into_any_element()
938        }
939    }
940
941    impl DockAreaRenderer for Recorder {
942        fn frame(&self, _: &mut Window, _: &mut App) -> Stateful<Div> {
943            div().id("recorder").size_full()
944        }
945
946        fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
947            Rc::new(Recorder {
948                log: self.log.clone(),
949            })
950        }
951    }
952
953    fn recording_area(
954        cx: &mut TestAppContext,
955    ) -> (
956        Entity<DockArea>,
957        Rc<RefCell<Recorded>>,
958        &mut VisualTestContext,
959    ) {
960        cx.update(|cx| {
961            crate::init(cx);
962        });
963        let log = Rc::new(RefCell::new(Recorded::default()));
964        let renderer = Rc::new(Recorder { log: log.clone() });
965        let (area, cx) = cx.add_window_view(|window, cx| {
966            DockArea::new("skin", None, window, cx).with_renderer(renderer)
967        });
968        (area, log, cx)
969    }
970
971    /// The gate carried forward from the old `TabPanel::render`, which wrapped
972    /// `on_drag` in `.when(state.draggable, ..)`. Base does not enforce it:
973    /// `TabGroupContext::drag_panel` answers for any tab in range.
974    #[gpui::test]
975    fn the_last_group_in_a_dock_offers_no_drag(cx: &mut TestAppContext) {
976        let (area, log, cx) = recording_area(cx);
977
978        cx.update(|window, cx| {
979            let layout = DockLayout::tabs().panel_view(panel_handle(Probe::new(cx)), cx);
980            area.update(cx, |area, cx| area.set_center(layout, window, cx));
981        });
982        cx.run_until_parked();
983        log.borrow_mut().draggable.clear();
984        cx.update(|window, cx| crate::test_redraw(window, cx));
985
986        assert_eq!(
987            log.borrow().draggable,
988            vec![false],
989            "the only visible panel in the dock has nowhere to go, so its tab \
990             must not start a drag"
991        );
992    }
993
994    #[gpui::test]
995    fn a_group_beside_another_offers_a_drag(cx: &mut TestAppContext) {
996        let (area, log, cx) = recording_area(cx);
997
998        cx.update(|window, cx| {
999            let layout = DockLayout::h_split()
1000                .child(
1001                    DockLayout::tabs().panel_view(panel_handle(Probe::new(cx)), cx),
1002                    None,
1003                )
1004                .child(
1005                    DockLayout::tabs().panel_view(panel_handle(Probe::new(cx)), cx),
1006                    None,
1007                );
1008            area.update(cx, |area, cx| area.set_center(layout, window, cx));
1009        });
1010        cx.run_until_parked();
1011        log.borrow_mut().draggable.clear();
1012        cx.update(|window, cx| crate::test_redraw(window, cx));
1013
1014        assert_eq!(
1015            log.borrow().draggable,
1016            vec![true, true],
1017            "each group has somewhere to go, so both tabs start a drag"
1018        );
1019    }
1020
1021    /// A panel that allows zooming and asks for the control in the toolbar.
1022    /// `Probe`'s default is `PanelControl::Menu`, which draws no button.
1023    struct ToolbarZoomProbe {
1024        focus_handle: FocusHandle,
1025    }
1026
1027    impl ToolbarZoomProbe {
1028        fn new(cx: &mut App) -> Entity<Self> {
1029            cx.new(|cx| Self {
1030                focus_handle: cx.focus_handle(),
1031            })
1032        }
1033    }
1034
1035    impl gpui_base::dock::Panel for ToolbarZoomProbe {
1036        fn panel_name(&self) -> &'static str {
1037            "ToolbarZoomProbe"
1038        }
1039    }
1040
1041    impl Panel for ToolbarZoomProbe {
1042        fn zoom_control(&self, _: &App) -> Option<PanelControl> {
1043            Some(PanelControl::Toolbar)
1044        }
1045    }
1046
1047    impl EventEmitter<PanelEvent> for ToolbarZoomProbe {}
1048
1049    impl Focusable for ToolbarZoomProbe {
1050        fn focus_handle(&self, _: &App) -> FocusHandle {
1051            self.focus_handle.clone()
1052        }
1053    }
1054
1055    impl Render for ToolbarZoomProbe {
1056        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1057            Empty
1058        }
1059    }
1060
1061    /// A panel that offers no zoom control but leaves base's `zoomable`
1062    /// default alone. Withholding the control is meant to be enough.
1063    struct NoControlProbe {
1064        focus_handle: FocusHandle,
1065    }
1066
1067    impl NoControlProbe {
1068        fn new(cx: &mut App) -> Entity<Self> {
1069            cx.new(|cx| Self {
1070                focus_handle: cx.focus_handle(),
1071            })
1072        }
1073    }
1074
1075    impl gpui_base::dock::Panel for NoControlProbe {
1076        fn panel_name(&self) -> &'static str {
1077            "NoControlProbe"
1078        }
1079    }
1080
1081    impl Panel for NoControlProbe {
1082        fn zoom_control(&self, _: &App) -> Option<PanelControl> {
1083            None
1084        }
1085    }
1086
1087    impl EventEmitter<PanelEvent> for NoControlProbe {}
1088
1089    impl Focusable for NoControlProbe {
1090        fn focus_handle(&self, _: &App) -> FocusHandle {
1091            self.focus_handle.clone()
1092        }
1093    }
1094
1095    impl Render for NoControlProbe {
1096        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1097            Empty
1098        }
1099    }
1100
1101    /// A panel that says "never zoom" in base's half but still names a place
1102    /// for the control in this crate's half.
1103    struct UnzoomableProbe {
1104        focus_handle: FocusHandle,
1105    }
1106
1107    impl gpui_base::dock::Panel for UnzoomableProbe {
1108        fn panel_name(&self) -> &'static str {
1109            "UnzoomableProbe"
1110        }
1111
1112        fn zoomable(&self, _: &App) -> bool {
1113            false
1114        }
1115    }
1116
1117    impl Panel for UnzoomableProbe {
1118        fn zoom_control(&self, _: &App) -> Option<PanelControl> {
1119            Some(PanelControl::Toolbar)
1120        }
1121    }
1122
1123    impl EventEmitter<PanelEvent> for UnzoomableProbe {}
1124
1125    impl Focusable for UnzoomableProbe {
1126        fn focus_handle(&self, _: &App) -> FocusHandle {
1127            self.focus_handle.clone()
1128        }
1129    }
1130
1131    impl Render for UnzoomableProbe {
1132        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1133            Empty
1134        }
1135    }
1136
1137    /// Draw one panel through the real [`DockSkin`] and report whether its tab
1138    /// bar offered a zoom control.
1139    ///
1140    /// The real skin, not a recorder: the bug this guards is `render_toolbar`
1141    /// asking only half the question, so a test that calls `zoom_control`
1142    /// itself would pass with the bug in place.
1143    fn drew_zoom_control(
1144        cx: &mut TestAppContext,
1145        panel: impl FnOnce(&mut App) -> Arc<dyn gpui_base::dock::PanelView>,
1146    ) -> bool {
1147        cx.update(|cx| {
1148            crate::init(cx);
1149        });
1150        let (area, cx) = cx.add_window_view(|window, cx| {
1151            let skin = DockSkin::new(cx);
1152            DockArea::new("skin", None, window, cx).with_renderer(skin)
1153        });
1154
1155        cx.update(|window, cx| {
1156            let layout = DockLayout::tabs().panel_view(panel(cx), cx);
1157            area.update(cx, |area, cx| area.set_center(layout, window, cx));
1158        });
1159        cx.run_until_parked();
1160        cx.update(|window, cx| crate::test_redraw(window, cx));
1161        cx.debug_bounds(ZOOM_CONTROL_SELECTOR).is_some()
1162    }
1163
1164    /// The two halves of the old `zoomable()` can now disagree, and base is
1165    /// the one that decides. A control drawn against base's refusal is dead:
1166    /// pressing it does nothing.
1167    #[gpui::test]
1168    fn a_panel_base_will_not_zoom_gets_no_zoom_control(cx: &mut TestAppContext) {
1169        let drew = drew_zoom_control(cx, |cx| {
1170            panel_handle(cx.new(|cx| UnzoomableProbe {
1171                focus_handle: cx.focus_handle(),
1172            }))
1173        });
1174
1175        assert!(
1176            !drew,
1177            "the panel names a place for the control, but base refuses the zoom"
1178        );
1179    }
1180
1181    /// The other half: a panel that allows zoom and asks for a toolbar control
1182    /// gets one drawn. Without this the test above would also pass a skin that
1183    /// never draws a zoom control at all.
1184    #[gpui::test]
1185    fn a_zoomable_panel_gets_its_zoom_control(cx: &mut TestAppContext) {
1186        let drew = drew_zoom_control(cx, |cx| panel_handle(ToolbarZoomProbe::new(cx)));
1187
1188        assert!(
1189            drew,
1190            "a zoomable panel asking for a toolbar control gets one"
1191        );
1192    }
1193
1194    /// The centre and the bottom dock share the centre column, and both get
1195    /// height.
1196    ///
1197    /// `DockSkin::center_frame` is a flex column holding the centre's root
1198    /// split and the bottom dock, and the centre's split frame sits between
1199    /// them. This pins that the frame carries a size at all: strip
1200    /// `split_frame` of both `size_full` and `flex_1` and every panel here
1201    /// measures zero. It does not pin *which* of the two does the work —
1202    /// either alone passes.
1203    #[gpui::test]
1204    fn the_centre_and_the_bottom_dock_share_the_column(cx: &mut TestAppContext) {
1205        cx.update(|cx| {
1206            crate::init(cx);
1207        });
1208        let centre = Rc::new(Cell::new(px(0.)));
1209        let bottom = Rc::new(Cell::new(px(0.)));
1210        let (area, cx) = cx.add_window_view(|window, cx| {
1211            let skin = DockSkin::new(cx);
1212            DockArea::new("skin", None, window, cx).with_renderer(skin)
1213        });
1214
1215        let (centre_probe, bottom_probe) = (centre.clone(), bottom.clone());
1216        cx.update(|window, cx| {
1217            let centre_panel = MeasuredProbe::new(centre_probe, cx);
1218            let bottom_panel = MeasuredProbe::new(bottom_probe, cx);
1219            area.update(cx, |area, cx| {
1220                // A split inside a split, so the *nested* `split_frame` — the
1221                // one that sits inside a `resizable_panel` — is exercised too,
1222                // not only the centre's root.
1223                area.set_center(
1224                    DockLayout::v_split().child(
1225                        DockLayout::h_split().child(
1226                            DockLayout::tabs().panel_view(panel_handle(centre_panel), cx),
1227                            None,
1228                        ),
1229                        None,
1230                    ),
1231                    window,
1232                    cx,
1233                );
1234                area.set_dock(
1235                    DockPlacement::Bottom,
1236                    DockLayout::tabs().panel_view(panel_handle(bottom_panel), cx),
1237                    window,
1238                    cx,
1239                );
1240                area.set_dock_size(DockPlacement::Bottom, px(200.), window, cx);
1241            });
1242        });
1243        cx.run_until_parked();
1244        cx.update(|window, cx| crate::test_redraw(window, cx));
1245
1246        let window_height = cx.update(|window, _| window.viewport_size().height);
1247        assert!(
1248            centre.get() > px(0.),
1249            "the centre panel must receive height; it got {:?}",
1250            centre.get()
1251        );
1252        assert!(
1253            bottom.get() > px(0.),
1254            "the bottom dock's panel must receive height; it got {:?}",
1255            bottom.get()
1256        );
1257        assert!(
1258            centre.get() < window_height - px(150.),
1259            "the centre must give the 200px bottom dock its share; the centre \
1260             got {:?} of {window_height:?}",
1261            centre.get()
1262        );
1263    }
1264
1265    /// Whichever slots of a split are hidden, the drawn ones fill it.
1266    ///
1267    /// `render_node` pins every slot but one to a fixed size and lets the
1268    /// remaining one absorb whatever the container has spare. Picking that
1269    /// slot by tree position alone picks a hidden one whenever the trailing
1270    /// container's panels are all hidden — nothing draws there, nothing
1271    /// grows, and the split stops short of its frame, showing a band of the
1272    /// frame's own background under the last visible panel. Hiding a slot is
1273    /// an everyday event: a panel that is only meaningful for some symbols
1274    /// answers `visible` with `false` for the rest.
1275    ///
1276    /// Every subset is covered because the defect is positional: only the
1277    /// cases that hide the trailing slot fail, and a test that hid one fixed
1278    /// slot would pass against a fix that only special-cased that slot.
1279    #[gpui::test]
1280    fn a_split_fills_its_container_whichever_slots_are_hidden(cx: &mut TestAppContext) {
1281        cx.update(|cx| {
1282            crate::init(cx);
1283        });
1284        let heights: Vec<Rc<Cell<Pixels>>> = (0..3).map(|_| Rc::new(Cell::new(px(0.)))).collect();
1285        let (area, cx) = cx.add_window_view(|window, cx| {
1286            let skin = DockSkin::new(cx);
1287            DockArea::new("skin", None, window, cx).with_renderer(skin)
1288        });
1289
1290        let slots = heights.clone();
1291        let probes = cx.update(|window, cx| {
1292            let probes: Vec<_> = slots
1293                .iter()
1294                .map(|height| HideableProbe::new(height.clone(), cx))
1295                .collect();
1296            area.update(cx, |area, cx| {
1297                area.set_dock(
1298                    DockPlacement::Right,
1299                    probes.iter().zip([260., 320., 200.]).fold(
1300                        DockLayout::v_split(),
1301                        |split, (probe, size)| {
1302                            split.child(
1303                                DockLayout::tabs().panel_view(panel_handle(probe.clone()), cx),
1304                                Some(px(size)),
1305                            )
1306                        },
1307                    ),
1308                    window,
1309                    cx,
1310                );
1311                area.set_dock_size(DockPlacement::Right, px(380.), window, cx);
1312            });
1313            probes
1314        });
1315        cx.run_until_parked();
1316        let draw = |cx: &mut VisualTestContext| {
1317            cx.update(|window, _| window.refresh());
1318            cx.update(|window, cx| crate::test_redraw(window, cx));
1319            cx.update(|window, cx| crate::test_redraw(window, cx));
1320        };
1321        draw(cx);
1322
1323        let dock_height = cx.update(|window, _| window.viewport_size().height);
1324        // Each slot spends a tab bar out of its height and the probe under it
1325        // measures the rest, so the drawn slots account for the whole dock
1326        // once one tab bar per drawn slot is added back.
1327        let drawn: Pixels = heights.iter().map(|height| height.get()).sum();
1328        let bar = (dock_height - drawn) / 3.;
1329        assert!(
1330            bar > px(0.) && bar < px(60.),
1331            "the three slots fill the dock to begin with, one tab bar each; \
1332             that leaves {bar:?} per slot of {dock_height:?}"
1333        );
1334
1335        // Every subset except "all three hidden", which gives the whole node
1336        // up to *its* parent and so has no container of its own to fill.
1337        for hidden in 1..0b111u8 {
1338            let shown = (0..3).filter(|slot| hidden & (1 << slot) == 0);
1339            cx.update(|_, cx| {
1340                for (slot, probe) in probes.iter().enumerate() {
1341                    // A sentinel, so a slot that stopped drawing is not read
1342                    // as one that kept the height it had.
1343                    heights[slot].set(px(-1.));
1344                    probe.update(cx, |probe, cx| {
1345                        probe.set_visible(hidden & (1 << slot) == 0, cx)
1346                    });
1347                }
1348            });
1349            cx.run_until_parked();
1350            draw(cx);
1351
1352            let mut count = 0;
1353            let mut total = px(0.);
1354            for slot in shown {
1355                assert_ne!(
1356                    heights[slot].get(),
1357                    px(-1.),
1358                    "hiding {hidden:03b}: slot {slot} is shown and must draw"
1359                );
1360                count += 1;
1361                total += heights[slot].get();
1362            }
1363            let empty = dock_height - total - bar * count as f32;
1364            assert!(
1365                empty.abs() < px(1.),
1366                "hiding {hidden:03b}: the drawn slots must take the hidden \
1367                 ones' space between them; they left {empty:?} of \
1368                 {dock_height:?} empty"
1369            );
1370        }
1371    }
1372
1373    /// The old dock installed `ToggleZoom` and `ClosePanel` on the tab panel
1374    /// itself; base installs neither, so the skin's `frame` is the only place
1375    /// the keybindings reach.
1376    #[gpui::test]
1377    fn the_zoom_action_reaches_the_group_through_the_skin(cx: &mut TestAppContext) {
1378        cx.update(|cx| {
1379            crate::init(cx);
1380        });
1381        let (area, cx) = cx.add_window_view(|window, cx| {
1382            let skin = DockSkin::new(cx);
1383            DockArea::new("skin", None, window, cx).with_renderer(skin)
1384        });
1385
1386        let panel = cx.update(|window, cx| {
1387            let panel = Probe::new(cx);
1388            let layout = DockLayout::tabs().panel_view(panel_handle(panel.clone()), cx);
1389            area.update(cx, |area, cx| area.set_center(layout, window, cx));
1390            panel
1391        });
1392        cx.run_until_parked();
1393        cx.update(|window, cx| {
1394            panel.read(cx).focus_handle(cx).focus(window, cx);
1395        });
1396        cx.run_until_parked();
1397
1398        assert_eq!(cx.read(|cx| area.read(cx).is_zoomed()), false);
1399        cx.dispatch_action(ToggleZoom);
1400        cx.run_until_parked();
1401        assert_eq!(
1402            cx.read(|cx| area.read(cx).is_zoomed()),
1403            true,
1404            "the skin's frame is what carries the ToggleZoom handler"
1405        );
1406
1407        cx.dispatch_action(ToggleZoom);
1408        cx.run_until_parked();
1409        assert_eq!(cx.read(|cx| area.read(cx).is_zoomed()), false);
1410    }
1411
1412    /// Withholding the control withholds the whole affordance, keybinding
1413    /// included. The two halves of the zoom question are asked in one place —
1414    /// the skin's `frame` — so a doc claiming the action gets through anyway
1415    /// would send a panel author looking for a second switch that does not
1416    /// exist.
1417    #[gpui::test]
1418    fn the_zoom_action_refuses_a_panel_that_offers_no_control(cx: &mut TestAppContext) {
1419        cx.update(|cx| {
1420            crate::init(cx);
1421        });
1422        let (area, cx) = cx.add_window_view(|window, cx| {
1423            let skin = DockSkin::new(cx);
1424            DockArea::new("skin", None, window, cx).with_renderer(skin)
1425        });
1426
1427        let panel = cx.update(|window, cx| {
1428            let panel = NoControlProbe::new(cx);
1429            let layout = DockLayout::tabs().panel_view(panel_handle(panel.clone()), cx);
1430            area.update(cx, |area, cx| area.set_center(layout, window, cx));
1431            panel
1432        });
1433        cx.run_until_parked();
1434        cx.update(|window, cx| {
1435            panel.read(cx).focus_handle(cx).focus(window, cx);
1436        });
1437        cx.run_until_parked();
1438
1439        cx.dispatch_action(ToggleZoom);
1440        cx.run_until_parked();
1441        assert_eq!(
1442            cx.read(|cx| area.read(cx).is_zoomed()),
1443            false,
1444            "no control means no zoom, however the zoom was asked for"
1445        );
1446    }
1447
1448    /// The tab group's own frame has to be a flex column.
1449    ///
1450    /// gpui's default display is Block, and block layout ignores a child's
1451    /// `flex_grow`. With a plain `div()` frame the content region's `flex_1`
1452    /// does nothing, `#tab-content` sizes to its content, and its only child
1453    /// is the panel view positioned absolutely by `cached` — which
1454    /// contributes no content height. The whole chain resolves to zero and
1455    /// the dock draws a tab bar with nothing under it.
1456    ///
1457    /// This asserts a dimension, which the project's testing guidance
1458    /// discourages, because a zero-height content region is not a cosmetic
1459    /// difference: it is the panel not rendering at all, and no behavioral
1460    /// test in this crate can see it. `set_active` still fires, the layout
1461    /// still round-trips, and the window still opens.
1462    #[gpui::test]
1463    fn the_panel_content_region_gets_the_height_below_the_tab_bar(cx: &mut TestAppContext) {
1464        cx.update(|cx| {
1465            crate::init(cx);
1466        });
1467        let height = Rc::new(Cell::new(px(0.)));
1468        let (area, cx) = cx.add_window_view(|window, cx| {
1469            let skin = DockSkin::new(cx);
1470            DockArea::new("skin", None, window, cx).with_renderer(skin)
1471        });
1472
1473        let measured = height.clone();
1474        cx.update(|window, cx| {
1475            let panel = MeasuredProbe::new(measured, cx);
1476            let layout = DockLayout::tabs().panel_view(panel_handle(panel), cx);
1477            area.update(cx, |area, cx| area.set_center(layout, window, cx));
1478        });
1479        cx.run_until_parked();
1480        cx.update(|window, cx| crate::test_redraw(window, cx));
1481
1482        let window_height = cx.update(|window, _| window.viewport_size().height);
1483        let content = height.get();
1484        assert!(
1485            content > px(0.),
1486            "the panel must receive height; it got {content:?} in a {window_height:?} window"
1487        );
1488        // The tab bar is 30px and the padded content region adds none for a
1489        // single tab, so the panel should get nearly the whole window.
1490        assert!(
1491            content > window_height - px(60.),
1492            "the panel should fill what the tab bar leaves; it got {content:?} \
1493             of {window_height:?}"
1494        );
1495    }
1496
1497    /// A collapsed group is a strip of tabs with no content, and the actions
1498    /// act on content. The old `TabPanel::bind_actions` gated them the same
1499    /// way.
1500    ///
1501    /// The bottom dock, not a side one: a closed left or right dock draws
1502    /// nothing at all, so it would pass this whether or not the gate exists.
1503    #[gpui::test]
1504    fn a_collapsed_dock_ignores_the_zoom_action(cx: &mut TestAppContext) {
1505        cx.update(|cx| {
1506            crate::init(cx);
1507        });
1508        let (area, cx) = cx.add_window_view(|window, cx| {
1509            let skin = DockSkin::new(cx);
1510            DockArea::new("skin", None, window, cx).with_renderer(skin)
1511        });
1512
1513        let panel = cx.update(|window, cx| {
1514            let panel = Probe::new(cx);
1515            let layout = DockLayout::tabs().panel_view(panel_handle(panel.clone()), cx);
1516            area.update(cx, |area, cx| {
1517                area.set_dock(DockPlacement::Bottom, layout, window, cx);
1518                area.toggle_dock(DockPlacement::Bottom, window, cx);
1519            });
1520            panel
1521        });
1522        cx.run_until_parked();
1523        cx.update(|window, cx| {
1524            panel.read(cx).focus_handle(cx).focus(window, cx);
1525        });
1526        cx.run_until_parked();
1527
1528        cx.dispatch_action(ToggleZoom);
1529        cx.run_until_parked();
1530        assert_eq!(
1531            cx.read(|cx| area.read(cx).is_zoomed()),
1532            false,
1533            "a collapsed group installs no action handler"
1534        );
1535    }
1536
1537    /// A panel that carries its own chrome declines the one-panel title bar
1538    /// and gets the whole group.
1539    #[gpui::test]
1540    fn a_panel_without_a_title_bar_gets_the_whole_group(cx: &mut TestAppContext) {
1541        struct Chromeless {
1542            focus_handle: FocusHandle,
1543            height: Rc<Cell<Pixels>>,
1544        }
1545
1546        impl gpui_base::dock::Panel for Chromeless {
1547            fn panel_name(&self) -> &'static str {
1548                "Chromeless"
1549            }
1550        }
1551
1552        impl Panel for Chromeless {
1553            fn title_bar(&self, _: &App) -> bool {
1554                false
1555            }
1556        }
1557
1558        impl EventEmitter<PanelEvent> for Chromeless {}
1559
1560        impl Focusable for Chromeless {
1561            fn focus_handle(&self, _: &App) -> FocusHandle {
1562                self.focus_handle.clone()
1563            }
1564        }
1565
1566        impl Render for Chromeless {
1567            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1568                let height = self.height.clone();
1569                div()
1570                    .size_full()
1571                    .on_prepaint(move |bounds, _, _| height.set(bounds.size.height))
1572            }
1573        }
1574
1575        cx.update(|cx| crate::init(cx));
1576
1577        let measure = |cx: &mut TestAppContext, chromeless: bool| -> Pixels {
1578            let height = Rc::new(Cell::new(px(0.)));
1579            let (area, cx) = cx.add_window_view(|window, cx| {
1580                let skin = DockSkin::new(cx);
1581                DockArea::new("skin", None, window, cx).with_renderer(skin)
1582            });
1583            let measured = height.clone();
1584            cx.update(|window, cx| {
1585                let panel: Arc<dyn gpui_base::dock::PanelView> = if chromeless {
1586                    panel_handle(cx.new(|cx| Chromeless {
1587                        focus_handle: cx.focus_handle(),
1588                        height: measured,
1589                    }))
1590                } else {
1591                    panel_handle(MeasuredProbe::new(measured, cx))
1592                };
1593                let layout = DockLayout::tabs().panel_view(panel, cx);
1594                area.update(cx, |area, cx| area.set_center(layout, window, cx));
1595            });
1596            cx.run_until_parked();
1597            cx.update(|window, cx| crate::test_redraw(window, cx));
1598            height.get()
1599        };
1600
1601        let with_title = measure(cx, false);
1602        let without = measure(cx, true);
1603        assert!(with_title > px(0.), "the probe must have been drawn");
1604        assert_eq!(
1605            without,
1606            with_title + px(30.),
1607            "the 30px the title bar took go to the panel instead"
1608        );
1609    }
1610
1611    /// Panel with a chosen `closable` that records whether it was made active.
1612    struct TabProbe {
1613        focus_handle: FocusHandle,
1614        closable: bool,
1615        activated: Rc<Cell<bool>>,
1616    }
1617
1618    impl TabProbe {
1619        fn new(closable: bool, cx: &mut App) -> Entity<Self> {
1620            cx.new(|cx| Self {
1621                focus_handle: cx.focus_handle(),
1622                closable,
1623                activated: Rc::new(Cell::new(false)),
1624            })
1625        }
1626    }
1627
1628    impl gpui_base::dock::Panel for TabProbe {
1629        fn panel_name(&self) -> &'static str {
1630            "TabProbe"
1631        }
1632
1633        fn closable(&self, _: &App) -> bool {
1634            self.closable
1635        }
1636
1637        fn set_active(&mut self, active: bool, _: &mut Window, _: &mut Context<Self>) {
1638            if active {
1639                self.activated.set(true);
1640            }
1641        }
1642    }
1643
1644    impl Panel for TabProbe {}
1645
1646    impl EventEmitter<PanelEvent> for TabProbe {}
1647
1648    impl Focusable for TabProbe {
1649        fn focus_handle(&self, _: &App) -> FocusHandle {
1650            self.focus_handle.clone()
1651        }
1652    }
1653
1654    impl Render for TabProbe {
1655        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1656            Empty
1657        }
1658    }
1659
1660    /// Render a two-tab group through the real [`DockSkin`] and report whether
1661    /// the first tab drew a close button. The second tab is a non-closable
1662    /// filler (a lone panel draws no tab bar) that never draws one, so the
1663    /// probe is unambiguous.
1664    fn drew_close_button(cx: &mut TestAppContext, closable: bool, enabled: bool) -> bool {
1665        cx.update(|cx| crate::init(cx));
1666        let mut skin = None;
1667        let (area, cx) = cx.add_window_view(|window, cx| {
1668            let renderer = DockSkin::new(cx);
1669            skin = Some(renderer.clone());
1670            DockArea::new("skin", None, window, cx).with_renderer(renderer)
1671        });
1672        let skin = skin.expect("skin constructed with the area");
1673        if enabled {
1674            cx.update(|_, cx| skin.set_close_button_visible(true, cx));
1675        }
1676        cx.update(|window, cx| {
1677            let under_test = TabProbe::new(closable, cx);
1678            let filler = TabProbe::new(false, cx);
1679            let layout = DockLayout::tabs()
1680                .panel_view(panel_handle(under_test), cx)
1681                .panel_view(panel_handle(filler), cx);
1682            area.update(cx, |area, cx| area.set_center(layout, window, cx));
1683        });
1684        cx.run_until_parked();
1685        cx.update(|window, cx| crate::test_redraw(window, cx));
1686        let button = cx.debug_bounds(CLOSE_BUTTON_SELECTOR);
1687        if enabled && closable {
1688            assert_eq!(
1689                button.as_ref().map(|bounds| bounds.size.width),
1690                Some(px(20.)),
1691                "the close button keeps the standard XS hover target"
1692            );
1693        }
1694        button.is_some()
1695    }
1696
1697    /// A closable panel's tab carries a close (X) button.
1698    #[gpui::test]
1699    fn a_closable_panel_gets_a_close_button(cx: &mut TestAppContext) {
1700        assert!(
1701            drew_close_button(cx, true, true),
1702            "a closable panel's tab must draw a close button"
1703        );
1704    }
1705
1706    /// A non-closable panel draws no close button (the gate is real).
1707    #[gpui::test]
1708    fn a_non_closable_panel_gets_no_close_button(cx: &mut TestAppContext) {
1709        assert!(
1710            !drew_close_button(cx, false, true),
1711            "a panel that reports itself non-closable must draw no close button"
1712        );
1713    }
1714
1715    #[gpui::test]
1716    fn close_buttons_are_off_by_default(cx: &mut TestAppContext) {
1717        assert!(!drew_close_button(cx, true, false));
1718    }
1719
1720    #[gpui::test]
1721    fn close_button_visibility_updates_after_the_skin_setting_changes(cx: &mut TestAppContext) {
1722        cx.update(|cx| crate::init(cx));
1723        let mut skin = None;
1724        let (area, cx) = cx.add_window_view(|window, cx| {
1725            let renderer = DockSkin::new(cx);
1726            skin = Some(renderer.clone());
1727            DockArea::new("skin", None, window, cx).with_renderer(renderer)
1728        });
1729        let skin = skin.expect("skin constructed with the area");
1730        cx.update(|window, cx| {
1731            let panel = TabProbe::new(true, cx);
1732            let filler = TabProbe::new(false, cx);
1733            area.update(cx, |area, cx| {
1734                area.set_center(
1735                    DockLayout::tabs()
1736                        .panel_view(panel_handle(panel), cx)
1737                        .panel_view(panel_handle(filler), cx),
1738                    window,
1739                    cx,
1740                )
1741            });
1742        });
1743
1744        for (visible, expected) in [(false, false), (true, true), (false, false)] {
1745            cx.update(|_, cx| skin.set_close_button_visible(visible, cx));
1746            cx.run_until_parked();
1747            cx.update(|window, cx| crate::test_redraw(window, cx));
1748            assert_eq!(cx.debug_bounds(CLOSE_BUTTON_SELECTOR).is_some(), expected);
1749        }
1750    }
1751
1752    /// Clicking a non-active tab's close button removes that panel by id and
1753    /// does not select it (`stop_propagation`). The displayed tab is a
1754    /// non-closable filler, so the only close button is the one under test.
1755    #[gpui::test]
1756    fn clicking_a_close_button_removes_only_that_tab(cx: &mut TestAppContext) {
1757        cx.update(|cx| crate::init(cx));
1758        let mut skin = None;
1759        let (area, cx) = cx.add_window_view(|window, cx| {
1760            let renderer = DockSkin::new(cx);
1761            skin = Some(renderer.clone());
1762            DockArea::new("skin", None, window, cx).with_renderer(renderer)
1763        });
1764        cx.update(|_, cx| skin.unwrap().set_close_button_visible(true, cx));
1765
1766        let (closable_id, filler_id, activated) = cx.update(|window, cx| {
1767            let filler = TabProbe::new(false, cx);
1768            let closable = TabProbe::new(true, cx);
1769            let activated = closable.read(cx).activated.clone();
1770            let filler_handle = panel_handle(filler);
1771            let closable_handle = panel_handle(closable);
1772            let ids = (closable_handle.panel_id(cx), filler_handle.panel_id(cx));
1773            // Filler at ix 0 is the displayed tab; the closable tab at ix 1 is
1774            // never active, so its close button is the only one drawn.
1775            let layout = DockLayout::tabs()
1776                .panel_view(filler_handle, cx)
1777                .panel_view(closable_handle, cx);
1778            area.update(cx, |area, cx| area.set_center(layout, window, cx));
1779            (ids.0, ids.1, activated)
1780        });
1781        cx.run_until_parked();
1782        cx.update(|window, cx| crate::test_redraw(window, cx));
1783
1784        assert!(
1785            cx.update(|_, cx| area.read(cx).panel(closable_id).is_some()),
1786            "the closable tab starts owned by the area"
1787        );
1788
1789        let button = cx
1790            .debug_bounds(CLOSE_BUTTON_SELECTOR)
1791            .expect("the non-active closable tab draws a close button");
1792        cx.simulate_mouse_down(button.center(), MouseButton::Left, Modifiers::none());
1793        cx.simulate_mouse_up(button.center(), MouseButton::Left, Modifiers::none());
1794        cx.run_until_parked();
1795
1796        assert!(
1797            cx.update(|_, cx| area.read(cx).panel(closable_id).is_none()),
1798            "the close click removes exactly the tab it belongs to"
1799        );
1800        assert!(
1801            cx.update(|_, cx| area.read(cx).panel(filler_id).is_some()),
1802            "the displayed filler tab is untouched"
1803        );
1804        assert!(
1805            !activated.get(),
1806            "stop_propagation keeps the close click from also selecting the tab"
1807        );
1808    }
1809
1810    /// A click is left to the tab bar's animated reveal: the skin's own snap
1811    /// for a changed tab would land the strip on the first frame and cut the
1812    /// animation short.
1813    #[gpui::test]
1814    fn a_clicked_tab_is_revealed_by_the_tab_bar_not_snapped(cx: &mut TestAppContext) {
1815        cx.update(|cx| {
1816            crate::init(cx);
1817            cx.set_reduce_motion(false);
1818        });
1819        let (area, cx) = cx.add_window_view(|window, cx| {
1820            DockArea::new("skin", None, window, cx).with_renderer(DockSkin::new(cx))
1821        });
1822        cx.simulate_resize(gpui::size(px(300.), px(300.)));
1823        cx.update(|window, cx| {
1824            let layout = (0..8).fold(DockLayout::tabs(), |layout, _| {
1825                layout.panel_view(panel_handle(Probe::new(cx)), cx)
1826            });
1827            area.update(cx, |area, cx| area.set_center(layout, window, cx));
1828        });
1829        cx.run_until_parked();
1830        cx.update(|window, cx| crate::test_redraw(window, cx));
1831
1832        // `debug_bounds` takes a `'static` selector.
1833        let tab = |cx: &mut VisualTestContext, ix: usize| {
1834            cx.debug_bounds(format!("{TAB_SELECTOR}-{ix}").leak())
1835                .unwrap()
1836        };
1837        let first_left = |cx: &mut VisualTestContext| tab(cx, 0).left();
1838        let start = first_left(cx);
1839        // The tab that runs off the 300px window: only its first few pixels
1840        // show before the bar's toolbar.
1841        let clipped = (0..8)
1842            .map(|ix| tab(cx, ix))
1843            .find(|tab| tab.right() > px(300.))
1844            .unwrap();
1845
1846        cx.simulate_click(
1847            clipped.origin + gpui::point(px(4.), px(16.)),
1848            Modifiers::none(),
1849        );
1850        cx.update(|window, cx| crate::test_redraw(window, cx));
1851        assert_eq!(first_left(cx), start, "the first frame has not snapped");
1852
1853        let mut lefts = Vec::new();
1854        for _ in 0..60 {
1855            cx.executor()
1856                .advance_clock(std::time::Duration::from_millis(16));
1857            cx.update(|window, cx| {
1858                window.simulate_next_frame(cx);
1859                crate::test_redraw(window, cx);
1860            });
1861            lefts.push(first_left(cx));
1862        }
1863        let end = *lefts.last().unwrap();
1864        assert!(end < start, "the strip scrolled");
1865        assert!(
1866            lefts.iter().any(|left| *left < start && *left > end),
1867            "the strip slid rather than jumped: {lefts:?}"
1868        );
1869    }
1870
1871    /// The collapse button reports the user's toggle; a toggle made by code
1872    /// does not.
1873    #[gpui::test]
1874    fn the_collapse_button_reports_the_toggle(cx: &mut TestAppContext) {
1875        cx.update(|cx| crate::init(cx));
1876        let (area, cx) = cx.add_window_view(|window, cx| {
1877            DockArea::new("toggle", None, window, cx).with_renderer(DockSkin::new(cx))
1878        });
1879        cx.simulate_resize(gpui::size(px(800.), px(600.)));
1880        let events = Rc::new(RefCell::new(Vec::new()));
1881        cx.update(|window, cx| {
1882            let center = DockLayout::tabs().panel_view(panel_handle(Probe::new(cx)), cx);
1883            let left = DockLayout::tabs().panel_view(panel_handle(Probe::new(cx)), cx);
1884            area.update(cx, |area, cx| {
1885                area.set_center(center, window, cx);
1886                area.set_dock(DockPlacement::Left, left, window, cx);
1887            });
1888            let events = events.clone();
1889            cx.subscribe(&area, move |_, event: &crate::dock::DockToggleEvent, _| {
1890                events
1891                    .borrow_mut()
1892                    .push((event.placement(), event.is_open()));
1893            })
1894            .detach();
1895        });
1896        cx.run_until_parked();
1897        cx.update(|window, cx| crate::test_redraw(window, cx));
1898
1899        let selector = format!("{DOCK_TOGGLE_SELECTOR}-{:?}", DockPlacement::Left).leak();
1900        let button = cx
1901            .debug_bounds(selector)
1902            .expect("the left dock offers a toggle");
1903        cx.simulate_click(button.center(), Modifiers::none());
1904        cx.run_until_parked();
1905        assert!(!cx.read(|cx| area.read(cx).is_dock_open(DockPlacement::Left)));
1906        assert_eq!(*events.borrow(), vec![(DockPlacement::Left, false)]);
1907
1908        cx.update(|window, cx| {
1909            area.update(cx, |area, cx| {
1910                area.toggle_dock(DockPlacement::Left, window, cx)
1911            });
1912        });
1913        cx.run_until_parked();
1914        assert_eq!(
1915            events.borrow().len(),
1916            1,
1917            "a toggle made by code is not reported"
1918        );
1919    }
1920
1921    /// Clicking a tab on a collapsed bottom dock's strip opens the dock and
1922    /// reports it.
1923    #[gpui::test]
1924    fn opening_the_bottom_strip_reports_the_toggle(cx: &mut TestAppContext) {
1925        cx.update(|cx| crate::init(cx));
1926        let (area, cx) = cx.add_window_view(|window, cx| {
1927            DockArea::new("strip", None, window, cx).with_renderer(DockSkin::new(cx))
1928        });
1929        cx.simulate_resize(gpui::size(px(800.), px(600.)));
1930        let events = Rc::new(RefCell::new(Vec::new()));
1931        cx.update(|window, cx| {
1932            // Two panels: a group with one panel draws its title, not a tab bar.
1933            let layout = DockLayout::tabs()
1934                .panel_view(panel_handle(Probe::new(cx)), cx)
1935                .panel_view(panel_handle(Probe::new(cx)), cx);
1936            area.update(cx, |area, cx| {
1937                area.set_dock(DockPlacement::Bottom, layout, window, cx);
1938                area.toggle_dock(DockPlacement::Bottom, window, cx);
1939            });
1940            let events = events.clone();
1941            cx.subscribe(&area, move |_, event: &crate::dock::DockToggleEvent, _| {
1942                events
1943                    .borrow_mut()
1944                    .push((event.placement(), event.is_open()));
1945            })
1946            .detach();
1947        });
1948        cx.run_until_parked();
1949        cx.update(|window, cx| crate::test_redraw(window, cx));
1950        assert!(!cx.read(|cx| area.read(cx).is_dock_open(DockPlacement::Bottom)));
1951
1952        let tab = cx
1953            .debug_bounds(format!("{TAB_SELECTOR}-0").leak())
1954            .expect("the collapsed strip still draws its tab");
1955        cx.simulate_click(tab.center(), Modifiers::none());
1956        cx.run_until_parked();
1957        assert_eq!(*events.borrow(), vec![(DockPlacement::Bottom, true)]);
1958    }
1959
1960    /// A dock that refuses to close is not reported as toggled.
1961    #[gpui::test]
1962    fn a_refused_toggle_is_not_reported(cx: &mut TestAppContext) {
1963        cx.update(|cx| crate::init(cx));
1964        let (area, cx) = cx.add_window_view(|window, cx| {
1965            DockArea::new("refuse", None, window, cx).with_renderer(DockSkin::new(cx))
1966        });
1967        let events = Rc::new(RefCell::new(Vec::new()));
1968        cx.update(|window, cx| {
1969            let layout = DockLayout::tabs().panel_view(panel_handle(Probe::new(cx)), cx);
1970            area.update(cx, |area, cx| {
1971                area.set_dock(DockPlacement::Left, layout, window, cx);
1972                area.set_dock_collapsible(DockPlacement::Left, false, window, cx);
1973            });
1974            let events = events.clone();
1975            cx.subscribe(&area, move |_, event: &crate::dock::DockToggleEvent, _| {
1976                events
1977                    .borrow_mut()
1978                    .push((event.placement(), event.is_open()));
1979            })
1980            .detach();
1981        });
1982        cx.update(|window, cx| {
1983            area.update(cx, |area, cx| {
1984                toggle_dock_by_user(area, DockPlacement::Left, window, cx)
1985            });
1986        });
1987        cx.run_until_parked();
1988        assert!(cx.read(|cx| area.read(cx).is_dock_open(DockPlacement::Left)));
1989        assert!(events.borrow().is_empty());
1990    }
1991
1992    /// A collapsed group offers no close button, though the same group does
1993    /// while open. Before/after collapse isolates `!collapsed`; nothing else
1994    /// changes.
1995    #[gpui::test]
1996    fn a_collapsed_group_draws_no_close_button(cx: &mut TestAppContext) {
1997        cx.update(|cx| crate::init(cx));
1998        let mut skin = None;
1999        let (area, cx) = cx.add_window_view(|window, cx| {
2000            let renderer = DockSkin::new(cx);
2001            skin = Some(renderer.clone());
2002            DockArea::new("skin", None, window, cx).with_renderer(renderer)
2003        });
2004        cx.update(|_, cx| skin.unwrap().set_close_button_visible(true, cx));
2005        // Two closable panels so the group is draggable (not on its last
2006        // visible panel) and offers close buttons while open.
2007        cx.update(|window, cx| {
2008            let a = TabProbe::new(true, cx);
2009            let b = TabProbe::new(true, cx);
2010            let layout = DockLayout::tabs()
2011                .panel_view(panel_handle(a), cx)
2012                .panel_view(panel_handle(b), cx);
2013            area.update(cx, |area, cx| {
2014                area.set_dock(DockPlacement::Bottom, layout, window, cx);
2015                if !area.is_dock_open(DockPlacement::Bottom) {
2016                    area.toggle_dock(DockPlacement::Bottom, window, cx);
2017                }
2018            });
2019        });
2020        cx.run_until_parked();
2021        cx.update(|window, cx| crate::test_redraw(window, cx));
2022        assert!(
2023            cx.debug_bounds(CLOSE_BUTTON_SELECTOR).is_some(),
2024            "an open group with two closable panels offers a close button"
2025        );
2026
2027        // Collapse the bottom dock: its strip stays clickable, but the close
2028        // buttons on it must not.
2029        cx.update(|window, cx| {
2030            area.update(cx, |area, cx| {
2031                area.toggle_dock(DockPlacement::Bottom, window, cx)
2032            });
2033        });
2034        cx.run_until_parked();
2035        cx.update(|window, cx| crate::test_redraw(window, cx));
2036        assert!(
2037            cx.debug_bounds(CLOSE_BUTTON_SELECTOR).is_none(),
2038            "a collapsed group must not offer a close button"
2039        );
2040    }
2041}