refactor: move panel stack state into app root
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 08:44:05 +07:00
parent 40c8831bf5
commit 2d07bcd1ed
15 changed files with 647 additions and 374 deletions
+99 -44
View File
@@ -6,15 +6,15 @@ use std::sync::Arc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
Render, SharedString, Styled as _, Subscription, Window, div, px, ParentElement as _, Render, SharedString, Styled as _, Subscription, Window, div, 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::{PanelRow, PanelStack, PanelView}; use ui::layout::panel::{PanelRow, 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::{Tabs, TabsVariant}; use ui::tabs::{Tabs, TabsVariant};
@@ -31,10 +31,14 @@ use crate::titlebar::{
}; };
pub struct AppRoot { pub struct AppRoot {
panel: Entity<PanelStack>, /// The id of the main panel currently shown.
main: Option<SharedString>,
/// The open main panels in tab order.
mains: Vec<(SharedString, Arc<dyn PanelView>)>,
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>,
} }
@@ -44,11 +48,10 @@ impl AppRoot {
bind_repository_shortcuts(cx); bind_repository_shortcuts(cx);
let app = cx.entity().downgrade(); let app = cx.entity().downgrade();
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);
@@ -67,12 +70,11 @@ 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| { log_dropped(app.update(cx, |this, cx| this.clear(cx)));
this.clear(cx);
}));
if signed_in { if signed_in {
ExploreView::open(&app, window, cx); ExploreView::open(&app, window, cx);
} }
@@ -94,10 +96,12 @@ impl AppRoot {
}); });
Self { Self {
panel, main: None,
mains: Vec::new(),
titlebar, titlebar,
sign_in, sign_in,
explore, explore,
empty,
passphrase: None, passphrase: None,
_subscriptions: subscriptions, _subscriptions: subscriptions,
} }
@@ -112,79 +116,127 @@ impl AppRoot {
cx.open_dialog(dialog); cx.open_dialog(dialog);
} }
/// The panel stack holding the main tile and the detail tiles. pub fn active_main(&self) -> Option<Arc<dyn PanelView>> {
pub fn panel(&self) -> Entity<PanelStack> { let id = self.main.as_ref()?;
self.panel.clone() self.mains
.iter()
.find(|(open, _)| open == id)
.map(|(_, view)| view.clone())
} }
pub fn open_main( pub fn has_main(&self, id: &SharedString) -> bool {
self.mains.iter().any(|(open, _)| open == id)
}
/// Whether the active main panel owns an open sub panel with this id.
pub(crate) fn has_detail(&self, id: &SharedString, cx: &App) -> bool {
self.active_main()
.is_some_and(|main| main.sub_panels(cx).iter().any(|(open, _)| open == 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>,
) { ) {
self.panel match self.mains.iter_mut().find(|(open, _)| *open == id) {
.update(cx, |panel, cx| panel.open_main(id, view, cx)); Some((_, open_view)) => *open_view = view,
None => self.mains.push((id.clone(), view)),
}
self.main = Some(id);
cx.notify();
} }
pub fn activate_main(&mut self, id: &SharedString, cx: &mut Context<Self>) {
self.main = Some(id.clone());
cx.notify();
}
/// Opens the panel as a sub panel of the active main panel.
pub fn open_detail( pub fn open_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>,
) { ) {
self.panel let Some(active) = self.active_main() else {
.update(cx, |panel, cx| panel.open_split(id, view, cx)); log::warn!("no main panel open for detail {id}");
return;
};
let panel_id = id.clone();
if !active.open_sub(id, view, cx) {
log::warn!("active panel ignored sub panel {panel_id}");
}
} }
/// Closes the active main panel's sub panel with `id`.
pub fn close_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) { pub fn close_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) {
self.panel.update(cx, |panel, cx| panel.close_split(id, cx)); if let Some(active) = self.active_main() {
active.close_sub(id, 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>) {
self.panel let Some((id, _)) = self.mains.get(index) else {
.update(cx, |panel, cx| panel.close_main_at(index, cx)); return;
};
let id = id.clone();
self.mains.remove(index);
if self.main.as_ref() == Some(&id) {
self.main = self
.mains
.get(index)
.or_else(|| index.checked_sub(1).and_then(|prev| self.mains.get(prev)))
.map(|(id, _)| id.clone());
}
cx.notify();
} }
pub fn clear(&mut self, cx: &mut Context<Self>) { pub fn clear(&mut self, cx: &mut Context<Self>) {
self.panel.update(cx, |panel, cx| panel.clear(cx)); self.main = None;
self.mains.clear();
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 panel = self.panel.read(cx); if self.mains.is_empty() {
if panel.mains().is_empty() {
return None; return None;
} }
let selected = panel.active_main_index(); let tabs: Vec<_> = self
let ids: Vec<SharedString> = panel .mains
.mains()
.iter() .iter()
.map(|panel| panel.id().clone()) .map(|(id, view)| (id.clone(), view.clone()))
.collect(); .collect();
let panel = self.panel.clone();
let selected = self
.main
.as_ref()
.and_then(|id| self.mains.iter().position(|(open, _)| open == 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: Vec<SharedString> = self.mains.iter().map(|(id, _)| id.clone()).collect();
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| panel.read(cx).main_tabs(cx)) .tabs(move |_, cx| {
tabs.iter()
.map(|(id, view)| view.tab(id.clone().into(), cx).closeable(true))
.collect()
})
.on_change(move |index, _, cx| { .on_change(move |index, _, cx| {
let Some(id) = ids.get(index) else { let Some(id) = open.get(index).cloned() 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);
})); }));
@@ -205,6 +257,8 @@ 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();
let has_main = main.is_some();
div() div()
.relative() .relative()
@@ -242,14 +296,15 @@ impl Render for AppRoot {
titlebar.suffix(menu) titlebar.suffix(menu)
}), }),
) )
.child(if signed_in { .child(
self.panel.clone().into_any_element() PanelRow::new("signed-panel")
} else { .when_some(main, |row, main| row.main(main))
PanelRow::new("signed-out-panel") .when(!has_main && signed_in, |row| row.main(self.empty.clone()))
.main(self.sign_in.clone()) .when(!has_main && !signed_in, |row| {
row.main(self.sign_in.clone())
.split_at(self.explore.clone(), px(300.)) .split_at(self.explore.clone(), px(300.))
.into_any_element()
}), }),
),
) )
} }
} }
+33 -1
View File
@@ -1,5 +1,7 @@
mod helpers; mod helpers;
use std::sync::Arc;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ListAlignment, ListState, AnyElement, App, AppContext as _, Context, Entity, IntoElement, ListAlignment, ListState,
ParentElement as _, Render, SharedString, Styled as _, Subscription, WeakEntity, Window, div, ParentElement as _, Render, SharedString, Styled as _, Subscription, WeakEntity, Window, div,
@@ -13,7 +15,7 @@ use ui::common::{h_flex, v_flex};
use ui::empty_state::EmptyState; use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent}; use ui::input::{Input, InputState, InputStateEvent};
use ui::layout::panel::Panel; use ui::layout::panel::{Panel, PanelView, SubPanels};
use ui::scrollbar::Scrollbar; use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption}; use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
@@ -35,6 +37,8 @@ pub struct ExploreView {
search: Entity<InputState>, search: Entity<InputState>,
/// Profiles for the card owners. /// Profiles for the card owners.
directory: Entity<ProfileDirectory>, directory: Entity<ProfileDirectory>,
/// The detail panels this panel owns, shown beside its content.
subs: SubPanels,
_search_subscription: Subscription, _search_subscription: Subscription,
_store_subscription: Subscription, _store_subscription: Subscription,
} }
@@ -88,6 +92,7 @@ impl ExploreView {
visible: Vec::new(), visible: Vec::new(),
search, search,
directory, directory,
subs: SubPanels::default(),
_search_subscription: search_subscription, _search_subscription: search_subscription,
_store_subscription: store_subscription, _store_subscription: store_subscription,
} }
@@ -181,6 +186,33 @@ impl Panel for ExploreView {
SharedString::from("Explore") SharedString::from("Explore")
} }
fn sub_panels(&self, _cx: &App) -> &SubPanels {
&self.subs
}
fn open_sub_panel(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut Context<Self>,
) -> bool {
if self.subs.open(id, view) {
cx.notify();
true
} else {
false
}
}
fn close_sub_panel(&mut self, id: &SharedString, cx: &mut Context<Self>) -> bool {
if self.subs.close(id) {
cx.notify();
true
} else {
false
}
}
fn prefix(&self, cx: &App) -> Option<AnyElement> { fn prefix(&self, cx: &App) -> Option<AnyElement> {
Some( Some(
Icon::named(IconRole::Grid) Icon::named(IconRole::Grid)
+23 -2
View File
@@ -1,6 +1,6 @@
use gpui::{ use gpui::{
App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render,
ScrollHandle, SharedString, Styled as _, Subscription, Window, div, ScrollHandle, SharedString, Styled as _, Subscription, WeakEntity, Window, div,
}; };
use metadata::ProfileDirectory; use metadata::ProfileDirectory;
use nostr::prelude::EventId; use nostr::prelude::EventId;
@@ -16,11 +16,16 @@ use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use utils::relative_time; use utils::relative_time;
use crate::app::AppRoot;
use crate::issues::helpers::{comment_form, comments_section, sidebar_section}; use crate::issues::helpers::{comment_form, comments_section, sidebar_section};
use crate::shared::log_dropped; use crate::shared::log_dropped;
use crate::shared::panels;
use crate::shared::widgets::status_badge; use crate::shared::widgets::status_badge;
pub struct IssueDetailView { pub struct IssueDetailView {
workspace: WeakEntity<AppRoot>,
/// The sub panel id this view closes through.
panel_id: SharedString,
store: Entity<RepoStore>, store: Entity<RepoStore>,
issue_id: EventId, issue_id: EventId,
comment_input: Entity<InputState>, comment_input: Entity<InputState>,
@@ -31,7 +36,13 @@ pub struct IssueDetailView {
} }
impl IssueDetailView { impl IssueDetailView {
pub fn new(store: Entity<RepoStore>, issue_id: EventId, cx: &mut Context<Self>) -> Self { pub fn new(
workspace: WeakEntity<AppRoot>,
panel_id: SharedString,
store: Entity<RepoStore>,
issue_id: EventId,
cx: &mut Context<Self>,
) -> Self {
let comment_input = InputState::builder().multiline().build(cx); let comment_input = InputState::builder().multiline().build(cx);
let subscription = cx.observe(&store, |this, _store, cx| { let subscription = cx.observe(&store, |this, _store, cx| {
@@ -46,6 +57,8 @@ impl IssueDetailView {
}); });
Self { Self {
workspace,
panel_id,
store, store,
issue_id, issue_id,
comment_input, comment_input,
@@ -125,7 +138,15 @@ impl Render for IssueDetailView {
h_flex() h_flex()
.id("issue-detail") .id("issue-detail")
.relative()
.size_full() .size_full()
.child(
div()
.absolute()
.top_1()
.right_1()
.child(panels::close_button(&self.workspace, &self.panel_id)),
)
.child( .child(
ScrollArea::new("issue-detail-scroll") ScrollArea::new("issue-detail-scroll")
.handle(self.scroll_handle.clone()) .handle(self.scroll_handle.clone())
+11 -1
View File
@@ -196,12 +196,22 @@ impl Render for IssuesView {
let store = store.clone(); let store = store.clone();
Rc::new(move |_, window, cx| { Rc::new(move |_, window, cx| {
let id = SharedString::from(format!("issue:{issue_id}")); let id = SharedString::from(format!("issue:{issue_id}"));
let panel_id = id.clone();
let workspace_for_build = workspace.clone();
let store = store.clone(); let store = store.clone();
panels::open_detail( panels::open_detail(
&workspace, &workspace,
id, id,
move |_, cx| { move |_, cx| {
cx.new(|cx| IssueDetailView::new(store.clone(), issue_id, cx)) cx.new(|cx| {
IssueDetailView::new(
workspace_for_build.clone(),
panel_id.clone(),
store.clone(),
issue_id,
cx,
)
})
}, },
window, window,
cx, cx,
+24 -2
View File
@@ -32,7 +32,7 @@ use crate::issues::helpers::{comment_form, comments_section, sidebar_section};
use crate::repo::commit_diff::{CommitDiffView, DiffPane}; use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::shared::event_list::commit_list; use crate::shared::event_list::commit_list;
use crate::shared::log_dropped; use crate::shared::log_dropped;
use crate::shared::panels::open_detail; use crate::shared::panels::{self, open_detail};
use crate::shared::widgets::status_badge; use crate::shared::widgets::status_badge;
const NOT_FOUND: &str = "Pull request not found"; const NOT_FOUND: &str = "Pull request not found";
@@ -50,6 +50,8 @@ struct PrBinding {
pub struct PullRequestDetailView { pub struct PullRequestDetailView {
workspace: WeakEntity<AppRoot>, workspace: WeakEntity<AppRoot>,
/// The sub panel id this view closes through.
panel_id: SharedString,
store: Entity<RepoStore>, store: Entity<RepoStore>,
pr_id: EventId, pr_id: EventId,
update_dialog: Option<Entity<dialogs::update::UpdatePrDialog>>, update_dialog: Option<Entity<dialogs::update::UpdatePrDialog>>,
@@ -73,6 +75,7 @@ pub struct PullRequestDetailView {
impl PullRequestDetailView { impl PullRequestDetailView {
pub fn new( pub fn new(
workspace: WeakEntity<AppRoot>, workspace: WeakEntity<AppRoot>,
panel_id: SharedString,
store: Entity<RepoStore>, store: Entity<RepoStore>,
pr_id: EventId, pr_id: EventId,
_window: &mut Window, _window: &mut Window,
@@ -92,6 +95,7 @@ impl PullRequestDetailView {
Self { Self {
workspace, workspace,
panel_id,
store, store,
pr_id, pr_id,
update_dialog: None, update_dialog: None,
@@ -304,13 +308,23 @@ impl PullRequestDetailView {
None => SharedString::from(format!("commit:{}:{commit_id}", worktree.display())), None => SharedString::from(format!("commit:{}:{commit_id}", worktree.display())),
}; };
let workspace = self.workspace.clone(); let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
let panel_id = id.clone();
let commit_id = commit_id.to_owned(); let commit_id = commit_id.to_owned();
open_detail( open_detail(
&workspace, &workspace,
id, id,
move |window, cx| { move |window, cx| {
cx.new(|cx| { cx.new(|cx| {
CommitDiffView::new(worktree.clone(), commit_id.clone(), false, window, cx) CommitDiffView::new(
workspace_for_build.clone(),
panel_id.clone(),
worktree.clone(),
commit_id.clone(),
false,
window,
cx,
)
}) })
}, },
window, window,
@@ -589,8 +603,16 @@ impl Render for PullRequestDetailView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex() v_flex()
.id("pull-request-detail") .id("pull-request-detail")
.relative()
.size_full() .size_full()
.min_h_0() .min_h_0()
.child(
div()
.absolute()
.top_1()
.right_1()
.child(panels::close_button(&self.workspace, &self.panel_id)),
)
.child(self.render_header(cx)) .child(self.render_header(cx))
.when_some(self.update_dialog.clone(), |el, view| el.child(view)) .when_some(self.update_dialog.clone(), |el, view| el.child(view))
.child(self.render_tabs(cx)) .child(self.render_tabs(cx))
@@ -309,6 +309,7 @@ impl Render for PullRequestsView {
let store = store.clone(); let store = store.clone();
Rc::new(move |_, window, cx| { Rc::new(move |_, window, cx| {
let id = SharedString::from(format!("pr:{pr_id}")); let id = SharedString::from(format!("pr:{pr_id}"));
let panel_id = id.clone();
let workspace_for_build = workspace.clone(); let workspace_for_build = workspace.clone();
let store = store.clone(); let store = store.clone();
open_detail( open_detail(
@@ -318,6 +319,7 @@ impl Render for PullRequestsView {
cx.new(|cx| { cx.new(|cx| {
PullRequestDetailView::new( PullRequestDetailView::new(
workspace_for_build.clone(), workspace_for_build.clone(),
panel_id.clone(),
store.clone(), store.clone(),
pr_id, pr_id,
window, window,
+20 -2
View File
@@ -28,7 +28,7 @@ use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::repo::helpers::announcement_display_name; use crate::repo::helpers::announcement_display_name;
use crate::shared::event_list::commit_list; use crate::shared::event_list::commit_list;
use crate::shared::log_dropped; use crate::shared::log_dropped;
use crate::shared::panels::open_detail; use crate::shared::panels::{self, open_detail};
use crate::shared::progress::error_row; use crate::shared::progress::error_row;
pub struct NewPullRequestView { pub struct NewPullRequestView {
@@ -232,13 +232,23 @@ impl NewPullRequestView {
None => SharedString::from(format!("commit:{}:{commit_id}", repo_path.display())), None => SharedString::from(format!("commit:{}:{commit_id}", repo_path.display())),
}; };
let workspace = self.workspace.clone(); let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
let panel_id = id.clone();
let commit_id = commit_id.to_owned(); let commit_id = commit_id.to_owned();
open_detail( open_detail(
&workspace, &workspace,
id, id,
move |window, cx| { move |window, cx| {
cx.new(|cx| { cx.new(|cx| {
CommitDiffView::new(repo_path.clone(), commit_id.clone(), false, window, cx) CommitDiffView::new(
workspace_for_build.clone(),
panel_id.clone(),
repo_path.clone(),
commit_id.clone(),
false,
window,
cx,
)
}) })
}, },
window, window,
@@ -806,7 +816,15 @@ impl Render for NewPullRequestView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex() v_flex()
.id("new-pr") .id("new-pr")
.relative()
.size_full() .size_full()
.child(
div()
.absolute()
.top_1()
.right_1()
.child(panels::close_button(&self.workspace, &self.panel_id)),
)
.child( .child(
v_flex() v_flex()
.gap_3() .gap_3()
@@ -13,6 +13,7 @@ use ui::theme::ActiveTheme as _;
use crate::app::AppRoot; use crate::app::AppRoot;
use crate::shared::log_dropped; use crate::shared::log_dropped;
use crate::shared::panels;
use crate::shared::progress::error_row; use crate::shared::progress::error_row;
pub struct SendPatchView { pub struct SendPatchView {
@@ -144,7 +145,15 @@ impl Render for SendPatchView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex() v_flex()
.id("send-patch") .id("send-patch")
.relative()
.size_full() .size_full()
.child(
div()
.absolute()
.top_1()
.right_1()
.child(panels::close_button(&self.workspace, &self.panel_id)),
)
.child( .child(
v_flex() v_flex()
.p_4() .p_4()
+11 -1
View File
@@ -53,13 +53,21 @@ pub fn open_repo_item(
match item { match item {
RepoItem::Issue(issue_id) => { RepoItem::Issue(issue_id) => {
let id = SharedString::from(format!("issue:{issue_id}")); let id = SharedString::from(format!("issue:{issue_id}"));
let panel_id = id.clone();
let workspace_for_build = workspace.clone();
let store = store.clone(); let store = store.clone();
panels::open_detail( panels::open_detail(
workspace, workspace,
id, id,
move |_, cx| { move |_, cx| {
cx.new(|cx| { cx.new(|cx| {
crate::issues::detail::IssueDetailView::new(store.clone(), issue_id, cx) crate::issues::detail::IssueDetailView::new(
workspace_for_build.clone(),
panel_id.clone(),
store.clone(),
issue_id,
cx,
)
}) })
}, },
window, window,
@@ -68,6 +76,7 @@ pub fn open_repo_item(
} }
RepoItem::PullRequest(pr_id) => { RepoItem::PullRequest(pr_id) => {
let id = SharedString::from(format!("pr:{pr_id}")); let id = SharedString::from(format!("pr:{pr_id}"));
let panel_id = id.clone();
let workspace_for_build = workspace.clone(); let workspace_for_build = workspace.clone();
let store = store.clone(); let store = store.clone();
panels::open_detail( panels::open_detail(
@@ -77,6 +86,7 @@ pub fn open_repo_item(
cx.new(|cx| { cx.new(|cx| {
crate::pull_requests::PullRequestDetailView::new( crate::pull_requests::PullRequestDetailView::new(
workspace_for_build.clone(), workspace_for_build.clone(),
panel_id.clone(),
store.clone(), store.clone(),
pr_id, pr_id,
window, window,
+17
View File
@@ -29,6 +29,8 @@ use ui::tree::{Tree, TreeItem, TreeItemSeed};
use utils::relative_time_secs; use utils::relative_time_secs;
use super::helpers::{DiffRow, co_authors, diff_rows, short_id}; use super::helpers::{DiffRow, co_authors, diff_rows, short_id};
use crate::app::AppRoot;
use crate::shared::panels;
/// Emitted when the user activates the Download commit button. /// Emitted when the user activates the Download commit button.
pub enum DiffPaneEvent { pub enum DiffPaneEvent {
@@ -607,6 +609,9 @@ impl Render for DiffPane {
} }
pub struct CommitDiffView { pub struct CommitDiffView {
workspace: WeakEntity<AppRoot>,
/// The sub panel id this view closes through.
panel_id: SharedString,
worktree: PathBuf, worktree: PathBuf,
commit: FileCommit, commit: FileCommit,
/// The diff is being computed on a background task. /// The diff is being computed on a background task.
@@ -619,6 +624,8 @@ pub struct CommitDiffView {
impl CommitDiffView { impl CommitDiffView {
pub fn new( pub fn new(
workspace: WeakEntity<AppRoot>,
panel_id: SharedString,
worktree: PathBuf, worktree: PathBuf,
commit_id: String, commit_id: String,
downloadable: bool, downloadable: bool,
@@ -642,6 +649,8 @@ impl CommitDiffView {
}); });
Self { Self {
workspace,
panel_id,
worktree, worktree,
commit: FileCommit { commit: FileCommit {
id: commit_id, id: commit_id,
@@ -895,8 +904,16 @@ impl Render for CommitDiffView {
}; };
v_flex() v_flex()
.relative()
.size_full() .size_full()
.min_h_0() .min_h_0()
.child(
div()
.absolute()
.top_1()
.right_1()
.child(panels::close_button(&self.workspace, &self.panel_id)),
)
.child(self.render_header(cx)) .child(self.render_header(cx))
.child(div().flex_1().min_h_0().child(body)) .child(div().flex_1().min_h_0().child(body))
} }
+11 -1
View File
@@ -142,13 +142,23 @@ impl RepoHistoryView {
None => SharedString::from(format!("commit:{}:{}", worktree.display(), commit_id)), None => SharedString::from(format!("commit:{}:{}", worktree.display(), commit_id)),
}; };
let workspace = self.workspace.clone(); let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
let panel_id = id.clone();
panels::open_detail( panels::open_detail(
&workspace, &workspace,
id, id,
move |window, cx| { move |window, cx| {
cx.new(|cx| { cx.new(|cx| {
CommitDiffView::new(worktree.clone(), commit_id.clone(), true, window, cx) CommitDiffView::new(
workspace_for_build.clone(),
panel_id.clone(),
worktree.clone(),
commit_id.clone(),
true,
window,
cx,
)
}) })
}, },
window, window,
+32 -1
View File
@@ -1,5 +1,6 @@
use std::collections::HashSet; use std::collections::HashSet;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::Error; use anyhow::Error;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
@@ -25,7 +26,7 @@ use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::dialog::Dialog; use ui::dialog::Dialog;
use ui::dropdown_menu::DropdownMenu; use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel; use ui::layout::panel::{Panel, PanelView, SubPanels};
use ui::menu::MenuItem; use ui::menu::MenuItem;
use ui::popover::Popover; use ui::popover::Popover;
use ui::sidebar::{Sidebar, SidebarEntry}; use ui::sidebar::{Sidebar, SidebarEntry};
@@ -107,6 +108,8 @@ pub struct RepoDetailView {
sync_error: Option<SharedString>, sync_error: Option<SharedString>,
pub(super) repo_menu_open: bool, pub(super) repo_menu_open: bool,
pub(super) clone_open: bool, pub(super) clone_open: bool,
/// The detail panels this repo panel owns, shown beside its content.
subs: SubPanels,
_subscriptions: Vec<Subscription>, _subscriptions: Vec<Subscription>,
} }
@@ -231,6 +234,7 @@ impl RepoDetailView {
sync_error: None, sync_error: None,
repo_menu_open: false, repo_menu_open: false,
clone_open: false, clone_open: false,
subs: SubPanels::default(),
_subscriptions: subscriptions, _subscriptions: subscriptions,
} }
} }
@@ -1479,6 +1483,33 @@ impl Panel for RepoDetailView {
SharedString::from("Repository") SharedString::from("Repository")
} }
fn sub_panels(&self, _cx: &App) -> &SubPanels {
&self.subs
}
fn open_sub_panel(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut Context<Self>,
) -> bool {
if self.subs.open(id, view) {
cx.notify();
true
} else {
false
}
}
fn close_sub_panel(&mut self, id: &SharedString, cx: &mut Context<Self>) -> bool {
if self.subs.close(id) {
cx.notify();
true
} else {
false
}
}
fn prefix(&self, cx: &App) -> Option<AnyElement> { fn prefix(&self, cx: &App) -> Option<AnyElement> {
let store = self.store.read(cx); let store = self.store.read(cx);
+28 -6
View File
@@ -1,11 +1,14 @@
use std::sync::Arc; use std::sync::Arc;
use gpui::{App, Entity, SharedString, WeakEntity, Window}; use gpui::{App, ElementId, Entity, SharedString, WeakEntity, Window};
use ui::button::{Button, ButtonVariant};
use ui::common::Sizable as _;
use ui::icons::Icon;
use ui::layout::panel::{Panel, PanelView}; use ui::layout::panel::{Panel, PanelView};
use crate::app::AppRoot; use crate::app::AppRoot;
/// Opens a repository in the main panel, reusing its tab when it is already open. /// Opens a panel in the main panel, reusing it when it is already open.
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>,
@@ -17,8 +20,9 @@ pub fn open_primary<P, F>(
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static, F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{ {
let id = id.into(); let id = id.into();
if workspace if workspace
.read_with(cx, |app, cx| app.panel().read(cx).has(&id)) .read_with(cx, |app, _| app.has_main(&id))
.unwrap_or(false) .unwrap_or(false)
{ {
if let Err(error) = workspace.update(cx, |app, cx| app.activate_main(&id, cx)) { if let Err(error) = workspace.update(cx, |app, cx| app.activate_main(&id, cx)) {
@@ -28,12 +32,13 @@ pub fn open_primary<P, F>(
} }
let view: Arc<dyn PanelView> = Arc::new(build(window, cx)); 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)) { if let Err(error) = workspace.update(cx, |app, cx| app.show_main(id.clone(), view, cx)) {
log::warn!("failed to open panel {id}: {error}"); log::warn!("failed to open panel {id}: {error}");
} }
} }
/// Opens a detail tile beside the main panel, reusing it when it is already open. /// Opens the panel as a sub panel of the active main panel, reusing the tile
/// that 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>,
@@ -45,8 +50,9 @@ pub fn open_detail<P, F>(
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static, F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{ {
let id = id.into(); let id = id.into();
if workspace if workspace
.read_with(cx, |app, cx| app.panel().read(cx).has(&id)) .read_with(cx, |app, cx| app.has_detail(&id, cx))
.unwrap_or(false) .unwrap_or(false)
{ {
return; return;
@@ -57,3 +63,19 @@ pub fn open_detail<P, F>(
log::warn!("failed to open panel {id}: {error}"); log::warn!("failed to open panel {id}: {error}");
} }
} }
/// The corner button a sub panel renders to close itself.
pub fn close_button(workspace: &WeakEntity<AppRoot>, panel_id: &SharedString) -> Button {
let workspace = workspace.clone();
let panel_id = panel_id.clone();
Button::new((ElementId::from("close-sub-panel"), panel_id.clone()))
.icon(Icon::named(ui::icons::IconRole::Close))
.variant(ButtonVariant::Ghost)
.xsmall()
.on_click(move |_, _, cx| {
let panel_id = panel_id.clone();
if let Err(error) = workspace.update(cx, |app, cx| app.close_detail(&panel_id, cx)) {
log::warn!("failed to close panel {panel_id}: {error}");
}
})
}
+213 -310
View File
@@ -3,26 +3,72 @@
//! 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, Context, Div, ElementId, Entity, IntoElement, AnyElement, AnyView, App, Axis, Context, Div, ElementId, Entity, IntoElement,
ParentElement as _, Pixels, Render, RenderOnce, SharedString, StyleRefinement, Styled as _, ParentElement as _, Pixels, Render, RenderOnce, SharedString, StyleRefinement, Styled as _,
WeakEntity, Window, div, Window, div, px,
}; };
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};
/// The sub panels a panel owns and shows beside its content.
#[derive(Default)]
pub struct SubPanels {
panels: Vec<(SharedString, Arc<dyn PanelView>)>,
}
impl SubPanels {
pub fn is_empty(&self) -> bool {
self.panels.is_empty()
}
pub fn len(&self) -> usize {
self.panels.len()
}
pub fn get(&self, id: &SharedString) -> Option<&Arc<dyn PanelView>> {
self.panels
.iter()
.find(|(open, _)| open == id)
.map(|(_, view)| view)
}
pub fn has(&self, id: &SharedString) -> bool {
self.get(id).is_some()
}
/// Adds the sub panel; returns false when `id` is already open.
pub fn open(&mut self, id: impl Into<SharedString>, view: Arc<dyn PanelView>) -> bool {
let id = id.into();
if self.has(&id) {
return false;
}
self.panels.push((id, view));
true
}
/// Removes the sub panel; returns whether it was open.
pub fn close(&mut self, id: &SharedString) -> bool {
match self.panels.iter().position(|(open, _)| open == id) {
Some(index) => {
self.panels.remove(index);
true
}
None => false,
}
}
pub fn iter(&self) -> impl Iterator<Item = (&SharedString, &Arc<dyn PanelView>)> {
self.panels.iter().map(|(id, view)| (id, view))
}
}
/// A user-defined panel the row can show. /// A user-defined panel the row can show.
#[allow(unused_variables)] #[allow(unused_variables)]
pub trait Panel: Render + 'static { pub trait Panel: Render + 'static {
@@ -43,6 +89,27 @@ pub trait Panel: Render + 'static {
fn loading(&self, cx: &App) -> bool { fn loading(&self, cx: &App) -> bool {
false false
} }
/// The sub panels this panel owns, shown beside its content.
fn sub_panels(&self, _cx: &App) -> &SubPanels {
const EMPTY: &SubPanels = &SubPanels { panels: Vec::new() };
EMPTY
}
/// Opens a sub panel this panel owns; returns false when the panel owns none.
fn open_sub_panel(
&mut self,
_id: SharedString,
_view: Arc<dyn PanelView>,
_cx: &mut Context<Self>,
) -> bool {
false
}
/// Closes the owned sub panel with `id`; returns whether it was open.
fn close_sub_panel(&mut self, _id: &SharedString, _cx: &mut Context<Self>) -> bool {
false
}
} }
/// An object-safe handle to a panel, so apps can hold panels by kind. /// An object-safe handle to a panel, so apps can hold panels by kind.
@@ -69,6 +136,15 @@ pub trait PanelView: 'static {
false false
} }
/// The sub panels this panel owns, cloned so callers can render beside it.
fn sub_panels(&self, cx: &App) -> Vec<(SharedString, Arc<dyn PanelView>)>;
/// Opens the panel as a sub panel of this panel; returns whether it was accepted.
fn open_sub(&self, id: SharedString, view: Arc<dyn PanelView>, cx: &mut App) -> bool;
/// Closes this panel's sub panel with `id`; returns whether it was open.
fn close_sub(&self, id: &SharedString, cx: &mut App) -> bool;
/// Builds the panel's tab from its title, prefix, and loading state. /// Builds the panel's tab from its title, prefix, and loading state.
fn tab(&self, key: ElementId, cx: &App) -> Tab { fn tab(&self, key: ElementId, cx: &App) -> Tab {
let mut tab = Tab::new(key, self.title(cx)).busy(self.loading(cx)); let mut tab = Tab::new(key, self.title(cx)).busy(self.loading(cx));
@@ -99,6 +175,22 @@ impl<T: Panel> PanelView for Entity<T> {
fn loading(&self, cx: &App) -> bool { fn loading(&self, cx: &App) -> bool {
self.read(cx).loading(cx) self.read(cx).loading(cx)
} }
fn sub_panels(&self, cx: &App) -> Vec<(SharedString, Arc<dyn PanelView>)> {
self.read(cx)
.sub_panels(cx)
.iter()
.map(|(id, view)| (id.clone(), view.clone()))
.collect()
}
fn open_sub(&self, id: SharedString, view: Arc<dyn PanelView>, cx: &mut App) -> bool {
self.update(cx, |panel, cx| T::open_sub_panel(panel, id, view, cx))
}
fn close_sub(&self, id: &SharedString, cx: &mut App) -> bool {
self.update(cx, |panel, cx| T::close_sub_panel(panel, id, cx))
}
} }
impl<P: PanelView + ?Sized> PanelView for Arc<P> { impl<P: PanelView + ?Sized> PanelView for Arc<P> {
@@ -121,6 +213,18 @@ impl<P: PanelView + ?Sized> PanelView for Arc<P> {
fn loading(&self, cx: &App) -> bool { fn loading(&self, cx: &App) -> bool {
(**self).loading(cx) (**self).loading(cx)
} }
fn sub_panels(&self, cx: &App) -> Vec<(SharedString, Arc<dyn PanelView>)> {
(**self).sub_panels(cx)
}
fn open_sub(&self, id: SharedString, view: Arc<dyn PanelView>, cx: &mut App) -> bool {
(**self).open_sub(id, view, cx)
}
fn close_sub(&self, id: &SharedString, cx: &mut App) -> bool {
(**self).close_sub(id, cx)
}
} }
/// The panel row drawn under the titlebar. /// The panel row drawn under the titlebar.
@@ -128,8 +232,8 @@ impl<P: PanelView + ?Sized> PanelView for Arc<P> {
#[must_use] #[must_use]
pub struct PanelRow { pub struct PanelRow {
id: ElementId, id: ElementId,
main: Option<AnyElement>, main: Option<Arc<dyn PanelView>>,
split: Option<AnyElement>, split: Option<Arc<dyn PanelView>>,
/// The main pane's width when split; `None` splits the row in half. /// The main pane's width when split; `None` splits the row in half.
split_width: Option<Pixels>, split_width: Option<Pixels>,
resizable: bool, resizable: bool,
@@ -155,6 +259,61 @@ fn island(panel: Div, cx: &App) -> Div {
.overflow_hidden() .overflow_hidden()
} }
/// Renders a panel's island plus, beside it, the sub panels it owns.
fn panel_tile(
panel: &Arc<dyn PanelView>,
id: ElementId,
extent: Pixels,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let subs = panel.sub_panels(cx);
let content = island(
div()
.size_full()
.child(panel.view().cached(content_style())),
cx,
);
if subs.is_empty() {
return content.into_any_element();
}
let count = subs.len();
let gutter = RESIZE_HANDLE_WIDTH;
let content_width = ((extent - gutter * count as f32) / 2.0).max(PANE_MIN_SIZE);
let sub_width = (content_width / count as f32).max(PANE_MIN_SIZE);
let sizes = window.with_element_namespace(id.clone(), |window| {
window
.use_keyed_state("panel-sizes", cx, |_, _| ResizableState::default())
.clone()
});
// The last pane is the flexible remainder; the others hold fixed widths.
if sizes.read(cx).sizes().is_empty() {
sizes.update(cx, |state, cx| {
state.set_pane_width(0, content_width, cx);
for index in 1..count {
state.set_pane_width(index, sub_width, cx);
}
});
}
let mut split = Resizable::new((id.clone(), "subs"), sizes)
.axis(Axis::Horizontal)
.pane(content)
.h_full();
for (index, (_, view)) in subs.iter().enumerate() {
let tile_id = (id.clone(), index.to_string()).into();
split = split.pane(panel_tile(view, tile_id, sub_width, window, cx));
}
div().w_full().h_full().child(split).into_any_element()
}
impl PanelRow { impl PanelRow {
/// Creates the panel row. /// Creates the panel row.
pub fn new<I>(id: I) -> Self pub fn new<I>(id: I) -> Self
@@ -176,7 +335,7 @@ impl PanelRow {
where where
P: PanelView, P: PanelView,
{ {
self.main = Some(main.view().cached(content_style()).into_any_element()); self.main = Some(Arc::new(main));
self self
} }
@@ -185,7 +344,7 @@ impl PanelRow {
where where
P: PanelView, P: PanelView,
{ {
self.split = Some(panel.view().cached(content_style()).into_any_element()); self.split = Some(Arc::new(panel));
self self
} }
@@ -195,7 +354,7 @@ impl PanelRow {
P: PanelView, P: PanelView,
{ {
self.split_width = Some(width); self.split_width = Some(width);
self.split = Some(panel.view().cached(content_style()).into_any_element()); self.split = Some(Arc::new(panel));
self self
} }
@@ -214,35 +373,49 @@ impl gpui::Styled for PanelRow {
impl RenderOnce for PanelRow { impl RenderOnce for PanelRow {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone(); let Self {
id,
main,
split,
split_width,
resizable,
style,
} = self;
let gutter = RESIZE_HANDLE_WIDTH; let gutter = RESIZE_HANDLE_WIDTH;
// The row's inner width: the viewport minus its own p_2 padding.
let extent = window.viewport_size().width - px(16.0);
let main = island( let row = match split {
div() Some(split) => {
.size_full() let main_width = split_width
.child(self.main.unwrap_or_else(|| div().into_any_element())), .unwrap_or((extent - gutter) / 2.0)
.max(PANE_MIN_SIZE);
let split_extent = (extent - main_width - gutter).max(PANE_MIN_SIZE);
let main_tile = match main.as_ref() {
Some(main) => {
panel_tile(main, (id.clone(), "main").into(), main_width, window, cx)
}
None => island(div().size_full(), cx).into_any_element(),
};
let split_tile = panel_tile(
&split,
(id.clone(), "split").into(),
split_extent,
window,
cx, cx,
); );
let row = match self.split { if !resizable {
Some(split) => {
let split = island(div().size_full().child(split), cx);
let extent = window.viewport_size().width - gutter * 2.0;
let main_width = self
.split_width
.unwrap_or((extent - gutter) / 2.0)
.max(PANE_MIN_SIZE);
if !self.resizable {
div() div()
.w_full() .w_full()
.h_full() .h_full()
.flex() .flex()
.flex_row() .flex_row()
.child(div().flex_none().w(main_width).h_full().child(main)) .child(div().flex_none().w(main_width).h_full().child(main_tile))
.child(div().flex_none().w(gutter)) .child(div().flex_none().w(gutter))
.child(div().flex_1().min_w_0().h_full().child(split)) .child(div().flex_1().min_w_0().h_full().child(split_tile))
} else { } else {
let sizes = window.with_element_namespace(id.clone(), |window| { let sizes = window.with_element_namespace(id.clone(), |window| {
window window
@@ -257,13 +430,19 @@ impl RenderOnce for PanelRow {
div().w_full().h_full().child( div().w_full().h_full().child(
Resizable::new((id.clone(), "split"), sizes) Resizable::new((id.clone(), "split"), sizes)
.axis(Axis::Horizontal) .axis(Axis::Horizontal)
.pane(main) .pane(main_tile)
.pane(split) .pane(split_tile)
.h_full(), .h_full(),
) )
} }
} }
None => div().w_full().h_full().child(main), None => {
let main_tile = match main.as_ref() {
Some(main) => panel_tile(main, (id.clone(), "main").into(), extent, window, cx),
None => island(div().size_full(), cx).into_any_element(),
};
div().w_full().h_full().child(main_tile)
}
}; };
div() div()
@@ -272,283 +451,7 @@ impl RenderOnce for PanelRow {
.h_full() .h_full()
.p_2() .p_2()
.pt_1() .pt_1()
.refine_style(&self.style) .refine_style(&style)
.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()
}
}
+112 -1
View File
@@ -1,6 +1,8 @@
//! The panel row: the main island fills the window; splitting makes two //! The panel row: the main island fills the window; splitting makes two
//! half-width islands with a drag divider that resizes them. //! half-width islands with a drag divider that resizes them.
use std::sync::Arc;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _,
@@ -8,7 +10,7 @@ use gpui::{
point, px, size, point, px, size,
}; };
use ui::common::v_flex; use ui::common::v_flex;
use ui::layout::panel::{Panel, PanelRow, PanelView}; use ui::layout::panel::{Panel, PanelRow, PanelView, SubPanels};
use ui::tabs::Tabs; use ui::tabs::Tabs;
use ui::theme::Theme; use ui::theme::Theme;
@@ -333,3 +335,112 @@ fn panel_tab_uses_title_prefix_and_loading(cx: &mut TestAppContext) {
"loading adds the spinner to the tab" "loading adds the spinner to the tab"
); );
} }
/// A marker panel that owns sub panels through the standard overrides.
struct SubsView {
selector: SharedString,
subs: SubPanels,
}
impl SubsView {
fn new(selector: &'static str) -> Self {
Self {
selector: SharedString::from(selector),
subs: SubPanels::default(),
}
}
}
impl Render for SubsView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let selector = self.selector.clone();
div()
.debug_selector(move || selector.to_string())
.size_full()
}
}
impl Panel for SubsView {
fn title(&self, _cx: &App) -> SharedString {
self.selector.clone()
}
fn sub_panels(&self, _cx: &App) -> &SubPanels {
&self.subs
}
fn open_sub_panel(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
_cx: &mut Context<Self>,
) -> bool {
self.subs.open(id, view)
}
fn close_sub_panel(&mut self, id: &SharedString, _cx: &mut Context<Self>) -> bool {
self.subs.close(id)
}
}
struct SubsHarness {
main: Entity<SubsView>,
}
impl Render for SubsHarness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.child(PanelRow::new("subs-harness").main(self.main.clone()))
}
}
/// Owned sub panels tile beside their panel, recursively, main at half width.
#[gpui::test]
fn sub_panels_tile_beside_their_panel(cx: &mut TestAppContext) {
let main = cx.update(|cx| {
Theme::init(cx);
let main = cx.new(|_| SubsView::new("sub-test-main"));
let sub = cx.new(|_| SubsView::new("sub-test-sub"));
let sub_sub = cx.new(|_| TagView::new("sub-test-sub-sub"));
sub.update(cx, |sub, _| {
sub.subs.open("sub-test-sub-sub", Arc::new(sub_sub.clone()));
});
main.update(cx, |main, _| {
main.subs.open("sub-test-sub", Arc::new(sub.clone()));
});
main
});
let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, _| {
SubsHarness { main }
});
let mut cx = VisualTestContext::from_window(window.into(), cx);
cx.run_until_parked();
let main = cx
.debug_bounds("sub-test-main")
.expect("main panel laid out");
let sub = cx.debug_bounds("sub-test-sub").expect("sub panel laid out");
let sub_sub = cx
.debug_bounds("sub-test-sub-sub")
.expect("sub-sub panel laid out");
// Three tiles run left to right, main first, each filling the row's height.
assert!(main.origin.x < sub.origin.x);
assert!(sub.origin.x < sub_sub.origin.x);
assert!(main.size.height >= px(WINDOW_HEIGHT - 40.0));
assert!(sub.size.height >= px(WINDOW_HEIGHT - 40.0));
assert!(sub_sub.size.height >= px(WINDOW_HEIGHT - 40.0));
// The main tile opens seeded at half the row; the sub tiles share the rest.
assert!(
(main.size.width - px(498.0)).abs() <= px(15.0),
"main tile width {:?}",
main.size.width
);
assert!(main.size.width > sub.size.width);
assert!(sub_sub.right() <= px(WINDOW_WIDTH));
}