dock: Revert panel radio size to back to use Pixels type for panel size. (#842)

This PR to revert previous dock changes to back to use `Pixels` type for
panel size.

- #833 
- #839 
- #840
This commit is contained in:
Jason Lee 2025-05-09 16:47:24 +08:00 committed by GitHub
parent 6caf6f95df
commit d288a51e06
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 212 additions and 204 deletions

View file

@ -279,7 +279,7 @@ impl StoryWorkspace {
cx,
),
],
vec![None, Some(0.2)],
vec![None, Some(px(360.))],
&dock_area,
window,
cx,
@ -328,9 +328,9 @@ impl StoryWorkspace {
_ = dock_area.update(cx, |view, cx| {
view.set_version(MAIN_DOCK_AREA.version, window, cx);
view.set_center(dock_item, window, cx);
view.set_left_dock(left_panels, px(300.), true, window, cx);
view.set_bottom_dock(bottom_panels, px(200.), true, window, cx);
view.set_right_dock(right_panels, px(320.), true, window, cx);
view.set_left_dock(left_panels, Some(px(350.)), true, window, cx);
view.set_bottom_dock(bottom_panels, Some(px(200.)), true, window, cx);
view.set_right_dock(right_panels, Some(px(320.)), true, window, cx);
Self::save_state(&view.dump(cx)).unwrap();
});

View file

@ -53,32 +53,36 @@ impl ResizableStory {
v_resizable()
.group(
h_resizable()
.ratio(0.1)
.size(px(150.))
.child(
resizable_panel()
.ratio(0.3)
.size(px(300.))
.content(|_, cx| panel_box("Left 1 (Min 120px)", cx)),
cx,
)
.child(
resizable_panel().content(|_, cx| panel_box("Center 1", cx)),
resizable_panel()
.size(px(400.))
.content(|_, cx| panel_box("Center 1", cx)),
cx,
)
.child(
resizable_panel()
.ratio(0.4)
.size(px(300.))
.content(|_, cx| panel_box("Right (Grow)", cx)),
cx,
),
cx,
)
.child(
resizable_panel().content(|_, cx| panel_box("Center (Grow)", cx)),
resizable_panel()
.size(px(150.))
.content(|_, cx| panel_box("Center (Grow)", cx)),
cx,
)
.child(
resizable_panel()
.ratio(0.5)
.size(px(210.))
.content(|_, cx| panel_box("Bottom", cx)),
cx,
)
@ -88,12 +92,14 @@ impl ResizableStory {
h_resizable()
.child(
resizable_panel()
.ratio(0.3)
.size(px(300.))
.content(|_, cx| panel_box("Left 2", cx)),
cx,
)
.child(
resizable_panel().content(|_, cx| panel_box("Right (Grow)", cx)),
resizable_panel()
.size(px(400.))
.content(|_, cx| panel_box("Right (Grow)", cx)),
cx,
)
});
@ -108,9 +114,8 @@ impl ResizableStory {
impl Render for ResizableStory {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.h_full()
.gap_6()
.child(div().h(px(800.)).child(self.group1.clone()))
.child(self.group1.clone())
.child(self.group2.clone())
}
}

View file

@ -66,7 +66,7 @@ pub struct Dock {
pub(super) placement: DockPlacement,
dock_area: WeakEntity<DockArea>,
pub(crate) panel: DockItem,
/// The size of the dock.
/// The size is means the width or height of the Dock, if the placement is left or right, the size is width, otherwise the size is height.
pub(super) size: Pixels,
pub(super) open: bool,
/// Whether the Dock is collapsible, default: true
@ -104,7 +104,7 @@ impl Dock {
panel,
open: true,
collapsible: true,
size: px(200.),
size: px(200.0),
resizing: false,
}
}
@ -147,7 +147,7 @@ impl Dock {
pub(super) fn from_state(
dock_area: WeakEntity<DockArea>,
placement: DockPlacement,
size: impl Into<Pixels>,
size: Pixels,
panel: DockItem,
open: bool,
window: &mut Window,
@ -176,7 +176,7 @@ impl Dock {
dock_area,
panel,
open,
size: size.into(),
size,
collapsible: true,
resizing: false,
}
@ -249,8 +249,8 @@ impl Dock {
}
/// Set the size of the Dock.
pub fn set_size(&mut self, size: impl Into<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
self.size = size.into();
pub fn set_size(&mut self, size: Pixels, _: &mut Window, cx: &mut Context<Self>) {
self.size = size.max(PANEL_MIN_SIZE);
cx.notify();
}
@ -301,7 +301,6 @@ impl Dock {
cx.new(|_| info.deref().clone())
})
}
fn resize(&mut self, mouse_position: Point<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
if !self.resizing {
return;
@ -313,6 +312,28 @@ impl Dock {
.expect("DockArea is missing")
.read(cx);
let area_bounds = dock_area.bounds;
let mut left_dock_size = Pixels(0.0);
let mut right_dock_size = Pixels(0.0);
// Get the size of the left dock if it's open and not the current dock
if let Some(left_dock) = &dock_area.left_dock {
if left_dock.entity_id() != cx.entity().entity_id() {
let left_dock_read = left_dock.read(cx);
if left_dock_read.is_open() {
left_dock_size = left_dock_read.size;
}
}
}
// Get the size of the right dock if it's open and not the current dock
if let Some(right_dock) = &dock_area.right_dock {
if right_dock.entity_id() != cx.entity().entity_id() {
let right_dock_read = right_dock.read(cx);
if right_dock_read.is_open() {
right_dock_size = right_dock_read.size;
}
}
}
let size = match self.placement {
DockPlacement::Left => mouse_position.x - area_bounds.left(),
@ -320,7 +341,21 @@ impl Dock {
DockPlacement::Bottom => area_bounds.bottom() - mouse_position.y,
DockPlacement::Center => unreachable!(),
};
self.size = size.max(PANEL_MIN_SIZE);
match self.placement {
DockPlacement::Left => {
let max_size = area_bounds.size.width - PANEL_MIN_SIZE - right_dock_size;
self.size = size.clamp(PANEL_MIN_SIZE, max_size);
}
DockPlacement::Right => {
let max_size = area_bounds.size.width - PANEL_MIN_SIZE - left_dock_size;
self.size = size.clamp(PANEL_MIN_SIZE, max_size);
}
DockPlacement::Bottom => {
let max_size = area_bounds.size.height - PANEL_MIN_SIZE;
self.size = size.clamp(PANEL_MIN_SIZE, max_size);
}
DockPlacement::Center => unreachable!(),
}
cx.notify();
}
@ -337,14 +372,13 @@ impl Render for Dock {
}
let cache_style = StyleRefinement::default().absolute().size_full();
let dock_size = self.size;
div()
.relative()
.overflow_hidden()
.map(|this| match self.placement {
DockPlacement::Left | DockPlacement::Right => this.h_flex().h_full().w(dock_size),
DockPlacement::Bottom => this.w_full().h(dock_size),
DockPlacement::Left | DockPlacement::Right => this.h_flex().h_full().w(self.size),
DockPlacement::Bottom => this.w_full().h(self.size),
DockPlacement::Center => unreachable!(),
})
// Bottom Dock should keep the title bar, then user can click the Toggle button

View file

@ -8,7 +8,7 @@ mod tiles;
use anyhow::Result;
use gpui::{
actions, canvas, div, prelude::FluentBuilder, px, AnyElement, AnyView, App, AppContext, Axis,
actions, canvas, div, prelude::FluentBuilder, AnyElement, AnyView, App, AppContext, Axis,
Bounds, Context, Edges, Entity, EntityId, EventEmitter, InteractiveElement as _, IntoElement,
ParentElement as _, Pixels, Render, SharedString, Styled, Subscription, WeakEntity, Window,
};
@ -78,7 +78,7 @@ pub enum DockItem {
Split {
axis: Axis,
items: Vec<DockItem>,
ratios: Vec<Option<f32>>,
sizes: Vec<Option<Pixels>>,
view: Entity<StackPanel>,
},
/// Tab layout
@ -100,15 +100,12 @@ impl std::fmt::Debug for DockItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DockItem::Split {
axis,
items,
ratios,
..
axis, items, sizes, ..
} => f
.debug_struct("Split")
.field("axis", axis)
.field("items", &items.len())
.field("ratios", ratios)
.field("sizes", sizes)
.finish(),
DockItem::Tabs {
items, active_ix, ..
@ -138,12 +135,12 @@ impl DockItem {
/// Create DockItem with split layout, each item of panel have specified size.
///
/// Please note that the `items` and `ratios` must have the same length.
/// Please note that the `items` and `sizes` must have the same length.
/// Set `None` in `sizes` to make the index of panel have auto size.
pub fn split_with_sizes(
axis: Axis,
items: Vec<DockItem>,
ratios: Vec<Option<f32>>,
sizes: Vec<Option<Pixels>>,
dock_area: &WeakEntity<DockArea>,
window: &mut Window,
cx: &mut App,
@ -153,14 +150,14 @@ impl DockItem {
let mut stack_panel = StackPanel::new(axis, window, cx);
for (i, item) in items.iter_mut().enumerate() {
let view = item.view();
let ratio = ratios.get(i).copied().flatten();
stack_panel.add_panel(view.clone(), ratio, dock_area.clone(), window, cx)
let size = sizes.get(i).copied().flatten();
stack_panel.add_panel(view.clone(), size, dock_area.clone(), window, cx)
}
for (i, item) in items.iter().enumerate() {
let view = item.view();
let ratio = ratios.get(i).copied().flatten();
stack_panel.add_panel(view.clone(), ratio, dock_area.clone(), window, cx)
let size = sizes.get(i).copied().flatten();
stack_panel.add_panel(view.clone(), size, dock_area.clone(), window, cx)
}
stack_panel
@ -179,7 +176,7 @@ impl DockItem {
Self::Split {
axis,
items,
ratios,
sizes,
view: stack_panel,
}
}
@ -450,7 +447,7 @@ impl DockArea {
let dock_item = DockItem::Split {
axis: Axis::Horizontal,
items: vec![],
ratios: vec![],
sizes: vec![],
view: stack_panel.clone(),
};
@ -530,7 +527,7 @@ impl DockArea {
pub fn set_left_dock(
&mut self,
panel: DockItem,
size: impl Into<Pixels>,
size: Option<Pixels>,
open: bool,
window: &mut Window,
cx: &mut Context<Self>,
@ -539,7 +536,9 @@ impl DockArea {
let weak_self = cx.entity().downgrade();
self.left_dock = Some(cx.new(|cx| {
let mut dock = Dock::left(weak_self.clone(), window, cx);
dock.set_size(size, window, cx);
if let Some(size) = size {
dock.set_size(size, window, cx);
}
dock.set_panel(panel, window, cx);
dock.set_open(open, window, cx);
dock
@ -550,7 +549,7 @@ impl DockArea {
pub fn set_bottom_dock(
&mut self,
panel: DockItem,
size: impl Into<Pixels>,
size: Option<Pixels>,
open: bool,
window: &mut Window,
cx: &mut Context<Self>,
@ -559,7 +558,9 @@ impl DockArea {
let weak_self = cx.entity().downgrade();
self.bottom_dock = Some(cx.new(|cx| {
let mut dock = Dock::bottom(weak_self.clone(), window, cx);
dock.set_size(size, window, cx);
if let Some(size) = size {
dock.set_size(size, window, cx);
}
dock.set_panel(panel, window, cx);
dock.set_open(open, window, cx);
dock
@ -570,7 +571,7 @@ impl DockArea {
pub fn set_right_dock(
&mut self,
panel: DockItem,
size: impl Into<Pixels>,
size: Option<Pixels>,
open: bool,
window: &mut Window,
cx: &mut Context<Self>,
@ -579,7 +580,9 @@ impl DockArea {
let weak_self = cx.entity().downgrade();
self.right_dock = Some(cx.new(|cx| {
let mut dock = Dock::right(weak_self.clone(), window, cx);
dock.set_size(size, window, cx);
if let Some(size) = size {
dock.set_size(size, window, cx);
}
dock.set_panel(panel, window, cx);
dock.set_open(open, window, cx);
dock
@ -723,7 +726,7 @@ impl DockArea {
} else {
self.set_left_dock(
DockItem::tabs(vec![panel], None, &weak_self, window, cx),
px(200.),
None,
true,
window,
cx,
@ -736,7 +739,7 @@ impl DockArea {
} else {
self.set_bottom_dock(
DockItem::tabs(vec![panel], None, &weak_self, window, cx),
px(200.),
None,
true,
window,
cx,
@ -749,7 +752,7 @@ impl DockArea {
} else {
self.set_right_dock(
DockItem::tabs(vec![panel], None, &weak_self, window, cx),
px(200.),
None,
true,
window,
cx,

View file

@ -13,8 +13,8 @@ use crate::{
use super::{DockArea, Panel, PanelEvent, PanelState, PanelView, TabPanel};
use gpui::{
prelude::FluentBuilder as _, App, AppContext, Axis, Context, DismissEvent, Entity,
EventEmitter, FocusHandle, Focusable, IntoElement, ParentElement, Render, Styled, Subscription,
WeakEntity, Window,
EventEmitter, FocusHandle, Focusable, IntoElement, ParentElement, Pixels, Render, Styled,
Subscription, WeakEntity, Window,
};
use smallvec::SmallVec;
@ -41,11 +41,11 @@ impl Panel for StackPanel {
}
}
fn dump(&self, cx: &App) -> PanelState {
let flexes = self.panel_group.read(cx).ratios();
let sizes = self.panel_group.read(cx).sizes();
let mut state = PanelState::new(self);
for panel in &self.panels {
state.add_child(panel.dump(cx));
state.info = PanelInfo::stack(flexes.clone(), self.axis);
state.info = PanelInfo::stack(sizes.clone(), self.axis);
}
state
@ -111,19 +111,19 @@ impl StackPanel {
pub fn add_panel(
&mut self,
panel: Arc<dyn PanelView>,
ratio: Option<f32>,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.insert_panel(panel, self.panels.len(), ratio, dock_area, window, cx);
self.insert_panel(panel, self.panels.len(), size, dock_area, window, cx);
}
pub fn add_panel_at(
&mut self,
panel: Arc<dyn PanelView>,
placement: Placement,
ratio: Option<f32>,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
@ -132,7 +132,7 @@ impl StackPanel {
panel,
self.panels_len(),
placement,
ratio,
size,
dock_area,
window,
cx,
@ -145,17 +145,17 @@ impl StackPanel {
panel: Arc<dyn PanelView>,
ix: usize,
placement: Placement,
ratio: Option<f32>,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) {
match placement {
Placement::Top | Placement::Left => {
self.insert_panel_before(panel, ix, ratio, dock_area, window, cx)
self.insert_panel_before(panel, ix, size, dock_area, window, cx)
}
Placement::Right | Placement::Bottom => {
self.insert_panel_after(panel, ix, ratio, dock_area, window, cx)
self.insert_panel_after(panel, ix, size, dock_area, window, cx)
}
}
}
@ -165,12 +165,12 @@ impl StackPanel {
&mut self,
panel: Arc<dyn PanelView>,
ix: usize,
ratio: Option<f32>,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.insert_panel(panel, ix, ratio, dock_area, window, cx);
self.insert_panel(panel, ix, size, dock_area, window, cx);
}
/// Insert a panel after the index.
@ -178,26 +178,26 @@ impl StackPanel {
&mut self,
panel: Arc<dyn PanelView>,
ix: usize,
ratio: Option<f32>,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.insert_panel(panel, ix + 1, ratio, dock_area, window, cx);
self.insert_panel(panel, ix + 1, size, dock_area, window, cx);
}
fn new_resizable_panel(panel: Arc<dyn PanelView>, ratio: Option<f32>) -> ResizablePanel {
fn new_resizable_panel(panel: Arc<dyn PanelView>, size: Option<Pixels>) -> ResizablePanel {
resizable_panel()
.content_view(panel.view())
.content_visible(move |_, cx| panel.visible(cx))
.when_some(ratio, |this, ratio| this.ratio(ratio))
.when_some(size, |this, size| this.size(size))
}
fn insert_panel(
&mut self,
panel: Arc<dyn PanelView>,
ix: usize,
ratio: Option<f32>,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
@ -241,7 +241,7 @@ impl StackPanel {
self.panels.insert(ix, panel.clone());
self.panel_group.update(cx, |view, cx| {
view.insert_child(
Self::new_resizable_panel(panel.clone(), ratio),
Self::new_resizable_panel(panel.clone(), size),
ix,
window,
cx,

View file

@ -100,8 +100,7 @@ impl From<Bounds<Pixels>> for TileMeta {
pub enum PanelInfo {
#[serde(rename = "stack")]
Stack {
#[serde(default)]
ratios: Vec<f32>,
sizes: Vec<Pixels>,
axis: usize, // 0 for horizontal, 1 for vertical
},
#[serde(rename = "tabs")]
@ -113,9 +112,9 @@ pub enum PanelInfo {
}
impl PanelInfo {
pub fn stack(ratios: Vec<f32>, axis: Axis) -> Self {
pub fn stack(sizes: Vec<Pixels>, axis: Axis) -> Self {
Self::Stack {
ratios,
sizes,
axis: if axis == Axis::Horizontal { 0 } else { 1 },
}
}
@ -143,9 +142,9 @@ impl PanelInfo {
}
}
pub fn ratios(&self) -> Option<&Vec<f32>> {
pub fn sizes(&self) -> Option<&Vec<Pixels>> {
match self {
Self::Stack { ratios, .. } => Some(ratios),
Self::Stack { sizes, .. } => Some(sizes),
_ => None,
}
}
@ -195,14 +194,14 @@ impl PanelState {
.collect();
match info {
PanelInfo::Stack { ratios, axis } => {
PanelInfo::Stack { sizes, axis } => {
let axis = if axis == 0 {
Axis::Horizontal
} else {
Axis::Vertical
};
let ratios = ratios.iter().map(|&ratio| Some(ratio)).collect();
DockItem::split_with_sizes(axis, items, ratios, &dock_area, window, cx)
let sizes = sizes.iter().map(|s| Some(*s)).collect_vec();
DockItem::split_with_sizes(axis, items, sizes, &dock_area, window, cx)
}
PanelInfo::Tabs { active_index } => {
if items.len() == 1 {
@ -240,6 +239,8 @@ impl PanelState {
#[cfg(test)]
mod tests {
use gpui::px;
use super::*;
#[test]
fn test_deserialize_item_state() {
@ -258,7 +259,7 @@ mod tests {
let left_dock = state.left_dock.unwrap();
assert_eq!(left_dock.open, true);
assert_eq!(left_dock.size, px(350.));
assert_eq!(left_dock.size, px(350.0));
assert_eq!(left_dock.placement, DockPlacement::Left);
assert_eq!(left_dock.panel.panel_name, "TabPanel");
assert_eq!(left_dock.panel.children.len(), 1);
@ -266,14 +267,14 @@ mod tests {
let bottom_dock = state.bottom_dock.unwrap();
assert_eq!(bottom_dock.open, true);
assert_eq!(bottom_dock.size, px(200.));
assert_eq!(bottom_dock.size, px(200.0));
assert_eq!(bottom_dock.panel.panel_name, "TabPanel");
assert_eq!(bottom_dock.panel.children.len(), 2);
assert_eq!(bottom_dock.panel.children[0].panel_name, "StoryContainer");
let right_dock = state.right_dock.unwrap();
assert_eq!(right_dock.open, true);
assert_eq!(right_dock.size, px(320.));
assert_eq!(right_dock.size, px(320.0));
assert_eq!(right_dock.panel.panel_name, "TabPanel");
assert_eq!(right_dock.panel.children.len(), 1);
assert_eq!(right_dock.panel.children[0].panel_name, "StoryContainer");

View file

@ -1,10 +1,10 @@
use std::sync::Arc;
use gpui::{
div, prelude::FluentBuilder, px, relative, rems, App, AppContext, Context, Corner,
div, prelude::FluentBuilder, px, rems, App, AppContext, Context, Corner, DefiniteLength,
DismissEvent, DragMoveEvent, Empty, Entity, EventEmitter, FocusHandle, Focusable,
InteractiveElement as _, IntoElement, ParentElement, Render, ScrollHandle, SharedString,
StatefulInteractiveElement, StyleRefinement, Styled, WeakEntity, Window,
InteractiveElement as _, IntoElement, ParentElement, Pixels, Render, ScrollHandle,
SharedString, StatefulInteractiveElement, StyleRefinement, Styled, WeakEntity, Window,
};
use rust_i18n::t;
@ -264,7 +264,7 @@ impl TabPanel {
&mut self,
panel: Arc<dyn PanelView>,
placement: Placement,
ratio: Option<f32>,
size: Option<Pixels>,
window: &mut Window,
cx: &mut Context<Self>,
) {
@ -272,7 +272,7 @@ impl TabPanel {
cx.update(|window, cx| {
view.update(cx, |view, cx| {
view.will_split_placement = Some(placement);
view.split_panel(panel, placement, ratio, window, cx)
view.split_panel(panel, placement, size, window, cx)
})
.ok()
})
@ -823,7 +823,7 @@ impl TabPanel {
.bg(cx.theme().drop_target)
.map(|this| match self.will_split_placement {
Some(placement) => {
let size = relative(0.35);
let size = DefiniteLength::Fraction(0.35);
match placement {
Placement::Left => this.left_0().top_0().bottom_0().w(size),
Placement::Right => {
@ -930,7 +930,7 @@ impl TabPanel {
&self,
panel: Arc<dyn PanelView>,
placement: Placement,
ratio: Option<f32>,
size: Option<Pixels>,
window: &mut Window,
cx: &mut Context<Self>,
) {
@ -959,7 +959,7 @@ impl TabPanel {
Arc::new(new_tab_panel),
ix,
placement,
ratio,
size,
dock_area.clone(),
window,
cx,
@ -971,7 +971,7 @@ impl TabPanel {
Arc::new(new_tab_panel),
ix,
placement,
ratio,
size,
dock_area.clone(),
window,
cx,
@ -1001,13 +1001,7 @@ impl TabPanel {
new_stack_panel.update(cx, |view, cx| match placement {
Placement::Left | Placement::Top => {
view.add_panel(
Arc::new(new_tab_panel),
ratio,
dock_area.clone(),
window,
cx,
);
view.add_panel(Arc::new(new_tab_panel), size, dock_area.clone(), window, cx);
view.add_panel(
Arc::new(tab_panel.clone()),
None,
@ -1024,13 +1018,7 @@ impl TabPanel {
window,
cx,
);
view.add_panel(
Arc::new(new_tab_panel),
ratio,
dock_area.clone(),
window,
cx,
);
view.add_panel(Arc::new(new_tab_panel), size, dock_area.clone(), window, cx);
}
});

View file

@ -2,7 +2,7 @@ use std::{ops::Deref, rc::Rc};
use gpui::{
canvas, div, prelude::FluentBuilder, px, relative, Along, AnyElement, AnyView, App, AppContext,
Axis, Bounds, Context, Element, Empty, Entity, EntityId, EventEmitter, IntoElement,
Axis, Bounds, Context, Element, Empty, Entity, EntityId, EventEmitter, IntoElement, IsZero,
MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Render, Style, Styled, WeakEntity, Window,
};
@ -28,9 +28,9 @@ impl Render for DragPanel {
#[derive(Clone)]
pub struct ResizablePanelGroup {
panels: Vec<Entity<ResizablePanel>>,
ratios: Vec<f32>,
sizes: Vec<Pixels>,
axis: Axis,
ratio: Option<f32>,
size: Option<Pixels>,
bounds: Bounds<Pixels>,
resizing_panel_ix: Option<usize>,
}
@ -39,16 +39,16 @@ impl ResizablePanelGroup {
pub(super) fn new() -> Self {
Self {
axis: Axis::Horizontal,
ratios: Vec::new(),
sizes: Vec::new(),
panels: Vec::new(),
ratio: None,
size: None,
bounds: Bounds::default(),
resizing_panel_ix: None,
}
}
pub fn load(&mut self, ratios: Vec<f32>, panels: Vec<Entity<ResizablePanel>>) {
self.ratios = ratios;
pub fn load(&mut self, sizes: Vec<Pixels>, panels: Vec<Entity<ResizablePanel>>) {
self.sizes = sizes;
self.panels = panels;
}
@ -72,10 +72,10 @@ impl ResizablePanelGroup {
/// Add a ResizablePanelGroup as a child to the group.
pub fn group(self, group: ResizablePanelGroup, cx: &mut Context<Self>) -> Self {
let group: ResizablePanelGroup = group;
let ratio = group.ratio;
let size = group.size;
let panel = ResizablePanel::new()
.content_view(cx.new(|_| group).into())
.when_some(ratio, |this, ratio| this.ratio(ratio));
.when_some(size, |this, size| this.size(size));
self.child(panel, cx)
}
@ -83,31 +83,26 @@ impl ResizablePanelGroup {
///
/// - When the axis is horizontal, the size is the height of the group.
/// - When the axis is vertical, the size is the width of the group.
pub fn ratio(mut self, ratio: f32) -> Self {
self.ratio = Some(ratio);
pub fn size(mut self, size: Pixels) -> Self {
self.size = Some(size);
self
}
/// Returns the ratios of the panels.
pub(crate) fn ratios(&self) -> &Vec<f32> {
&self.ratios
/// Returns the sizes of the resizable panels.
pub(crate) fn sizes(&self) -> Vec<Pixels> {
self.sizes.clone()
}
/// Calculates the sum of all panel sizes within the group.
pub fn total_size(&self) -> Pixels {
self.bounds.size.along(self.axis)
self.sizes.iter().fold(px(0.0), |acc, &size| acc + size)
}
pub fn add_child(&mut self, panel: ResizablePanel, cx: &mut Context<Self>) {
let mut panel = panel;
panel.axis = self.axis;
panel.group = Some(cx.entity().downgrade());
let ratio = match panel.ratio {
Some(ratio) => ratio,
None => panel.initial_radio.unwrap_or_default(),
};
self.ratios.push(ratio);
self.sizes.push(panel.initial_size.unwrap_or_default());
self.panels.push(cx.new(|_| panel));
}
@ -121,11 +116,9 @@ impl ResizablePanelGroup {
let mut panel = panel;
panel.axis = self.axis;
panel.group = Some(cx.entity().downgrade());
let ratio = match panel.ratio {
Some(ratio) => ratio,
None => panel.initial_radio.unwrap_or_default(),
};
self.ratios.insert(ix, ratio);
self.sizes
.insert(ix, panel.initial_size.unwrap_or_default());
self.panels.insert(ix, cx.new(|_| panel));
cx.notify()
}
@ -141,32 +134,26 @@ impl ResizablePanelGroup {
let mut panel = panel;
let old_panel = self.panels[ix].clone();
let old_panel_initial_ratio = old_panel.read(cx).initial_radio;
let old_panel_ratio = old_panel.read(cx).ratio;
let old_panel_initial_size = old_panel.read(cx).initial_size;
let old_panel_size_ratio = old_panel.read(cx).size_ratio;
panel.initial_radio = old_panel_initial_ratio;
panel.ratio = old_panel_ratio;
panel.initial_size = old_panel_initial_size;
panel.size_ratio = old_panel_size_ratio;
panel.axis = self.axis;
panel.group = Some(cx.entity().downgrade());
let ratio = match panel.ratio {
Some(ratio) => ratio,
None => panel.initial_radio.unwrap_or_default(),
};
self.ratios[ix] = ratio;
self.sizes[ix] = panel.initial_size.unwrap_or_default();
self.panels[ix] = cx.new(|_| panel);
cx.notify()
}
pub fn remove_child(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Self>) {
self.ratios.remove(ix);
self.sizes.remove(ix);
self.panels.remove(ix);
cx.notify()
}
pub(crate) fn remove_all_children(&mut self, _: &mut Window, cx: &mut Context<Self>) {
self.ratios.clear();
self.sizes.clear();
self.panels.clear();
cx.notify()
}
@ -196,10 +183,9 @@ impl ResizablePanelGroup {
self.resizing_panel_ix = None;
}
fn sync_real_panel_sizes(&mut self, _: &Window, cx: &mut App) {
let total_size = self.total_size();
fn sync_real_panel_sizes(&mut self, _: &Window, cx: &App) {
for (i, panel) in self.panels.iter().enumerate() {
self.ratios[i] = panel.read(cx).bounds.size.along(self.axis) / total_size;
self.sizes[i] = panel.read(cx).bounds.size.along(self.axis)
}
}
@ -222,54 +208,53 @@ impl ResizablePanelGroup {
self.sync_real_panel_sizes(window, cx);
let new_ratio = size / container_size;
let mut changed = new_ratio - self.ratios[ix];
let is_expand = changed > 0.;
let mut changed = size - self.sizes[ix];
let is_expand = changed > px(0.);
let main_ix = ix;
let mut new_ratios = self.ratios.clone();
let min_ratio = PANEL_MIN_SIZE / container_size;
let mut new_sizes = self.sizes.clone();
if is_expand {
new_ratios[ix] = new_ratio;
new_sizes[ix] = size;
// Now to expand logic is correct.
while changed > 0. && ix < self.panels.len() - 1 {
while changed > px(0.) && ix < self.panels.len() - 1 {
ix += 1;
let available_ratio = (new_ratios[ix] - min_ratio).max(0.);
let to_reduce = changed.min(available_ratio);
new_ratios[ix] -= to_reduce;
let available_size = (new_sizes[ix] - PANEL_MIN_SIZE).max(px(0.));
let to_reduce = changed.min(available_size);
new_sizes[ix] -= to_reduce;
changed -= to_reduce;
}
} else {
let new_size = new_ratio.max(min_ratio);
new_ratios[ix] = new_size;
changed = new_ratio - min_ratio;
new_ratios[ix + 1] += self.ratios[ix] - new_size;
let new_size = size.max(PANEL_MIN_SIZE);
new_sizes[ix] = new_size;
changed = size - PANEL_MIN_SIZE;
new_sizes[ix + 1] += self.sizes[ix] - new_size;
while changed < 0. && ix > 0 {
while changed < px(0.) && ix > 0 {
ix -= 1;
let available_ratio = self.ratios[ix] - min_ratio;
let to_increase = (changed).min(available_ratio);
new_ratios[ix] += to_increase;
let available_size = self.sizes[ix] - PANEL_MIN_SIZE;
let to_increase = (changed).min(available_size);
new_sizes[ix] += to_increase;
changed += to_increase;
}
}
// If total size exceeds container size, adjust the main panel
let total_ratio: f32 = new_ratios.iter().sum();
if total_ratio > 1. {
let overflow = 1.0 - total_ratio;
new_ratios[main_ix] = (new_ratios[main_ix] - overflow).max(min_ratio);
let total_size: Pixels = new_sizes.iter().map(|s| s.0).sum::<f32>().into();
if total_size > container_size {
let overflow = total_size - container_size;
new_sizes[main_ix] = (new_sizes[main_ix] - overflow).max(PANEL_MIN_SIZE);
}
self.ratios = new_ratios;
let total_size = new_sizes.iter().fold(px(0.0), |acc, &size| acc + size);
self.sizes = new_sizes;
for (i, panel) in self.panels.iter().enumerate() {
let ratio = self.ratios[i];
if ratio > 0. {
let size = self.sizes[i];
if size > px(0.) {
panel.update(cx, |this, _| {
this.size = Some(container_size * ratio);
this.ratio = Some(ratio);
this.size = Some(size);
this.size_ratio = Some(size / total_size);
});
}
}
@ -315,11 +300,11 @@ impl Render for ResizablePanelGroup {
pub struct ResizablePanel {
group: Option<WeakEntity<ResizablePanelGroup>>,
/// Initial size is the size that the panel has when it is created.
initial_radio: Option<f32>,
initial_size: Option<Pixels>,
/// size is the size that the panel has when it is resized or adjusted by flex layout.
size: Option<Pixels>,
/// the size ratio that the panel has relative to its group
ratio: Option<f32>,
size_ratio: Option<f32>,
axis: Axis,
content_builder: Option<Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>>,
content_view: Option<AnyView>,
@ -333,9 +318,9 @@ impl ResizablePanel {
pub(super) fn new() -> Self {
Self {
group: None,
initial_radio: None,
initial_size: None,
size: None,
ratio: None,
size_ratio: None,
axis: Axis::Horizontal,
content_builder: None,
content_view: None,
@ -366,36 +351,28 @@ impl ResizablePanel {
self
}
// /// Set the initial size of the panel.
// pub fn size(mut self, size: Pixels) -> Self {
// self.initial_size = Some(size);
// self
// }
/// Set the flex ratio of the panel, the ratio is relative to the total size of the group.
///
/// The `ratio` is 0.0 to 1.0.
pub fn ratio(mut self, ratio: f32) -> Self {
self.initial_radio = Some(ratio);
self.ratio = Some(ratio);
/// Set the initial size of the panel.
pub fn size(mut self, size: Pixels) -> Self {
self.initial_size = Some(size);
self
}
/// Save the real panel size, and update group sizes
fn update_size(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
fn update_size(&mut self, bounds: Bounds<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
let new_size = bounds.size.along(self.axis);
self.bounds = bounds;
self.ratio = None;
self.size_ratio = None;
self.size = Some(new_size);
cx.notify();
if let Some(group) = self.group.clone() {
window.defer(cx, move |window, cx| {
_ = group.update(cx, |view, cx| {
view.sync_real_panel_sizes(window, cx);
});
let entity_id = cx.entity().entity_id();
if let Some(group) = self.group.as_ref() {
_ = group.update(cx, |view, _| {
if let Some(ix) = view.panels.iter().position(|v| v.entity_id() == entity_id) {
view.sizes[ix] = new_size;
}
});
}
cx.notify();
}
}
@ -405,7 +382,7 @@ impl Render for ResizablePanel {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if !(self.content_visible)(window, cx) {
// To keep size as initial size, to make sure the size will not be changed.
self.initial_radio = self.ratio;
self.initial_size = self.size;
self.size = None;
return div();
}
@ -422,23 +399,23 @@ impl Render for ResizablePanel {
.flex_grow()
.size_full()
.relative()
.when(self.initial_radio.is_none(), |this| this.flex_shrink())
.when(self.initial_size.is_none(), |this| this.flex_shrink())
.when(self.axis.is_vertical(), |this| this.min_h(PANEL_MIN_SIZE))
.when(self.axis.is_horizontal(), |this| this.min_w(PANEL_MIN_SIZE))
.when_some(self.initial_radio, |this, radio| {
if radio == 0. {
.when_some(self.initial_size, |this, size| {
if size.is_zero() {
this
} else {
// The `self.size` is None, that mean the initial size for the panel, so we need set flex_shrink_0
// To let it keep the initial size.
this.when(self.size.is_none() && radio > 0., |this| {
this.when(self.size.is_none() && size > px(0.), |this| {
this.flex_shrink_0()
})
.flex_basis(relative(radio))
.flex_basis(size)
}
})
.map(|this| match (self.ratio, self.size, total_size) {
(Some(ratio), _, _) => this.flex_basis(relative(ratio)),
.map(|this| match (self.size_ratio, self.size, total_size) {
(Some(size_ratio), _, _) => this.flex_basis(relative(size_ratio)),
(None, Some(size), Some(total_size)) => {
this.flex_basis(relative(size / total_size))
}