refactor: move panel state into panel stack entity
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run

This commit is contained in:
2026-11-23 04:21:01 +07:00
parent bef96c614b
commit 40c8831bf5
3 changed files with 362 additions and 346 deletions
+47 -259
View File
@@ -2,24 +2,22 @@ pub mod helpers;
mod placeholder; mod placeholder;
mod sign_in; mod sign_in;
use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
ParentElement as _, Render, SharedString, Styled as _, Subscription, WeakEntity, Window, div, Render, SharedString, Styled as _, Subscription, Window, div, px,
px,
}; };
use helpers::apply_appearance_mode; use helpers::apply_appearance_mode;
use settings::SettingsStore; use settings::SettingsStore;
use signed_state::{Backend, BackendEvent}; use signed_state::{Backend, BackendEvent};
use ui::common::{h_flex, v_flex}; use ui::common::{h_flex, v_flex};
use ui::icons::IconRole; use ui::icons::IconRole;
use ui::layout::panel::{Panel, PanelRow, PanelView}; use ui::layout::panel::{PanelRow, PanelStack, PanelView};
use ui::layout::root::RootContext as _; use ui::layout::root::RootContext as _;
use ui::layout::titlebar::Titlebar; use ui::layout::titlebar::Titlebar;
use ui::tabs::{Tab, Tabs, TabsVariant}; use ui::tabs::{Tabs, TabsVariant};
use ui::toast::Toast; use ui::toast::Toast;
use crate::app::placeholder::PlaceholderView; use crate::app::placeholder::PlaceholderView;
@@ -33,18 +31,10 @@ use crate::titlebar::{
}; };
pub struct AppRoot { pub struct AppRoot {
/// The repository shown in the main panel and the detail panels beside it. panel: Entity<PanelStack>,
main: Option<SharedString>,
main_order: Vec<SharedString>,
main_views: HashMap<SharedString, Arc<dyn PanelView>>,
details: Vec<SharedString>,
detail_views: HashMap<SharedString, Arc<dyn PanelView>>,
active_detail: Option<SharedString>,
detail_pane: Entity<DetailPane>,
titlebar: Entity<TitlebarView>, titlebar: Entity<TitlebarView>,
sign_in: Entity<SignedOutView>, sign_in: Entity<SignedOutView>,
explore: Entity<ExploreView>, explore: Entity<ExploreView>,
empty: Entity<PlaceholderView>,
passphrase: Option<Entity<PassphraseDialog>>, passphrase: Option<Entity<PassphraseDialog>>,
_subscriptions: Vec<Subscription>, _subscriptions: Vec<Subscription>,
} }
@@ -54,11 +44,11 @@ impl AppRoot {
bind_repository_shortcuts(cx); bind_repository_shortcuts(cx);
let app = cx.entity().downgrade(); let app = cx.entity().downgrade();
let detail_pane = cx.new(|_| DetailPane { app: app.clone() }); let empty = cx.new(|_| PlaceholderView::new("Select a repository"));
let panel = cx.new(|cx| PanelStack::new(empty.clone().into(), cx));
let titlebar = cx.new(|cx| TitlebarView::new(app.clone(), window, cx)); let titlebar = cx.new(|cx| TitlebarView::new(app.clone(), window, cx));
let sign_in = cx.new(|_| SignedOutView::new()); let sign_in = cx.new(|_| SignedOutView::new());
let explore = cx.new(|cx| ExploreView::new(app.clone(), cx)); let explore = cx.new(|cx| ExploreView::new(app.clone(), cx));
let empty = cx.new(|_| PlaceholderView::new("Select a repository"));
let backend = Backend::global(cx); let backend = Backend::global(cx);
let settings = SettingsStore::global(cx); let settings = SettingsStore::global(cx);
@@ -77,11 +67,12 @@ impl AppRoot {
BackendEvent::SignerChanged => { BackendEvent::SignerChanged => {
let app = cx.entity().downgrade(); let app = cx.entity().downgrade();
let backend = backend.clone(); let backend = backend.clone();
// Fires while AppRoot may still be under construction;
// opening panels reads the root, so run outside its lease.
window.defer(cx, move |window, cx| { window.defer(cx, move |window, cx| {
let signed_in = backend.read(cx).current_user().is_some(); let signed_in = backend.read(cx).current_user().is_some();
log_dropped(app.update(cx, |this, cx| this.clear(cx))); log_dropped(app.update(cx, |this, cx| {
this.clear(cx);
}));
if signed_in { if signed_in {
ExploreView::open(&app, window, cx); ExploreView::open(&app, window, cx);
} }
@@ -103,17 +94,10 @@ impl AppRoot {
}); });
Self { Self {
main: None, panel,
main_order: Vec::new(),
main_views: HashMap::new(),
details: Vec::new(),
detail_views: HashMap::new(),
active_detail: None,
detail_pane,
titlebar, titlebar,
sign_in, sign_in,
explore, explore,
empty,
passphrase: None, passphrase: None,
_subscriptions: subscriptions, _subscriptions: subscriptions,
} }
@@ -128,198 +112,79 @@ impl AppRoot {
cx.open_dialog(dialog); cx.open_dialog(dialog);
} }
pub fn active_main(&self) -> Option<Arc<dyn PanelView>> { /// The panel stack holding the main tile and the detail tiles.
self.main pub fn panel(&self) -> Entity<PanelStack> {
.as_ref() self.panel.clone()
.and_then(|id| self.main_views.get(id))
.cloned()
} }
pub fn active_main_id(&self) -> Option<&SharedString> { pub fn open_main(
self.main.as_ref()
}
pub fn open_mains(&self) -> &[SharedString] {
&self.main_order
}
/// The open main panel with this id.
pub fn main_view(&self, id: &SharedString) -> Option<Arc<dyn PanelView>> {
self.main_views.get(id).cloned()
}
pub fn active_detail(&self) -> Option<Arc<dyn PanelView>> {
self.active_detail
.as_ref()
.and_then(|id| self.detail_views.get(id))
.cloned()
}
pub fn has_main(&self, id: &SharedString) -> bool {
self.main_views.contains_key(id)
}
pub fn has_details(&self) -> bool {
!self.details.is_empty()
}
pub fn has_detail(&self, id: &SharedString) -> bool {
self.detail_views.contains_key(id)
}
pub fn show_main(
&mut self, &mut self,
id: SharedString, id: SharedString,
view: Arc<dyn PanelView>, view: Arc<dyn PanelView>,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
if self.main.as_ref() != Some(&id) { self.panel
self.clear_details(); .update(cx, |panel, cx| panel.open_main(id, view, cx));
}
if !self.main_views.contains_key(&id) {
self.main_order.push(id.clone());
}
self.main_views.insert(id.clone(), view);
self.main = Some(id);
cx.notify();
} }
pub fn activate_main(&mut self, id: &SharedString, cx: &mut Context<Self>) { pub fn open_detail(
if self.main.as_ref() != Some(id) {
self.clear_details();
}
self.main = Some(id.clone());
cx.notify();
}
pub fn activate_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) {
if self.detail_views.contains_key(id) {
self.active_detail = Some(id.clone());
cx.notify();
}
}
pub fn show_detail(
&mut self, &mut self,
id: SharedString, id: SharedString,
view: Arc<dyn PanelView>, view: Arc<dyn PanelView>,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
if !self.details.contains(&id) { self.panel
self.details.push(id.clone()); .update(cx, |panel, cx| panel.open_split(id, view, cx));
}
self.detail_views.insert(id.clone(), view);
self.active_detail = Some(id);
cx.notify();
} }
pub fn close_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) { pub fn close_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) {
let Some(index) = self.details.iter().position(|open| open == id) else { self.panel.update(cx, |panel, cx| panel.close_split(id, cx));
return; }
};
self.close_detail_at(index, cx); pub fn activate_main(&mut self, id: &SharedString, cx: &mut Context<Self>) {
self.panel
.update(cx, |panel, cx| panel.activate_main(id, cx));
} }
pub fn close_main_at(&mut self, index: usize, cx: &mut Context<Self>) { pub fn close_main_at(&mut self, index: usize, cx: &mut Context<Self>) {
if index >= self.main_order.len() { self.panel
return; .update(cx, |panel, cx| panel.close_main_at(index, cx));
}
let id = self.main_order.remove(index);
self.main_views.remove(&id);
if self.main.as_ref() == Some(&id) {
self.main = self
.main_order
.get(index)
.or_else(|| {
index
.checked_sub(1)
.and_then(|prev| self.main_order.get(prev))
})
.cloned();
self.clear_details();
}
cx.notify();
} }
pub fn clear(&mut self, cx: &mut Context<Self>) { pub fn clear(&mut self, cx: &mut Context<Self>) {
self.main = None; self.panel.update(cx, |panel, cx| panel.clear(cx));
self.main_order.clear();
self.main_views.clear();
self.clear_details();
cx.notify();
}
fn clear_details(&mut self) {
self.details.clear();
self.detail_views.clear();
self.active_detail = None;
}
fn close_detail_at(&mut self, index: usize, cx: &mut Context<Self>) {
let id = self.details.remove(index);
self.detail_views.remove(&id);
if self.active_detail.as_ref() == Some(&id) {
self.active_detail = self
.details
.get(index)
.or_else(|| index.checked_sub(1).and_then(|prev| self.details.get(prev)))
.cloned();
}
cx.notify();
}
fn activate_detail_at(&mut self, index: usize, cx: &mut Context<Self>) {
let Some(id) = self.details.get(index) else {
return;
};
self.active_detail = Some(id.clone());
cx.notify();
} }
/// Tabs for the repositories opened in the main panel. /// Tabs for the repositories opened in the main panel.
fn render_repo_tabs(&self, cx: &mut Context<Self>) -> Option<Tabs> { fn render_repo_tabs(&self, cx: &mut Context<Self>) -> Option<Tabs> {
let open = self.open_mains(); let panel = self.panel.read(cx);
if open.is_empty() { if panel.mains().is_empty() {
return None; return None;
} }
let tabs: Vec<_> = open let selected = panel.active_main_index();
let ids: Vec<SharedString> = panel
.mains()
.iter() .iter()
.map(|id| (id.clone(), self.main_view(id))) .map(|panel| panel.id().clone())
.collect(); .collect();
let panel = self.panel.clone();
let selected = self
.active_main_id()
.and_then(|id| open.iter().position(|open_id| open_id == id))
.unwrap_or(usize::MAX);
let app = cx.entity().downgrade(); let app = cx.entity().downgrade();
let close_app = app.clone(); let close_app = app.clone();
let open_for_change = open.to_vec();
Some( Some(
Tabs::new("signed-repo-tabs") Tabs::new("signed-repo-tabs")
.variant(TabsVariant::Titlebar) .variant(TabsVariant::Titlebar)
.overflow_scroll(true) .overflow_scroll(true)
.selected(selected) .selected(selected)
.tabs(move |_, cx| { .tabs(move |_, cx| panel.read(cx).main_tabs(cx))
tabs.iter()
.map(|(id, view)| match view {
Some(view) => view.tab(id.clone().into(), cx).closeable(true),
None => Tab::new(id.clone(), id.clone()).closeable(true),
})
.collect()
})
.on_change(move |index, _, cx| { .on_change(move |index, _, cx| {
let Some(id) = open_for_change.get(index).cloned() else { let Some(id) = ids.get(index) else {
return; return;
}; };
let id = id.clone();
log_dropped(app.update(cx, |app, cx| { log_dropped(app.update(cx, |app, cx| {
app.activate_main(&id, cx); app.activate_main(&id, cx);
})); }));
@@ -340,7 +205,6 @@ impl Render for AppRoot {
let repo_tabs = self.render_repo_tabs(cx); let repo_tabs = self.render_repo_tabs(cx);
let titlebar_view = self.titlebar.read(cx); let titlebar_view = self.titlebar.read(cx);
let main = self.active_main();
div() div()
.relative() .relative()
@@ -378,90 +242,14 @@ impl Render for AppRoot {
titlebar.suffix(menu) titlebar.suffix(menu)
}), }),
) )
.child( .child(if signed_in {
PanelRow::new("signed-panel") self.panel.clone().into_any_element()
.when_some(main.as_ref(), |row, main| { } else {
row.main(main.clone()).when(self.has_details(), |row| { PanelRow::new("signed-out-panel")
row.split(self.detail_pane.clone()) .main(self.sign_in.clone())
})
})
.when(!main.is_some() && signed_in, |row| {
row.main(self.empty.clone())
})
.when(!main.is_some() && !signed_in, |row| {
row.main(self.sign_in.clone())
.split_at(self.explore.clone(), px(300.)) .split_at(self.explore.clone(), px(300.))
}),
),
)
}
}
/// The split pane beside the main panel: detail tabs over the active detail.
struct DetailPane {
app: WeakEntity<AppRoot>,
}
impl Panel for DetailPane {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Workspace")
}
}
impl Render for DetailPane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(app) = self.app.upgrade() else {
return div().into_any_element();
};
let app = app.read(cx);
let selected = app
.active_detail
.as_ref()
.and_then(|active| app.details.iter().position(|id| id == active))
.unwrap_or(usize::MAX);
let details: Vec<_> = app
.details
.iter()
.map(|id| (id.clone(), app.detail_views.get(id).cloned()))
.collect();
let weak = self.app.clone();
let body = app.active_detail().map(|view| view.view());
v_flex()
.size_full()
.gap_2()
.when(app.details.len() > 1, |this| {
let close_weak = weak.clone();
this.child(
Tabs::new("signed-detail-tabs")
.variant(TabsVariant::Pill)
.overflow_scroll(true)
.selected(selected)
.tabs(move |_, cx| {
details
.iter()
.map(|(id, view)| match view {
Some(view) => view.tab(id.clone().into(), cx).closeable(true),
None => Tab::new(id.clone(), id.clone()).closeable(true),
})
.collect()
})
.on_change(move |index, _, cx| {
log_dropped(weak.update(cx, |app, cx| {
app.activate_detail_at(index, cx);
}));
})
.on_close(move |index, _, cx| {
log_dropped(close_weak.update(cx, |app, cx| {
app.close_detail_at(index, cx);
}));
}),
)
})
.child(div().flex_1().min_h_0().w_full().children(body))
.into_any_element() .into_any_element()
}),
)
} }
} }
+29 -84
View File
@@ -5,87 +5,7 @@ use ui::layout::panel::{Panel, PanelView};
use crate::app::AppRoot; use crate::app::AppRoot;
/// Which slot of the workspace a panel opens into. /// Opens a repository in the main panel, reusing its tab when it is already open.
#[derive(Clone, Copy)]
enum PanelSlot {
Main,
Detail,
}
impl PanelSlot {
/// Whether the slot already holds a panel under `id`.
fn has(self, workspace: &WeakEntity<AppRoot>, id: &SharedString, cx: &App) -> bool {
match self {
PanelSlot::Main => workspace
.read_with(cx, |workspace, _| workspace.has_main(id))
.unwrap_or(false),
PanelSlot::Detail => workspace
.read_with(cx, |workspace, _| workspace.has_detail(id))
.unwrap_or(false),
}
}
/// Activates the slot's cached panel under `id`.
fn activate(self, workspace: &WeakEntity<AppRoot>, id: &SharedString, cx: &mut App) {
let result = match self {
PanelSlot::Main => {
workspace.update(cx, |workspace, cx| workspace.activate_main(id, cx))
}
PanelSlot::Detail => {
workspace.update(cx, |workspace, cx| workspace.activate_detail(id, cx))
}
};
if let Err(error) = result {
log::warn!("failed to activate panel {id}: {error}");
}
}
/// Shows the panel in the slot.
fn show(
self,
workspace: &WeakEntity<AppRoot>,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut App,
) {
let result = match self {
PanelSlot::Main => {
workspace.update(cx, |workspace, cx| workspace.show_main(id, view, cx))
}
PanelSlot::Detail => {
workspace.update(cx, |workspace, cx| workspace.show_detail(id, view, cx))
}
};
if let Err(error) = result {
log::warn!("failed to open panel: {error}");
}
}
}
/// Opens a panel in `slot`, reusing it when it is already cached.
fn open_slot<P, F>(
slot: PanelSlot,
workspace: &WeakEntity<AppRoot>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
cx: &mut App,
) where
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
let id = id.into();
if slot.has(workspace, &id, cx) {
slot.activate(workspace, &id, cx);
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
slot.show(workspace, id, view, cx);
}
/// Opens a repository in the main panel, reusing it when it is already cached.
pub fn open_primary<P, F>( pub fn open_primary<P, F>(
workspace: &WeakEntity<AppRoot>, workspace: &WeakEntity<AppRoot>,
id: impl Into<SharedString>, id: impl Into<SharedString>,
@@ -96,10 +16,24 @@ pub fn open_primary<P, F>(
P: Panel + 'static, P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static, F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{ {
open_slot(PanelSlot::Main, workspace, id, build, window, cx); let id = id.into();
if workspace
.read_with(cx, |app, cx| app.panel().read(cx).has(&id))
.unwrap_or(false)
{
if let Err(error) = workspace.update(cx, |app, cx| app.activate_main(&id, cx)) {
log::warn!("failed to activate panel {id}: {error}");
}
return;
} }
/// Opens a detail panel beside the main panel, reusing it when it is already cached. let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
if let Err(error) = workspace.update(cx, |app, cx| app.open_main(id.clone(), view, cx)) {
log::warn!("failed to open panel {id}: {error}");
}
}
/// Opens a detail tile beside the main panel, reusing it when it is already open.
pub fn open_detail<P, F>( pub fn open_detail<P, F>(
workspace: &WeakEntity<AppRoot>, workspace: &WeakEntity<AppRoot>,
id: impl Into<SharedString>, id: impl Into<SharedString>,
@@ -110,5 +44,16 @@ pub fn open_detail<P, F>(
P: Panel + 'static, P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static, F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{ {
open_slot(PanelSlot::Detail, workspace, id, build, window, cx); let id = id.into();
if workspace
.read_with(cx, |app, cx| app.panel().read(cx).has(&id))
.unwrap_or(false)
{
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
if let Err(error) = workspace.update(cx, |app, cx| app.open_detail(id.clone(), view, cx)) {
log::warn!("failed to open panel {id}: {error}");
}
} }
+285 -2
View File
@@ -3,15 +3,22 @@
//! between them; the divider opens at half the row or at a set width //! between them; the divider opens at half the row or at a set width
//! ([`PanelRow::split_at`]), and dragging it can be disabled //! ([`PanelRow::split_at`]), and dragging it can be disabled
//! ([`PanelRow::resizable`]). A double-click restores the half split. //! ([`PanelRow::resizable`]). A double-click restores the half split.
//!
//! The [`PanelStack`] is the stateful variant: a main tile with one tile
//! per opened detail beside it, resizing like the row's split.
use std::sync::Arc; use std::sync::Arc;
use gpui::{ use gpui::{
AnyElement, AnyView, App, Axis, Div, ElementId, Entity, IntoElement, ParentElement as _, AnyElement, AnyView, App, Axis, Context, Div, ElementId, Entity, IntoElement,
Pixels, Render, RenderOnce, SharedString, StyleRefinement, Styled as _, Window, div, ParentElement as _, Pixels, Render, RenderOnce, SharedString, StyleRefinement, Styled as _,
WeakEntity, Window, div,
}; };
use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{ResultLogErr as _, Sizable as _};
use crate::components::tabs::Tab; use crate::components::tabs::Tab;
use crate::icons::IconRole;
use crate::layout::StyledExt as _; use crate::layout::StyledExt as _;
use crate::layout::resizable::{Resizable, ResizableState}; use crate::layout::resizable::{Resizable, ResizableState};
use crate::theme::{ActiveTheme as _, PANE_MIN_SIZE, RESIZE_HANDLE_WIDTH}; use crate::theme::{ActiveTheme as _, PANE_MIN_SIZE, RESIZE_HANDLE_WIDTH};
@@ -269,3 +276,279 @@ impl RenderOnce for PanelRow {
.child(row) .child(row)
} }
} }
/// One tile of the panel stack: a main view or a detail opened beside it.
#[derive(Clone)]
pub struct SubPanel {
id: SharedString,
view: Arc<dyn PanelView>,
}
impl SubPanel {
/// Wraps a panel view under `id`.
pub fn new(id: impl Into<SharedString>, view: Arc<dyn PanelView>) -> Self {
Self {
id: id.into(),
view,
}
}
/// The tile's id.
pub fn id(&self) -> &SharedString {
&self.id
}
/// The tile's panel view.
pub fn view(&self) -> &Arc<dyn PanelView> {
&self.view
}
}
/// The window's panels: the active main tile, plus one tile per opened detail.
pub struct PanelStack {
mains: Vec<SubPanel>,
active_main: Option<SharedString>,
splits: Vec<SubPanel>,
state: Entity<ResizableState>,
fallback: AnyView,
weak_self: WeakEntity<Self>,
style: StyleRefinement,
}
impl PanelStack {
/// Creates a stack showing `fallback` while no panel is open.
pub fn new(fallback: AnyView, cx: &mut Context<Self>) -> Self {
Self {
mains: Vec::new(),
active_main: None,
splits: Vec::new(),
state: ResizableState::new(cx),
fallback,
weak_self: cx.weak_entity(),
style: StyleRefinement::default(),
}
}
/// Shows a panel as the main tile, activating its tab when already open.
pub fn open_main(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut Context<Self>,
) {
if self.mains.iter().any(|panel| panel.id == id) {
if self.active_main.as_ref() != Some(&id) {
self.active_main = Some(id);
self.splits.clear();
cx.notify();
}
} else {
let panel = SubPanel::new(id, view);
self.active_main = Some(panel.id.clone());
self.mains.push(panel);
self.splits.clear();
cx.notify();
}
}
/// Opens a detail tile beside the main tile; open details keep their tile.
pub fn open_split(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut Context<Self>,
) {
if self.splits.iter().any(|panel| panel.id == id) {
return;
}
self.splits.push(SubPanel::new(id, view));
cx.notify();
}
/// Activates the main tile with `id`, closing the detail tiles.
pub fn activate_main(&mut self, id: &SharedString, cx: &mut Context<Self>) {
if self.active_main.as_ref() == Some(id) || !self.mains.iter().any(|panel| panel.id == *id)
{
return;
}
self.active_main = Some(id.clone());
self.splits.clear();
cx.notify();
}
/// Closes the main tab at `index`, activating a neighbor when it was active.
pub fn close_main_at(&mut self, index: usize, cx: &mut Context<Self>) {
if index >= self.mains.len() {
return;
}
let id = self.mains.remove(index).id;
if self.active_main.as_ref() == Some(&id) {
self.active_main = self
.mains
.get(index)
.or_else(|| index.checked_sub(1).and_then(|prev| self.mains.get(prev)))
.map(|panel| panel.id.clone());
self.splits.clear();
}
cx.notify();
}
/// Closes the detail tile with `id`.
pub fn close_split(&mut self, id: &SharedString, cx: &mut Context<Self>) {
self.remove_split(id, cx);
}
/// Closes every panel, leaving the fallback.
pub fn clear(&mut self, cx: &mut Context<Self>) {
self.mains.clear();
self.active_main = None;
self.splits.clear();
cx.notify();
}
/// Whether a main tab or a detail tile is open under `id`.
pub fn has(&self, id: &SharedString) -> bool {
self.mains.iter().any(|panel| &panel.id == id)
|| self.splits.iter().any(|panel| &panel.id == id)
}
/// The main tabs, in open order.
pub fn mains(&self) -> &[SubPanel] {
&self.mains
}
/// The id of the main tile on screen, if any.
pub fn active_main_id(&self) -> Option<&SharedString> {
self.active_main.as_ref()
}
/// Builds the titlebar tabs for the open mains.
pub fn main_tabs(&self, cx: &App) -> Vec<Tab> {
self.mains
.iter()
.map(|panel| panel.view.tab(panel.id.clone().into(), cx).closeable(true))
.collect()
}
/// The active tab's position in [`Self::mains`], or `usize::MAX` when none.
pub fn active_main_index(&self) -> usize {
self.active_main
.as_ref()
.and_then(|active| self.mains.iter().position(|panel| &panel.id == active))
.unwrap_or(usize::MAX)
}
/// Whether a main tile renders; pane 0 is the main tile when it does.
fn has_main_tile(&self) -> bool {
self.active_main.is_some()
}
/// Removes the stored size of the tile at `pane index`, keeping the rest.
fn remove_split(&mut self, id: &SharedString, cx: &mut Context<Self>) {
let Some(index) = self.splits.iter().position(|panel| panel.id == *id) else {
return;
};
self.splits.remove(index);
let base = usize::from(self.has_main_tile());
let pane_count = base + self.splits.len();
let sizes: Vec<Pixels> = self
.state
.read(cx)
.sizes()
.iter()
.enumerate()
.filter(|(ix, _)| *ix != base + index)
.map(|(_, &size)| size)
.take(pane_count.saturating_sub(1))
.collect();
self.state.update(cx, |state, cx| {
state.set_sizes(sizes, cx);
});
cx.notify();
}
}
impl gpui::Styled for PanelStack {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Render for PanelStack {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let content = if self.mains.is_empty() && self.splits.is_empty() {
island(div().size_full().child(self.fallback.clone()), cx).into_any_element()
} else {
let mut resizable = Resizable::new("panel-stack", self.state.clone())
.axis(Axis::Horizontal)
.h_full();
if let Some(main) = self
.active_main
.as_ref()
.and_then(|active| self.mains.iter().find(|panel| &panel.id == active))
{
resizable = resizable.pane(island(
div()
.size_full()
.child(main.view.view().cached(content_style())),
cx,
));
}
for panel in &self.splits {
let id = panel.id.clone();
let weak_self = self.weak_self.clone();
resizable = resizable.pane(
div()
.relative()
.size_full()
.child(island(
div()
.size_full()
.child(panel.view.view().cached(content_style())),
cx,
))
.child(
div().absolute().top_1().right_1().child(
Button::new((ElementId::from("panel-stack-close"), id.clone()))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.xsmall()
.on_click(move |_, window, cx| {
let stack = weak_self.clone();
let id = id.clone();
window.defer(cx, move |_, cx| {
stack
.update(cx, |stack, cx| {
stack.close_split(&id, cx);
})
.log_err();
});
}),
),
),
);
}
div().size_full().child(resizable).into_any_element()
};
div()
.size_full()
.min_w_0()
.p_2()
.pt_1()
.refine_style(&self.style)
.child(content)
.into_any_element()
}
}