layout: replace dock with simple titlebar and panel row

This commit is contained in:
2026-11-15 10:08:24 +07:00
parent 33f8856bc2
commit 2d85db215b
13 changed files with 836 additions and 2442 deletions
+12 -21
View File
@@ -2,14 +2,13 @@
name = "gpui-native-layout"
version = "0.1.0"
edition = "2024"
description = "Application layout bootstrap: sidebars and a center dock, one cargo feature each"
description = "Application window layout: a titlebar over a panel row, one cargo feature each"
[dependencies]
gpui = { workspace = true }
gpui-native-theme = { workspace = true }
gpui-native-utils = { workspace = true }
gpui-native-core = { workspace = true, optional = true }
gpui-native-data = { workspace = true, optional = true, features = ["sidebar"] }
gpui-native-icons = { workspace = true, optional = true }
[dev-dependencies]
@@ -17,29 +16,21 @@ gpui = { workspace = true, features = ["test-support"] }
[features]
default = ["full"]
full = ["dock", "resize_handle", "resizable", "shell", "titlebar", "window_controls", "toast", "alert"]
dock = [
"shell",
full = [
"alert",
"panel",
"resize_handle",
"dep:gpui-native-core",
"dep:gpui-native-data",
"dep:gpui-native-icons",
"gpui-native-core/context_menu",
"gpui-native-data/tabs",
"resizable",
"shell",
"titlebar",
"toast",
"window_controls",
]
panel = ["resizable"]
resize_handle = []
resizable = ["resize_handle"]
shell = [
"resize_handle",
"titlebar",
"window_controls",
"dep:gpui-native-core",
"gpui-native-core/button",
"dep:gpui-native-data",
"dep:gpui-native-icons",
]
shell = ["titlebar", "window_controls"]
titlebar = ["window_controls"]
toast = ["shell", "gpui-native-core/toast"]
alert = ["shell", "gpui-native-core/alert"]
toast = ["shell", "gpui-native-core/toast", "gpui-native-core/button"]
alert = ["shell", "gpui-native-core/alert", "gpui-native-core/button"]
window_controls = ["dep:gpui-native-icons"]
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,7 +1,7 @@
//! Application layout: sidebars and a center dock bootstrapped for the app (plan §6.4).
//! Application window layout: a titlebar over a panel row.
#[cfg(feature = "dock")]
pub mod dock;
#[cfg(feature = "panel")]
pub mod panel;
#[cfg(feature = "resize_handle")]
pub mod resize_handle;
+108
View File
@@ -0,0 +1,108 @@
//! The panel row: the window's main content, island-style on the muted
//! background. It can split once into two half-width panels with a drag
//! divider between them; dragging the seam resizes the panels and a
//! double-click restores the half split.
use gpui::{
AnyElement, AnyView, App, Axis, Div, ElementId, IntoElement, ParentElement as _, RenderOnce,
StyleRefinement, Styled as _, Window, div,
};
use gpui_native_theme::ActiveTheme as _;
use crate::resizable::{Resizable, ResizableState};
/// The layout the cached panel content lays out with.
fn content_style() -> StyleRefinement {
StyleRefinement::default().size_full()
}
/// The island chrome every panel paints.
fn island(panel: Div, cx: &App) -> Div {
let theme = cx.theme();
let colors = theme.colors;
panel
.size_full()
.bg(colors.background)
.p_2()
.border_1()
.border_color(colors.border)
.rounded(theme.radius.overlay)
}
/// The panel row drawn under the titlebar.
#[derive(IntoElement)]
#[must_use]
pub struct Panel {
id: ElementId,
main: Option<AnyElement>,
split: Option<AnyElement>,
}
impl Panel {
/// Creates the panel row.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
main: None,
split: None,
}
}
/// Sets the main panel's content.
pub fn main(mut self, main: AnyView) -> Self {
self.main = Some(main.cached(content_style()).into_any_element());
self
}
/// Splits the row into two half-width panels,
pub fn split(mut self, panel: AnyView) -> Self {
self.split = Some(panel.cached(content_style()).into_any_element());
self
}
}
impl RenderOnce for Panel {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let app_background = theme.colors.muted;
let id = self.id.clone();
let main = island(
div()
.size_full()
.child(self.main.unwrap_or_else(|| div().into_any_element())),
cx,
);
let row = match self.split {
Some(split) => {
let sizes = window.with_element_namespace(id.clone(), |window| {
window
.use_keyed_state("panel-sizes", cx, |_, _| ResizableState::default())
.clone()
});
div().w_full().h_full().child(
Resizable::new((id.clone(), "split"), sizes)
.axis(Axis::Horizontal)
.pane(main)
.pane(island(div().size_full().child(split), cx))
.h_full(),
)
}
None => div().w_full().h_full().child(main),
};
div()
.flex_1()
.min_w_0()
.h_full()
.p_2()
.bg(app_background)
.child(row)
}
}
+2 -4
View File
@@ -14,6 +14,7 @@ use crate::resize_handle::ResizeHandle;
type DebugSelector = std::rc::Rc<dyn Fn() -> String>;
/// The retained pane sizes of one resizable group.
#[derive(Default)]
pub struct ResizableState {
/// Sizes of every pane except the remainder pane, which fills what's left.
sizes: Vec<Pixels>,
@@ -24,10 +25,7 @@ pub struct ResizableState {
impl ResizableState {
/// Creates state whose panes start at the default size.
pub fn new(cx: &mut App) -> Entity<Self> {
cx.new(|_| Self {
sizes: Vec::new(),
measured: None,
})
cx.new(|_| Self::default())
}
/// The stored size of each fixed pane; the remainder pane isn't listed.
+20 -19
View File
@@ -1,4 +1,5 @@
//! The drag divider: a thin handle that resizes the adjacent region.
//! The drag divider: a thin handle in the gap between panels that resizes
//! them. It shows its hairline only while hovered or dragged.
use std::rc::Rc;
@@ -8,11 +9,9 @@ use gpui::{
InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, Styled as _, Window, canvas, deferred, div,
fill, point, px,
};
use gpui_native_theme::{
ActiveTheme as _, BORDER_WIDTH, HAIRLINE_WIDTH, RESIZE_KEYBOARD_STEP, Size,
fill, point, px, rems,
};
use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, HAIRLINE_WIDTH, RESIZE_KEYBOARD_STEP};
use gpui_native_utils::{focus_handle, focus_ring};
/// How far one keyboard arrow step moves the seam.
@@ -100,12 +99,8 @@ impl ResizeHandle {
impl RenderOnce for ResizeHandle {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let border = theme.colors.border;
let ring = theme.colors.ring;
let thickness = theme.sizes.resolve(Size::default()).dense_padding_x;
// Half the handle overlaps each pane so the hairline lands on their shared boundary,
// leaving the handle no layout footprint of its own.
let straddle = -thickness / 2.0;
let thickness = rems(0.5).to_pixels(window.rem_size());
let label = self
.accessibility_label
@@ -141,10 +136,10 @@ impl RenderOnce for ResizeHandle {
.aria_label(label)
.flex_none()
.when(axis == Axis::Horizontal, |handle| {
handle.w(thickness).h_full().mx(straddle)
handle.w(thickness).h_full()
})
.when(axis == Axis::Vertical, |handle| {
handle.w_full().h(thickness).my(straddle)
handle.w_full().h(thickness)
})
.when(self.disabled, |handle| handle.opacity(0.5))
.when(!self.disabled, |handle| {
@@ -153,6 +148,14 @@ impl RenderOnce for ResizeHandle {
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(ring)))
.on_mouse_down_out({
let focus = focus.clone();
move |_, window, cx| {
if focus.is_focused(window) {
window.blur(cx);
}
}
})
.on_mouse_down(MouseButton::Left, {
let drag = drag.clone();
let focus = focus.clone();
@@ -211,16 +214,14 @@ impl RenderOnce for ResizeHandle {
let on_resize = self.on_resize.clone();
move |_, (hitbox, bounds), window, _cx| {
let hovered = hitbox.is_hovered(window);
if !disabled {
window.set_cursor_style(cursor, &hitbox);
}
// The hairline highlights while hovered or dragged.
let line_color = if !disabled && (dragging || hovered) {
ring
} else {
border
};
if disabled || !(dragging || hovered) {
return;
}
let line = match axis {
Axis::Horizontal => {
@@ -239,7 +240,7 @@ impl RenderOnce for ResizeHandle {
}
};
window.paint_quad(fill(line, line_color));
window.paint_quad(fill(line, ring));
window.on_mouse_event({
let drag = drag.clone();
+43 -426
View File
@@ -1,487 +1,104 @@
//! The application shell: an optional titlebar above a left sidebar (on by
//! default), a right sidebar (off by default), and the center region that
//! hosts the dock.
//! The application shell: the titlebar above the panel row, wrapped in the
//! client-side window frame, with the toast and alert overlays mounted at
//! the window root.
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, ElementId, Entity, InteractiveElement as _,
IntoElement, ParentElement as _, Pixels, RenderOnce, SharedString, Styled as _, Window, div,
px,
AnyElement, App, ElementId, Entity, IntoElement, ParentElement as _, RenderOnce, Styled as _,
Window, div,
};
#[cfg(feature = "alert")]
use gpui_native_core::alert::{Alert, Alerts, AlertsView};
use gpui_native_core::button::{Button, ButtonVariant};
use gpui_native_core::common::{Sizable as _, h_flex, v_flex};
use gpui_native_core::alert::{Alerts, AlertsView};
#[cfg(feature = "toast")]
use gpui_native_core::toast::{Toast, Toasts, ToastsView};
use gpui_native_data::sidebar::Sidebar;
use gpui_native_icons::IconRole;
use gpui_native_theme::{
ActiveTheme as _, SIDEBAR_DEFAULT_WIDTH, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH, Size,
};
use gpui_native_core::toast::{Toasts, ToastsView};
use gpui_native_utils::v_flex;
use crate::resize_handle::ResizeHandle;
use crate::titlebar::Titlebar;
use crate::window_controls::{TRAFFIC_LIGHT_PAD, WindowControls, titlebar_strip};
use crate::window_frame::frame;
/// The layout the application owns.
pub struct LayoutState {
left_visible: bool,
right_visible: bool,
left_width: Pixels,
right_width: Pixels,
#[cfg(feature = "toast")]
toasts: Entity<Toasts>,
#[cfg(feature = "alert")]
alerts: Entity<Alerts>,
}
impl LayoutState {
/// Creates the state: left sidebar visible, right sidebar hidden.
pub fn new(cx: &mut App) -> Entity<Self> {
cx.new(|_cx| Self {
left_visible: true,
right_visible: false,
left_width: SIDEBAR_DEFAULT_WIDTH,
right_width: SIDEBAR_DEFAULT_WIDTH,
#[cfg(feature = "toast")]
toasts: _cx.new(|_| Toasts::default()),
#[cfg(feature = "alert")]
alerts: _cx.new(|_| Alerts::default()),
})
}
/// Shows or hides the left sidebar.
pub fn set_left_sidebar_visible(&mut self, visible: bool, cx: &mut Context<Self>) {
if self.left_visible != visible {
self.left_visible = visible;
cx.notify();
}
}
/// Shows or hides the right sidebar.
pub fn set_right_sidebar_visible(&mut self, visible: bool, cx: &mut Context<Self>) {
if self.right_visible != visible {
self.right_visible = visible;
cx.notify();
}
}
/// Opens the left sidebar when closed, closes it when open.
pub fn toggle_left_sidebar(&mut self, cx: &mut Context<Self>) {
self.set_left_sidebar_visible(!self.left_visible, cx);
}
/// Opens the right sidebar when closed, closes it when open.
pub fn toggle_right_sidebar(&mut self, cx: &mut Context<Self>) {
self.set_right_sidebar_visible(!self.right_visible, cx);
}
/// Whether the left sidebar is visible.
pub fn is_left_sidebar_visible(&self) -> bool {
self.left_visible
}
/// Whether the right sidebar is visible.
pub fn is_right_sidebar_visible(&self) -> bool {
self.right_visible
}
/// The left sidebar's current width.
pub fn left_sidebar_width(&self) -> Pixels {
self.left_width
}
/// The right sidebar's current width.
pub fn right_sidebar_width(&self) -> Pixels {
self.right_width
}
/// Applies a drag delta to the left sidebar's width, clamped.
fn resize_left(&mut self, delta: Pixels, cx: &mut Context<Self>) {
let width = (self.left_width + delta).clamp(SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH);
if (self.left_width - width).abs() > px(f32::EPSILON) {
self.left_width = width;
cx.notify();
}
}
/// Applies a drag delta to the right sidebar's width, clamped.
fn resize_right(&mut self, delta: Pixels, cx: &mut Context<Self>) {
let width = (self.right_width - delta).clamp(SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH);
if (self.right_width - width).abs() > px(f32::EPSILON) {
self.right_width = width;
cx.notify();
}
}
/// Raises a toast in the shell's overlay. Returns its id.
#[cfg(feature = "toast")]
pub fn push_toast(&mut self, toast: Toast, cx: &mut Context<Self>) -> usize {
self.toasts.update(cx, |toasts, cx| toasts.push(toast, cx))
}
/// Dismisses one toast by id.
#[cfg(feature = "toast")]
pub fn dismiss_toast(&mut self, id: usize, cx: &mut Context<Self>) {
self.toasts.update(cx, |toasts, cx| toasts.dismiss(id, cx));
}
/// Dismisses the toast on screen.
#[cfg(feature = "toast")]
pub fn clear_toasts(&mut self, cx: &mut Context<Self>) {
self.toasts.update(cx, |toasts, cx| toasts.clear(cx));
}
/// Pushes an alert onto the shell's stack. Returns its id.
#[cfg(feature = "alert")]
pub fn push_alert(&mut self, alert: Alert, cx: &mut Context<Self>) -> usize {
self.alerts.update(cx, |alerts, cx| alerts.push(alert, cx))
}
/// Dismisses one alert by id, running its dismiss handler.
#[cfg(feature = "alert")]
pub fn dismiss_alert(&mut self, id: usize, cx: &mut Context<Self>) {
self.alerts.update(cx, |alerts, cx| alerts.dismiss(id, cx));
}
/// Dismisses every alert, running each entry's `on_dismiss` handler.
#[cfg(feature = "alert")]
pub fn clear_alerts(&mut self, cx: &mut Context<Self>) {
self.alerts.update(cx, |alerts, cx| alerts.clear(cx));
}
}
/// Which sidebar a region or toggle belongs to.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Side {
Left,
Right,
}
impl Side {
fn name(self) -> &'static str {
match self {
Side::Left => "left",
Side::Right => "right",
}
}
}
/// The application shell.
#[derive(IntoElement)]
#[must_use]
pub struct Shell {
id: ElementId,
state: Entity<LayoutState>,
/// The titlebar drawn above the regions, replacing the strips.
titlebar: Option<Titlebar>,
left_sidebar: Option<Sidebar>,
right_sidebar: Option<AnyElement>,
center: Option<AnyElement>,
/// Whether the left strip renders the default sidebar toggle.
toggle_button: bool,
panel: Option<AnyElement>,
#[cfg(feature = "toast")]
toasts: Option<Entity<Toasts>>,
#[cfg(feature = "alert")]
alerts: Option<Entity<Alerts>>,
}
impl Shell {
/// Creates the shell bound to `state`.
pub fn new<I>(id: I, state: Entity<LayoutState>) -> Self
/// Creates the shell.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
state,
titlebar: None,
left_sidebar: None,
right_sidebar: None,
center: None,
toggle_button: true,
panel: None,
#[cfg(feature = "toast")]
toasts: None,
#[cfg(feature = "alert")]
alerts: None,
}
}
/// Renders the default sidebar toggle in the left strip's trailing end.
pub fn toggle_button(mut self, toggle_button: bool) -> Self {
self.toggle_button = toggle_button;
self
}
/// Sets the titlebar drawn above the regions, disabling the sidebar strips.
/// Sets the titlebar drawn above the panel row.
pub fn titlebar(mut self, titlebar: Titlebar) -> Self {
self.titlebar = Some(titlebar);
self
}
/// Sets the left sidebar's navigation list.
pub fn left_sidebar(mut self, sidebar: Sidebar) -> Self {
self.left_sidebar = Some(sidebar);
self
}
/// Sets the right sidebar's content: a details or inspector pane.
pub fn right_sidebar<E>(mut self, content: E) -> Self
/// Sets the panel row filling the rest of the window.
pub fn panel<E>(mut self, panel: E) -> Self
where
E: IntoElement,
{
self.right_sidebar = Some(content.into_any_element());
self.panel = Some(panel.into_any_element());
self
}
/// Sets the center region's content, which hosts the dock.
pub fn center<E>(mut self, content: E) -> Self
where
E: IntoElement,
{
self.center = Some(content.into_any_element());
/// Hosts the toast overlay raised on `toasts`.
#[cfg(feature = "toast")]
pub fn toasts(mut self, toasts: Entity<Toasts>) -> Self {
self.toasts = Some(toasts);
self
}
/// Hosts the alert overlay stacked on `alerts`.
#[cfg(feature = "alert")]
pub fn alerts(mut self, alerts: Entity<Alerts>) -> Self {
self.alerts = Some(alerts);
self
}
}
impl RenderOnce for Shell {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(Size::default());
let background = theme.colors.background;
let titlebar_height = theme.titlebar_height;
let id = self.id.clone();
let state = self.state;
let titlebar = self.titlebar;
let mut left = self.left_sidebar;
let mut right = self.right_sidebar;
let mut center = self.center;
let left_visible = state.read(cx).is_left_sidebar_visible();
let right_visible = state.read(cx).is_right_sidebar_visible();
let left_material = left
.as_ref()
.is_some_and(|sidebar| sidebar.is_transparent());
// A titlebar carries the strips' window duties,
// so the strips only render when it is absent.
let left_strip = titlebar.is_none().then_some(Strip {
side: Side::Left,
height: titlebar_height,
padding_x: metrics.dense_padding_x,
toggle: self.toggle_button,
});
// A titlebar carries the strips' window duties,
// so the strips only render when it is absent.
let right_strip = titlebar.is_none().then_some(Strip {
side: Side::Right,
height: titlebar_height,
padding_x: metrics.dense_padding_x,
toggle: false,
});
let row = div()
.flex()
.flex_row()
.w_full()
.flex_1()
.min_h_0()
.overflow_hidden()
.when(left_visible && left.is_some(), |row| {
let width = state.read(cx).left_sidebar_width();
row.child(
v_flex()
.w(width)
.h_full()
.overflow_hidden()
.when(!left_material, |region| region.bg(background))
.child(
left.take()
.map(|sidebar| {
sidebar
.when_some(left_strip, |sidebar, strip| {
sidebar.strip(sidebar_strip(
(id.clone(), "left"),
strip,
&state,
window,
cx,
))
})
.into_any_element()
})
.unwrap_or_else(|| div().into_any_element()),
),
)
.child(ResizeHandle::new((id.clone(), "left-resize")).on_resize({
let state = state.clone();
move |delta, _, cx| {
state.update(cx, |state, cx| state.resize_left(delta, cx));
}
}))
})
.child(
div()
.flex_1()
.h_full()
.min_w_0()
.overflow_hidden()
.bg(background)
.child(center.take().unwrap_or_else(|| div().into_any_element())),
)
.when(right_visible && right.is_some(), |row| {
let width = state.read(cx).right_sidebar_width();
row.child(ResizeHandle::new((id.clone(), "right-resize")).on_resize({
let state = state.clone();
move |delta, _, cx| {
state.update(cx, |state, cx| state.resize_right(delta, cx));
}
}))
.child(sidebar_region(
(id.clone(), "right"),
width,
right.take().unwrap_or_else(|| div().into_any_element()),
&state,
right_strip,
window,
cx,
))
});
let layout = v_flex()
.w_full()
.h_full()
.overflow_hidden()
.when_some(titlebar, |layout, titlebar| layout.child(titlebar))
.child(row);
.when_some(self.titlebar, |layout, titlebar| layout.child(titlebar))
.child(self.panel.unwrap_or_else(|| div().into_any_element()));
// Wraps the layout in a window frame
let frame = frame(layout, window, cx);
#[cfg(feature = "toast")]
let frame = frame.child(ToastsView::new(
(id.clone(), "toasts"),
state.read(cx).toasts.clone(),
));
let frame = frame.when_some(self.toasts, |frame, toasts| {
frame.child(ToastsView::new((id.clone(), "toasts"), toasts))
});
#[cfg(feature = "alert")]
let frame = frame.child(AlertsView::new(
(id, "alerts"),
state.read(cx).alerts.clone(),
));
let frame = frame.when_some(self.alerts, |frame, alerts| {
frame.child(AlertsView::new((id, "alerts"), alerts))
});
frame
}
}
/// One sidebar show/hide toggle.
fn sidebar_toggle_button<I>(id: I, side: Side, state: &Entity<LayoutState>, cx: &App) -> Button
where
I: Into<ElementId>,
{
let name = side.name();
let visible = match side {
Side::Left => state.read(cx).is_left_sidebar_visible(),
Side::Right => state.read(cx).is_right_sidebar_visible(),
};
Button::new(id)
.icon(match side {
Side::Left => IconRole::PanelLeft,
Side::Right => IconRole::PanelRight,
})
.variant(ButtonVariant::Ghost)
.small()
.accessibility_label(SharedString::from(format!(
"{} {} sidebar",
if visible { "Hide" } else { "Show" },
name,
)))
.debug_selector(move || format!("sidebar-toggle-{}", name))
.on_click({
let state = state.clone();
move |_, _, cx| match side {
Side::Left => state.update(cx, LayoutState::toggle_left_sidebar),
Side::Right => state.update(cx, LayoutState::toggle_right_sidebar),
}
})
}
/// Which titlebar duties a sidebar's header strip carries.
#[derive(Clone, Copy)]
struct Strip {
side: Side,
height: Pixels,
padding_x: Pixels,
/// Whether the strip carries the sidebar's hide toggle.
toggle: bool,
}
fn sidebar_region<I>(
id: I,
width: Pixels,
content: AnyElement,
state: &Entity<LayoutState>,
strip: Option<Strip>,
window: &mut Window,
cx: &mut App,
) -> AnyElement
where
I: Into<ElementId>,
{
let background = cx.theme().colors.background;
v_flex()
.w(width)
.h_full()
.overflow_hidden()
.bg(background)
.when_some(strip, |region, strip| {
region.child(sidebar_strip(id, strip, state, window, cx))
})
.child(div().flex_1().min_h_0().overflow_hidden().child(content))
.into_any_element()
}
fn sidebar_strip<I>(
id: I,
strip: Strip,
state: &Entity<LayoutState>,
window: &mut Window,
cx: &mut App,
) -> AnyElement
where
I: Into<ElementId>,
{
let id = id.into();
h_flex()
.id((id.clone(), "strip"))
.debug_selector(move || format!("sidebar-strip-{}", strip.side.name()))
.flex_none()
.h(strip.height)
.occlude()
.items_center()
.px(strip.padding_x)
.when(
cfg!(target_os = "macos") && strip.side == Side::Left,
|row| row.pl(TRAFFIC_LIGHT_PAD),
)
.child(titlebar_strip(
div().id((id.clone(), "strip-drag")).flex_1().self_stretch(),
(id.clone(), "strip-drag"),
window,
cx,
))
.when(strip.side == Side::Left && strip.toggle, |row| {
row.child(sidebar_toggle_button(
(id.clone(), "sidebar-toggle"),
Side::Left,
state,
cx,
))
})
.when(strip.side == Side::Right, |row| {
row.child(WindowControls::new((id, "window-controls")))
})
.into_any_element()
}
+81 -31
View File
@@ -1,6 +1,8 @@
//! The window titlebar: the full-width strip drawn above the shell's regions;
//! it moves the window, hosts the window controls, and leads with the app's
//! own children.
//! The window titlebar: the full-width strip drawn above the panel row —
//! the prefix, tab bar, and suffix in the middle, the platform's window
//! controls at macOS's leading edge and every other platform's trailing
//! edge. The bar itself moves the window, tab bar included; the prefix and
//! suffix opt out, so a press on a control never starts a drag.
use gpui::prelude::FluentBuilder as _;
use gpui::{
@@ -17,7 +19,9 @@ use crate::window_controls::{WindowControls, titlebar_strip};
#[must_use]
pub struct Titlebar {
id: ElementId,
children: Vec<AnyElement>,
prefix: Vec<AnyElement>,
tab_bar: Option<AnyElement>,
suffix: Vec<AnyElement>,
}
impl Titlebar {
@@ -28,50 +32,96 @@ impl Titlebar {
{
Self {
id: id.into(),
children: Vec::new(),
prefix: Vec::new(),
tab_bar: None,
suffix: Vec::new(),
}
}
/// Sets the tab bar drawn between the prefix and the suffix.
pub fn tab_bar<E>(mut self, tab_bar: E) -> Self
where
E: IntoElement,
{
self.tab_bar = Some(tab_bar.into_any_element());
self
}
/// Sets the element drawn after the tab bar, before the trailing window controls.
pub fn suffix<E>(mut self, suffix: E) -> Self
where
E: IntoElement,
{
self.suffix = vec![suffix.into_any_element()];
self
}
}
impl ParentElement for Titlebar {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
self.prefix.extend(elements);
}
}
impl RenderOnce for Titlebar {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let background = theme.colors.background;
let app_background = theme.colors.muted;
let height = theme.titlebar_height;
let padding_x = theme.sizes.resolve(Size::default()).dense_padding_x;
let id = self.id;
let bar_id = SharedString::from(format!("{id}-bar"));
h_flex()
.id(id.clone())
.debug_selector(move || bar_id.to_string())
.flex_none()
.w_full()
.h(height)
.occlude()
.bg(background)
.px(padding_x)
.when(cfg!(target_os = "macos"), |bar| bar.pl(TRAFFIC_LIGHT_PAD))
.child(
h_flex()
.min_w_0()
.gap_1()
.overflow_hidden()
.children(self.children),
)
.child(titlebar_strip(
div().id((id.clone(), "drag")).flex_1().self_stretch(),
(id.clone(), "drag"),
window,
cx,
))
.child(WindowControls::new((id, "window-controls")))
titlebar_strip(
h_flex()
.id(id.clone())
.debug_selector(move || bar_id.to_string())
.flex_none()
.w_full()
.h(height)
.bg(app_background)
.px(padding_x)
.when(cfg!(target_os = "macos"), |bar| bar.pl(TRAFFIC_LIGHT_PAD))
.when(!self.prefix.is_empty(), |bar| {
bar.child(
h_flex()
.occlude()
.flex_none()
.h_full()
.items_center()
.gap_1()
.children(self.prefix),
)
})
.when_some(self.tab_bar, |bar, tab_bar| {
bar.child(
div()
.flex()
.flex_1()
.min_w_0()
.h_full()
.items_center()
.overflow_hidden()
.when(cfg!(target_os = "windows"), |slot| slot.occlude())
.child(tab_bar),
)
})
.when(!self.suffix.is_empty(), |bar| {
bar.child(
h_flex()
.occlude()
.flex_none()
.h_full()
.items_center()
.gap_1()
.children(self.suffix),
)
}),
(id.clone(), "drag"),
window,
cx,
)
.child(WindowControls::new((id, "window-controls")))
}
}
View File
+151
View File
@@ -0,0 +1,151 @@
#![cfg(feature = "panel")]
//! The panel row: the main island fills the window; splitting makes two
//! half-width islands with a drag divider that resizes them.
use gpui::{
AnyView, AppContext as _, Context, InteractiveElement as _, IntoElement, Modifiers,
MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Render,
SharedString, Styled as _, TestAppContext, VisualTestContext, Window, div, point, px, size,
};
use gpui_native_layout::panel::Panel;
use gpui_native_theme::Theme;
const WINDOW_WIDTH: f32 = 1024.0;
const WINDOW_HEIGHT: f32 = 768.0;
/// A full-size marker the tests measure through its debug selector.
struct TagView {
selector: SharedString,
}
impl TagView {
fn new(selector: &'static str) -> Self {
Self {
selector: SharedString::from(selector),
}
}
}
impl Render for TagView {
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()
}
}
struct PanelHarness {
split: bool,
main: AnyView,
split_view: AnyView,
}
impl Render for PanelHarness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let panel = Panel::new("panel-harness").main(self.main.clone());
let panel = if self.split {
panel.split(self.split_view.clone())
} else {
panel
};
div().size_full().child(panel)
}
}
fn panel_window(cx: &mut TestAppContext, split: bool) -> VisualTestContext {
let (main, split_view) = cx.update(|cx| {
Theme::init(cx);
let main = cx.new(|_| TagView::new("panel-test-main"));
let split = cx.new(|_| TagView::new("panel-test-split"));
(main, split)
});
let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, _| {
PanelHarness {
split,
main: main.into(),
split_view: split_view.into(),
}
});
let cx = VisualTestContext::from_window(window.into(), cx);
cx.run_until_parked();
cx
}
#[gpui::test]
fn main_fills_the_row_without_a_split(cx: &mut TestAppContext) {
let mut cx = panel_window(cx, false);
let main = cx
.debug_bounds("panel-test-main")
.expect("main panel laid out");
// The row's padding and the island's inset are all main gives up.
assert!(main.size.width >= px(WINDOW_WIDTH - 40.0));
assert!(main.size.height >= px(WINDOW_HEIGHT - 40.0));
assert!(main.origin.x >= px(0.0));
}
#[gpui::test]
fn split_makes_two_half_width_panels(cx: &mut TestAppContext) {
let mut cx = panel_window(cx, true);
let main = cx
.debug_bounds("panel-test-main")
.expect("main panel laid out");
let split = cx
.debug_bounds("panel-test-split")
.expect("split panel laid out");
// Both islands share the row at half width, main first, and neither
// leaves the viewport. The divider's width lands on the remainder pane.
assert!(
(main.size.width - split.size.width).abs() <= px(10.0),
"main={:?} split={:?}",
main.size.width,
split.size.width
);
assert!(main.size.width < px(WINDOW_WIDTH / 2.0));
assert!(main.right() <= split.left());
assert!(split.right() <= px(WINDOW_WIDTH));
assert!(main.size.height >= px(WINDOW_HEIGHT - 40.0));
}
#[gpui::test]
fn dragging_the_divider_resizes_the_panels(cx: &mut TestAppContext) {
let mut cx = panel_window(cx, true);
let before = cx
.debug_bounds("panel-test-main")
.expect("main panel laid out");
// Press the divider between the islands and drag it 100px to the right.
let seam = point(before.right() + px(13.0), px(400.0));
cx.simulate_event(MouseDownEvent {
position: seam,
button: MouseButton::Left,
modifiers: Modifiers::default(),
click_count: 1,
first_mouse: false,
});
cx.simulate_event(MouseMoveEvent {
position: point(seam.x + px(100.0), seam.y),
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::default(),
});
cx.simulate_event(MouseUpEvent {
position: point(seam.x + px(100.0), seam.y),
button: MouseButton::Left,
modifiers: Modifiers::default(),
click_count: 1,
});
cx.run_until_parked();
// The main panel grew by the drag; the split panel gave up the space.
let after = cx
.debug_bounds("panel-test-main")
.expect("main panel laid out after the drag");
assert_eq!(after.size.width, before.size.width + px(100.0));
}