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
+212 -309
View File
@@ -3,26 +3,72 @@
//! between them; the divider opens at half the row or at a set width
//! ([`PanelRow::split_at`]), and dragging it can be disabled
//! ([`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 gpui::{
AnyElement, AnyView, App, Axis, Context, Div, ElementId, Entity, IntoElement,
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::icons::IconRole;
use crate::layout::StyledExt as _;
use crate::layout::resizable::{Resizable, ResizableState};
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.
#[allow(unused_variables)]
pub trait Panel: Render + 'static {
@@ -43,6 +89,27 @@ pub trait Panel: Render + 'static {
fn loading(&self, cx: &App) -> bool {
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.
@@ -69,6 +136,15 @@ pub trait PanelView: 'static {
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.
fn tab(&self, key: ElementId, cx: &App) -> Tab {
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 {
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> {
@@ -121,6 +213,18 @@ impl<P: PanelView + ?Sized> PanelView for Arc<P> {
fn loading(&self, cx: &App) -> bool {
(**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.
@@ -128,8 +232,8 @@ impl<P: PanelView + ?Sized> PanelView for Arc<P> {
#[must_use]
pub struct PanelRow {
id: ElementId,
main: Option<AnyElement>,
split: Option<AnyElement>,
main: Option<Arc<dyn PanelView>>,
split: Option<Arc<dyn PanelView>>,
/// The main pane's width when split; `None` splits the row in half.
split_width: Option<Pixels>,
resizable: bool,
@@ -155,6 +259,61 @@ fn island(panel: Div, cx: &App) -> Div {
.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 {
/// Creates the panel row.
pub fn new<I>(id: I) -> Self
@@ -176,7 +335,7 @@ impl PanelRow {
where
P: PanelView,
{
self.main = Some(main.view().cached(content_style()).into_any_element());
self.main = Some(Arc::new(main));
self
}
@@ -185,7 +344,7 @@ impl PanelRow {
where
P: PanelView,
{
self.split = Some(panel.view().cached(content_style()).into_any_element());
self.split = Some(Arc::new(panel));
self
}
@@ -195,7 +354,7 @@ impl PanelRow {
P: PanelView,
{
self.split_width = Some(width);
self.split = Some(panel.view().cached(content_style()).into_any_element());
self.split = Some(Arc::new(panel));
self
}
@@ -214,35 +373,49 @@ impl gpui::Styled for PanelRow {
impl RenderOnce for PanelRow {
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;
// 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(
div()
.size_full()
.child(self.main.unwrap_or_else(|| div().into_any_element())),
cx,
);
let row = match self.split {
let row = match split {
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
let main_width = split_width
.unwrap_or((extent - gutter) / 2.0)
.max(PANE_MIN_SIZE);
let split_extent = (extent - main_width - gutter).max(PANE_MIN_SIZE);
if !self.resizable {
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,
);
if !resizable {
div()
.w_full()
.h_full()
.flex()
.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_1().min_w_0().h_full().child(split))
.child(div().flex_1().min_w_0().h_full().child(split_tile))
} else {
let sizes = window.with_element_namespace(id.clone(), |window| {
window
@@ -257,13 +430,19 @@ impl RenderOnce for PanelRow {
div().w_full().h_full().child(
Resizable::new((id.clone(), "split"), sizes)
.axis(Axis::Horizontal)
.pane(main)
.pane(split)
.pane(main_tile)
.pane(split_tile)
.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()
@@ -272,283 +451,7 @@ impl RenderOnce for PanelRow {
.h_full()
.p_2()
.pt_1()
.refine_style(&self.style)
.refine_style(&style)
.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
//! half-width islands with a drag divider that resizes them.
use std::sync::Arc;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _,
@@ -8,7 +10,7 @@ use gpui::{
point, px, size,
};
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::theme::Theme;
@@ -333,3 +335,112 @@ fn panel_tab_uses_title_prefix_and_loading(cx: &mut TestAppContext) {
"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));
}