From 2d85db215b3affa15257cb1b7920b6f41b38b7dc Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Sun, 15 Nov 2026 10:08:24 +0700 Subject: [PATCH] layout: replace dock with simple titlebar and panel row --- Cargo.lock | 1 - crates/layout/Cargo.toml | 33 +- crates/layout/src/dock.rs | 1305 ---------------------------- crates/layout/src/lib.rs | 6 +- crates/layout/src/panel.rs | 108 +++ crates/layout/src/resizable.rs | 6 +- crates/layout/src/resize_handle.rs | 39 +- crates/layout/src/shell.rs | 469 +--------- crates/layout/src/titlebar.rs | 112 ++- crates/layout/tests/.keep | 0 crates/layout/tests/panel.rs | 151 ++++ docs/CHECKLIST.md | 30 +- examples/gallery/src/main.rs | 1018 +++++++++------------- 13 files changed, 836 insertions(+), 2442 deletions(-) delete mode 100644 crates/layout/src/dock.rs create mode 100644 crates/layout/src/panel.rs delete mode 100644 crates/layout/tests/.keep create mode 100644 crates/layout/tests/panel.rs diff --git a/Cargo.lock b/Cargo.lock index 0485ad9..7c655e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2032,7 +2032,6 @@ version = "0.1.0" dependencies = [ "gpui", "gpui-native-core", - "gpui-native-data", "gpui-native-icons", "gpui-native-theme", "gpui-native-utils", diff --git a/crates/layout/Cargo.toml b/crates/layout/Cargo.toml index 5011718..58c29a3 100644 --- a/crates/layout/Cargo.toml +++ b/crates/layout/Cargo.toml @@ -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"] diff --git a/crates/layout/src/dock.rs b/crates/layout/src/dock.rs deleted file mode 100644 index a054d2a..0000000 --- a/crates/layout/src/dock.rs +++ /dev/null @@ -1,1305 +0,0 @@ -//! The dock: the center pane tree — tabbed panes the app fills from -//! registered panels, split two ways, collapsing as tabs close. - -use std::collections::HashMap; -use std::rc::Rc; -use std::sync::Arc; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - AnyElement, AnyView, App, AppContext as _, Axis, Context, ElementId, Entity, - InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Render, RenderOnce, Role, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas, - div, px, relative, size, -}; -use gpui_native_core::common::{h_flex, v_flex}; -use gpui_native_core::context_menu::ContextMenu; -use gpui_native_core::menu::MenuItem; -use gpui_native_data::tabs::{Tab, Tabs, TabsVariant}; -use gpui_native_icons::IconRole; -use gpui_native_theme::{ActiveTheme as _, Size}; - -use crate::resize_handle::ResizeHandle; -use crate::window_controls::{TRAFFIC_LIGHT_PAD, WindowControls, titlebar_strip}; - -/// The narrowest either side of a split can get, as a fraction of the split. -const MIN_SPLIT_RATIO: f32 = 0.1; -/// The fraction a split opens at, and what a double-click on the seam restores. -const DEFAULT_SPLIT_RATIO: f32 = 0.5; - -/// Builds a panel's view entity the first time its tab opens. -type PanelBuilder = Box Arc>; -/// Runs when a panel with a right sidebar activates, so the app can open it. -type OpenRightSidebarHandler = Rc; - -/// A dockable panel. -#[allow(unused_variables)] -pub trait Panel: Render + 'static { - /// The panel's tab label. - fn title(&self, cx: &App) -> Option { - None - } - - /// An element, e.g. an icon or avatar, leading the tab label. - fn lead(&self, cx: &App) -> Option { - None - } - - /// The view the right sidebar shows while this panel is active. - /// - /// Activating the panel opens the right sidebar. - fn right_sidebar(&mut self, window: &mut Window, cx: &mut App) -> Option { - None - } -} - -/// Object-safe handle to an open panel entity. -pub trait PanelView: 'static { - /// The panel's view. - fn view(&self) -> AnyView; - /// The tab label, read live from the panel. - fn title(&self, cx: &App) -> Option; - /// The element leading the tab label, read live from the panel. - fn lead(&self, cx: &App) -> Option; - /// The right sidebar view, built through the panel. - fn right_sidebar(&self, window: &mut Window, cx: &mut App) -> Option; -} - -impl PanelView for Entity { - fn view(&self) -> AnyView { - self.clone().into() - } - - fn title(&self, cx: &App) -> Option { - self.read(cx).title(cx) - } - - fn lead(&self, cx: &App) -> Option { - self.read(cx).lead(cx) - } - - fn right_sidebar(&self, window: &mut Window, cx: &mut App) -> Option { - self.update(cx, |panel, cx| panel.right_sidebar(window, cx)) - } -} - -/// Which side of its pane a split places the new pane on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SplitDirection { - Left, - Right, - Top, - Bottom, -} - -impl SplitDirection { - fn axis(self) -> Axis { - match self { - Self::Left | Self::Right => Axis::Horizontal, - Self::Top | Self::Bottom => Axis::Vertical, - } - } - - /// Whether the new pane takes the split's leading slot. - fn leads(self) -> bool { - matches!(self, Self::Left | Self::Top) - } -} - -/// The payload a dock tab drags: the panel to move. -#[derive(Clone)] -pub struct PanelDrag { - pub panel: SharedString, -} - -/// The card that follows the cursor while a tab is dragged. -struct DragPreview { - title: Option, -} - -impl Render for DragPreview { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let theme = cx.theme(); - div() - .px_2() - .py_1() - .rounded(theme.radius.sm) - .border_1() - .border_color(theme.colors.border) - .bg(theme.colors.surface) - .text_size(theme.sizes.medium.text_size) - .text_color(theme.colors.foreground) - .opacity(0.85) - .children(self.title.clone()) - } -} - -/// One open panel: its dock id, live handle, and right sidebar view. -struct PanelTab { - panel: SharedString, - handle: Arc, - right_view: Option, -} - -/// A leaf: the tabs of one region and which is active. -struct Pane { - key: u64, - tabs: Vec, - active: Option, - overflow_open: bool, -} - -/// An internal node: two children along an axis. -struct Split { - key: u64, - axis: Axis, - ratio: f32, - a: Box, - b: Box, -} - -enum Node { - Pane(Pane), - Split(Split), -} - -/// The dock's pane tree, owned by the application. -pub struct DockState { - root: Node, - panels: HashMap, - /// The pane new panels open into, kept on the last activated pane. - active_pane: u64, - next_key: u64, - /// The right sidebar view on display, retained from its panel. - right_view: Option, - /// Runs when a panel with a right sidebar activates, so the app can open it. - on_open_right_sidebar: Option, -} - -impl DockState { - /// Creates a dock with one empty pane. - pub fn new(cx: &mut App) -> Entity { - cx.new(|_| Self { - root: Node::Pane(Pane { - key: 0, - tabs: Vec::new(), - active: None, - overflow_open: false, - }), - panels: HashMap::new(), - active_pane: 0, - next_key: 1, - right_view: None, - on_open_right_sidebar: None, - }) - } - - /// Runs when a panel with a right sidebar activates. - pub fn on_open_right_sidebar(&mut self, handler: impl Fn(&mut App) + 'static) { - self.on_open_right_sidebar = Some(Rc::new(handler)); - } - - /// Registers a panel under `id`, replacing any earlier one with it. - pub fn register_panel(&mut self, id: I, build: F) - where - I: Into, - F: Fn(&mut Window, &mut App) -> Entity

+ 'static, - P: Panel, - { - let build: PanelBuilder = Box::new(move |window, cx| { - let panel = build(window, cx); - Arc::new(panel) - }); - self.panels.insert(id.into(), build); - } - - /// Opens a panel into the active pane and activates its tab. - pub fn open_panel(&mut self, id: &str, window: &mut Window, cx: &mut Context) { - if self.is_open(id) { - self.activate_panel(id, cx); - return; - } - - let Some(build) = self.panels.get(id) else { - return; - }; - - let handle = build(window, cx); - let right_view = handle.right_sidebar(window, cx); - - let tab = PanelTab { - panel: SharedString::from(id), - handle, - right_view, - }; - - let pane_key = self.target_pane_key(); - - if let Some(pane) = self.pane_mut(pane_key) { - pane.tabs.push(tab); - pane.active = Some(SharedString::from(id)); - } - - self.active_pane = pane_key; - self.show_right_view_of(id, cx); - cx.notify(); - } - - /// Points the right sidebar at the panel's own view and asks the app to open it. - fn show_right_view_of(&mut self, id: &str, cx: &mut Context) { - let right_view = Self::tab_in(&self.root, id).and_then(|tab| tab.right_view.clone()); - let Some(right_view) = right_view else { - return; - }; - self.right_view = Some(right_view); - if let Some(handler) = self.on_open_right_sidebar.clone() { - (handler)(cx); - } - } - - /// Activates a panel's tab and makes its pane the active pane. - pub fn activate_panel(&mut self, id: &str, cx: &mut Context) { - let Some((pane_key, _)) = self.locate(id) else { - return; - }; - let changed = { - let Some(pane) = self.pane_mut(pane_key) else { - return; - }; - let changed = pane.active.as_deref() != Some(id); - if changed { - pane.active = Some(SharedString::from(id)); - } - changed - }; - self.active_pane = pane_key; - if changed { - self.show_right_view_of(id, cx); - cx.notify(); - } - } - - /// Closes a panel's tab. - pub fn close_panel(&mut self, id: &str, cx: &mut Context) { - let Some((pane_key, index)) = self.locate(id) else { - return; - }; - - let (closed_right_view, emptied) = { - let Some(pane) = self.pane_mut(pane_key) else { - return; - }; - - let was_active = pane.active.as_deref() == Some(id); - let closed = pane.tabs.remove(index); - - if was_active { - pane.active = pane - .tabs - .get(index) - .or_else(|| { - index - .checked_sub(1) - .and_then(|previous| pane.tabs.get(previous)) - }) - .map(|tab| tab.panel.clone()); - } - - (closed.right_view, pane.tabs.is_empty()) - }; - - // The sidebar showed the closed panel's view. - if self.right_view.as_ref() == closed_right_view.as_ref() { - self.right_view = Self::first_right_view(&self.root); - } - - if emptied { - self.detach_pane(pane_key); - if self.active_pane == pane_key { - self.active_pane = self.first_pane_key().unwrap_or(0); - } - } - - cx.notify(); - } - - /// Shows or hides the pane's overflow popover. - pub fn set_pane_overflow_open(&mut self, key: u64, open: bool, cx: &mut Context) { - let Some(pane) = self.pane_mut(key) else { - return; - }; - if pane.overflow_open != open { - pane.overflow_open = open; - cx.notify(); - } - } - - /// Closes every other tab in the panel's pane, keeping this one active. - pub fn close_others(&mut self, id: &str, cx: &mut Context) { - let Some((pane_key, _)) = self.locate(id) else { - return; - }; - - let changed = { - let Some(pane) = self.pane_mut(pane_key) else { - return; - }; - - let before = pane.tabs.len(); - pane.tabs.retain(|tab| tab.panel.as_ref() == id); - pane.active = Some(SharedString::from(id)); - pane.tabs.len() != before - }; - - if changed { - // The kept tab may have no right view, show the first remaining one. - self.right_view = self - .locate(id) - .and_then(|(pane_key, _)| self.pane(pane_key)) - .and_then(|pane| { - pane.active.as_deref().and_then(|active| { - pane.tabs.iter().find(|tab| tab.panel.as_ref() == active) - }) - }) - .and_then(|tab| tab.right_view.clone()) - .or_else(|| Self::first_right_view(&self.root)); - cx.notify(); - } - } - - /// Closes every tab in the panel's pane; a non-root pane collapses. - pub fn close_pane(&mut self, id: &str, cx: &mut Context) { - let Some((pane_key, _)) = self.locate(id) else { - return; - }; - - let was_empty = self - .pane_mut(pane_key) - .is_none_or(|pane| pane.tabs.is_empty()); - - if was_empty { - return; - } - - if let Some(pane) = self.pane_mut(pane_key) { - pane.tabs.clear(); - pane.active = None; - } - - self.detach_pane(pane_key); - - if self.active_pane == pane_key { - self.active_pane = self.first_pane_key().unwrap_or(0); - } - - // The closed pane's views are gone; show the first remaining one. - self.right_view = Self::first_right_view(&self.root); - - cx.notify(); - } - - /// Moves a panel's tab into a new pane on `direction`'s side of its pane. - pub fn split_panel(&mut self, id: &str, direction: SplitDirection, cx: &mut Context) { - self.split_panel_at(id, id, direction, cx); - } - - /// Moves a panel's tab into a new pane on `direction`. - pub fn split_panel_at( - &mut self, - id: &str, - anchor: &str, - direction: SplitDirection, - cx: &mut Context, - ) { - let (Some((source_key, index)), Some((target_key, _))) = - (self.locate(id), self.locate(anchor)) - else { - return; - }; - - let tab = { - let Some(pane) = self.pane_mut(source_key) else { - return; - }; - - let tab = pane.tabs.remove(index); - if pane.active.as_deref() == Some(id) { - pane.active = pane - .tabs - .get(index) - .or_else(|| { - index - .checked_sub(1) - .and_then(|previous| pane.tabs.get(previous)) - }) - .map(|remaining| remaining.panel.clone()); - } - - tab - }; - - let emptied = self - .pane_mut(source_key) - .is_none_or(|pane| pane.tabs.is_empty()); - - let new_key = self.next_key; - let split_key = self.next_key + 1; - self.next_key += 2; - - let new_pane = Node::Pane(Pane { - key: new_key, - tabs: vec![tab], - active: Some(SharedString::from(id)), - overflow_open: false, - }); - - Self::wrap_in(&mut self.root, target_key, new_pane, direction, split_key); - - if emptied { - self.detach_pane(source_key); - } - - self.active_pane = new_key; - cx.notify(); - } - - /// Moves a panel's tab into the pane holding `anchor`, appended last. - pub fn move_panel(&mut self, id: &str, anchor: &str, cx: &mut Context) { - let (Some((source_key, index)), Some((target_key, _))) = - (self.locate(id), self.locate(anchor)) - else { - return; - }; - - if source_key == target_key { - return; - } - - let tab = { - let Some(pane) = self.pane_mut(source_key) else { - return; - }; - let tab = pane.tabs.remove(index); - - if pane.active.as_deref() == Some(id) { - pane.active = pane - .tabs - .get(index) - .or_else(|| { - index - .checked_sub(1) - .and_then(|previous| pane.tabs.get(previous)) - }) - .map(|remaining| remaining.panel.clone()); - } - tab - }; - - if let Some(pane) = self.pane_mut(target_key) { - pane.tabs.push(tab); - pane.active = Some(SharedString::from(id)); - } - - let emptied = self - .pane_mut(source_key) - .is_none_or(|pane| pane.tabs.is_empty()); - - if emptied { - self.detach_pane(source_key); - if self.active_pane == source_key { - self.active_pane = self.first_pane_key().unwrap_or(0); - } - } - - self.active_pane = target_key; - cx.notify(); - } - - /// The active tab of the pane new panels open into. - pub fn active_panel(&self) -> Option { - let pane = Self::pane_in(&self.root, self.target_pane_key())?; - pane.active.clone() - } - - /// Whether a panel's tab is open anywhere in the tree. - pub fn is_open(&self, id: &str) -> bool { - self.locate(id).is_some() - } - - fn locate(&self, id: &str) -> Option<(u64, usize)> { - Self::locate_in(&self.root, id) - } - - fn locate_in(node: &Node, id: &str) -> Option<(u64, usize)> { - match node { - Node::Pane(pane) => pane - .tabs - .iter() - .position(|tab| tab.panel.as_ref() == id) - .map(|index| (pane.key, index)), - Node::Split(split) => { - Self::locate_in(&split.a, id).or_else(|| Self::locate_in(&split.b, id)) - } - } - } - - fn target_pane_key(&self) -> u64 { - if Self::pane_in(&self.root, self.active_pane).is_some() { - self.active_pane - } else { - self.first_pane_key().unwrap_or(0) - } - } - - fn first_pane_key(&self) -> Option { - Self::first_pane_in(&self.root) - } - - fn first_pane_in(node: &Node) -> Option { - match node { - Node::Pane(pane) => Some(pane.key), - Node::Split(split) => { - Self::first_pane_in(&split.a).or_else(|| Self::first_pane_in(&split.b)) - } - } - } - - fn pane(&self, key: u64) -> Option<&Pane> { - Self::pane_in(&self.root, key) - } - - fn pane_in(node: &Node, key: u64) -> Option<&Pane> { - match node { - Node::Pane(pane) => (pane.key == key).then_some(pane), - Node::Split(split) => { - Self::pane_in(&split.a, key).or_else(|| Self::pane_in(&split.b, key)) - } - } - } - - fn pane_mut(&mut self, key: u64) -> Option<&mut Pane> { - Self::pane_mut_in(&mut self.root, key) - } - - fn pane_mut_in(node: &mut Node, key: u64) -> Option<&mut Pane> { - match node { - Node::Pane(pane) => (pane.key == key).then_some(pane), - Node::Split(split) => Self::pane_mut_in(&mut split.a, key) - .or_else(|| Self::pane_mut_in(&mut split.b, key)), - } - } - - fn split_mut(node: &mut Node, key: u64) -> Option<&mut Split> { - let Node::Split(split) = node else { - return None; - }; - if split.key == key { - return Some(split); - } - Self::split_mut(&mut split.a, key).or_else(|| Self::split_mut(&mut split.b, key)) - } - - /// Nudges a split's ratio by `fraction`, clamped at both ends. - fn resize_split(&mut self, key: u64, fraction: f32, cx: &mut Context) { - let Some(split) = Self::split_mut(&mut self.root, key) else { - return; - }; - - let ratio = (split.ratio + fraction).clamp(MIN_SPLIT_RATIO, 1.0 - MIN_SPLIT_RATIO); - - if (split.ratio - ratio).abs() > f32::EPSILON { - split.ratio = ratio; - cx.notify(); - } - } - - /// Restores a split to its default ratio. - fn reset_split(&mut self, key: u64, cx: &mut Context) { - let Some(split) = Self::split_mut(&mut self.root, key) else { - return; - }; - - if (split.ratio - DEFAULT_SPLIT_RATIO).abs() > f32::EPSILON { - split.ratio = DEFAULT_SPLIT_RATIO; - cx.notify(); - } - } - - /// Replaces a pane with a split holding it and `new_pane`. - fn wrap_in( - node: &mut Node, - key: u64, - new_pane: Node, - direction: SplitDirection, - split_key: u64, - ) { - match node { - Node::Pane(pane) if pane.key == key => { - let old_pane = Self::take_node(node); - let split = if direction.leads() { - Split { - key: split_key, - axis: direction.axis(), - ratio: DEFAULT_SPLIT_RATIO, - a: Box::new(new_pane), - b: Box::new(old_pane), - } - } else { - Split { - key: split_key, - axis: direction.axis(), - ratio: DEFAULT_SPLIT_RATIO, - a: Box::new(old_pane), - b: Box::new(new_pane), - } - }; - *node = Node::Split(split); - } - Node::Pane(_) => {} - Node::Split(split) => { - if Self::pane_in(&split.a, key).is_some() { - Self::wrap_in(&mut split.a, key, new_pane, direction, split_key); - } else if Self::pane_in(&split.b, key).is_some() { - Self::wrap_in(&mut split.b, key, new_pane, direction, split_key); - } - } - } - } - - /// Removes a pane and replaces its parent split with the sibling subtree. - fn detach_pane(&mut self, key: u64) { - Self::detach_in(&mut self.root, key); - } - - fn detach_in(node: &mut Node, key: u64) { - let Node::Split(split) = node else { - return; - }; - - let a_direct = Self::direct_pane_key(&split.a) == Some(key); - let b_direct = Self::direct_pane_key(&split.b) == Some(key); - - if a_direct != b_direct { - let survivor = if a_direct { - Self::take_node(&mut split.b) - } else { - Self::take_node(&mut split.a) - }; - *node = survivor; - } else { - Self::detach_in(&mut split.a, key); - Self::detach_in(&mut split.b, key); - } - } - - /// The tree the dock renders from. - fn snapshot(&self) -> TreeView { - fn snap(node: &Node) -> TreeView { - match node { - Node::Pane(pane) => TreeView::Pane(PaneView { - key: pane.key, - tabs: pane - .tabs - .iter() - .map(|tab| TabView { - panel: tab.panel.clone(), - handle: tab.handle.clone(), - }) - .collect(), - active: pane.active.clone(), - overflow_open: pane.overflow_open, - }), - Node::Split(split) => TreeView::Split(SplitView { - key: split.key, - axis: split.axis, - ratio: split.ratio, - a: Box::new(snap(&split.a)), - b: Box::new(snap(&split.b)), - }), - } - } - snap(&self.root) - } - - /// Finds an open tab by panel id, anywhere in the tree. - fn tab_in<'a>(node: &'a Node, id: &str) -> Option<&'a PanelTab> { - match node { - Node::Pane(pane) => pane.tabs.iter().find(|tab| tab.panel.as_ref() == id), - Node::Split(split) => Self::tab_in(&split.a, id).or_else(|| Self::tab_in(&split.b, id)), - } - } - - /// The first open tab's right sidebar view, in display order. - fn first_right_view(node: &Node) -> Option { - match node { - Node::Pane(pane) => pane.tabs.iter().find_map(|tab| tab.right_view.clone()), - Node::Split(split) => { - Self::first_right_view(&split.a).or_else(|| Self::first_right_view(&split.b)) - } - } - } - - /// The pane key of a node that is a pane, for seam-level tree edits. - fn direct_pane_key(node: &Node) -> Option { - match node { - Node::Pane(pane) => Some(pane.key), - Node::Split(_) => None, - } - } - - /// Takes a node out, leaving a placeholder that is never read again. - fn take_node(node: &mut Node) -> Node { - std::mem::replace( - node, - Node::Pane(Pane { - key: u64::MAX, - tabs: Vec::new(), - active: None, - overflow_open: false, - }), - ) - } -} - -/// One open panel's handle, per frame. -#[derive(Clone)] -struct TabView { - panel: SharedString, - handle: Arc, -} - -#[derive(Clone)] -struct PaneView { - key: u64, - tabs: Vec, - active: Option, - overflow_open: bool, -} - -struct SplitView { - key: u64, - axis: Axis, - ratio: f32, - a: Box, - b: Box, -} - -enum TreeView { - Pane(PaneView), - Split(SplitView), -} - -/// A dock: renders the pane tree of a [`DockState`]. -#[derive(IntoElement)] -#[must_use] -pub struct Dock { - id: ElementId, - state: Entity, - /// The pill bar is the window's titlebar: trailing window controls. - window_controls: bool, - /// The pill bar leads the window: pad for the macOS traffic lights. - traffic_light_pad: bool, - /// Builds the pill bar's leading element on each frame. - tab_prefix: Option AnyElement>>, - /// Builds the pill bar's trailing element on each frame. - tab_suffix: Option AnyElement>>, -} - -impl Dock { - /// Creates a dock bound to `state`. - pub fn new(id: I, state: Entity) -> Self - where - I: Into, - { - Self { - id: id.into(), - state, - window_controls: false, - traffic_light_pad: false, - tab_prefix: None, - tab_suffix: None, - } - } - - /// Renders the window controls in the pill bar's trailing end. - pub fn window_controls(mut self, window_controls: bool) -> Self { - self.window_controls = window_controls; - self - } - - /// Pads the pill bar's leading edge for the macOS traffic lights. - pub fn traffic_light_pad(mut self, traffic_light_pad: bool) -> Self { - self.traffic_light_pad = traffic_light_pad; - self - } - - /// Leads the pill bar with `prefix`, rebuilt on each frame. - pub fn tab_prefix(mut self, prefix: F) -> Self - where - F: Fn() -> AnyElement + 'static, - { - self.tab_prefix = Some(Rc::new(prefix)); - self - } - - /// Trails the pill bar with `suffix`, rebuilt on each frame. - pub fn tab_suffix(mut self, suffix: F) -> Self - where - F: Fn() -> AnyElement + 'static, - { - self.tab_suffix = Some(Rc::new(suffix)); - self - } -} - -impl RenderOnce for Dock { - fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let tree = self.state.read(cx).snapshot(); - let titlebar = Titlebar { - window_controls: self.window_controls, - traffic_light_pad: self.traffic_light_pad, - height: cx.theme().titlebar_height, - prefix: self.tab_prefix, - suffix: self.tab_suffix, - }; - let root = render_node(&self.id, &self.state, &tree, &titlebar, window, cx); - - div() - .id(self.id.clone()) - .debug_selector({ - let id = self.id.clone(); - move || format!("dock-{id}") - }) - .size_full() - .flex() - .flex_col() - .overflow_hidden() - .child(root) - } -} - -/// Which titlebar duties the pane's pill bar carries. -#[derive(Clone, Default)] -struct Titlebar { - window_controls: bool, - traffic_light_pad: bool, - height: Pixels, - /// Builds the tab bar's leading element on each frame. - prefix: Option AnyElement>>, - /// Builds the tab bar's trailing element on each frame. - suffix: Option AnyElement>>, -} - -/// The right sidebar content of the dock's active panel. -#[derive(IntoElement)] -pub struct DockSidebar { - id: ElementId, - state: Entity, -} - -impl DockSidebar { - /// Creates the sidebar content bound to `state`. - pub fn new(id: I, state: Entity) -> Self - where - I: Into, - { - Self { - id: id.into(), - state, - } - } -} - -impl RenderOnce for DockSidebar { - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - // The cache keeps an un-notified sidebar from re-rendering on frames. - let right_view = self.state.read(cx).right_view.clone(); - - div() - .id(self.id.clone()) - .debug_selector({ - let id = self.id.clone(); - move || format!("{id}-view") - }) - .size_full() - .overflow_hidden() - .when_some(right_view, |sidebar, view| { - sidebar.child(view.cached(StyleRefinement::default().absolute().size_full())) - }) - } -} - -fn render_node( - dock_id: &ElementId, - state: &Entity, - node: &TreeView, - titlebar: &Titlebar, - window: &mut Window, - cx: &mut App, -) -> AnyElement { - match node { - TreeView::Pane(pane) => render_pane(dock_id, state, pane, titlebar, cx), - TreeView::Split(split) => render_split(dock_id, state, split, titlebar, window, cx), - } -} - -fn render_split( - dock_id: &ElementId, - state: &Entity, - split: &SplitView, - titlebar: &Titlebar, - window: &mut Window, - cx: &mut App, -) -> AnyElement { - let span_state = window.with_element_namespace(dock_id.clone(), |window| { - window - .use_keyed_state(("split-span", split.key), cx, |_, _| size(px(0.), px(0.))) - .clone() - }); - - let seam = ResizeHandle::new(SharedString::from(format!("{dock_id}-seam-{}", split.key))) - .axis(split.axis) - .on_resize({ - let span_state = span_state.clone(); - let state = state.clone(); - let axis = split.axis; - let key = split.key; - move |delta, _, cx| { - let span = match axis { - Axis::Horizontal => span_state.read(cx).width, - Axis::Vertical => span_state.read(cx).height, - }; - if span > px(0.) { - let fraction = delta / span; - state.update(cx, |dock, cx| dock.resize_split(key, fraction, cx)); - } - } - }) - .on_reset({ - let state = state.clone(); - let key = split.key; - move |_, cx| state.update(cx, |dock, cx| dock.reset_split(key, cx)) - }); - - div() - .id(SharedString::from(format!("{dock_id}-split-{}", split.key))) - .size_full() - .min_w_0() - .min_h_0() - .overflow_hidden() - .flex() - .when(split.axis == Axis::Horizontal, |split_el| { - split_el.flex_row() - }) - .when(split.axis == Axis::Vertical, |split_el| split_el.flex_col()) - .child( - canvas(|bounds, _, _| bounds.size, { - let span_state = span_state.clone(); - move |_, span, _, cx| span_state.update(cx, |slot, _| *slot = span) - }) - .absolute() - .inset_0(), - ) - .child( - div() - .flex_grow(split.ratio) - .flex_basis(relative(0.)) - .min_w_0() - .min_h_0() - .overflow_hidden() - .child(render_node(dock_id, state, &split.a, titlebar, window, cx)), - ) - .child(seam) - .child( - div() - .flex_grow(1.0 - split.ratio) - .flex_basis(relative(0.)) - .min_w_0() - .min_h_0() - .overflow_hidden() - .child(render_node(dock_id, state, &split.b, titlebar, window, cx)), - ) - .into_any_element() -} - -fn render_pane( - dock_id: &ElementId, - state: &Entity, - pane: &PaneView, - titlebar: &Titlebar, - cx: &App, -) -> AnyElement { - if pane.tabs.is_empty() { - return div().size_full().into_any_element(); - } - - let theme = cx.theme(); - let metrics = theme.sizes.resolve(Size::default()); - let pane_id = SharedString::from(format!("{dock_id}-pane-{}", pane.key)); - - let active_view = pane - .tabs - .iter() - .find(|tab| Some(&tab.panel) == pane.active.as_ref()) - .map(|tab| tab.handle.view()); - - // The cache keeps an un-notified panel from re-rendering on dock frames. - let content_id = SharedString::from(format!("{dock_id}-content-{}", pane.key)); - let content = div() - .id(content_id.clone()) - .debug_selector(move || content_id.to_string()) - .flex_1() - .min_h_0() - .overflow_hidden() - .role(Role::TabPanel) - .when_some(active_view, |content, view| { - content.child(view.cached(StyleRefinement::default().absolute().size_full())) - }) - .when(cx.has_active_drag(), |content| { - content.children(render_drop_zones(state, pane)) - }); - - let menu = ContextMenu::new(SharedString::from(format!( - "{dock_id}-pane-{}-menu", - pane.key - ))) - .target({ - let dock_id = dock_id.clone(); - let state = state.clone(); - let pane = pane.clone(); - let titlebar = titlebar.clone(); - let padding_x = metrics.dense_padding_x; - - move |window, cx| { - let selected = pane - .active - .as_ref() - .and_then(|active| pane.tabs.iter().position(|tab| &tab.panel == active)) - .unwrap_or(0); - let tabs = Tabs::new(SharedString::from(format!( - "{dock_id}-pane-{}-tabs", - pane.key - ))) - .variant(TabsVariant::Pill) - .overflow_popover(true) - .overflow_open(pane.overflow_open) - .on_overflow_open({ - let state = state.clone(); - let pane_key = pane.key; - move |open, _, cx| { - state.update(cx, |dock, cx| { - dock.set_pane_overflow_open(pane_key, open, cx) - }); - } - }) - .selected(selected) - .tabs({ - let tabs = pane.tabs.clone(); - move |_, cx| { - tabs.iter() - .map(|tab| { - Tab::new(tab.panel.clone(), tab.handle.title(cx).unwrap_or_default()) - .when_some(tab.handle.lead(cx), |entry, lead| entry.lead(lead)) - .closeable(true) - .wrap({ - let panel = tab.panel.clone(); - let handle = tab.handle.clone(); - move |tab| { - tab.on_drag( - PanelDrag { - panel: panel.clone(), - }, - { - let handle = handle.clone(); - move |_, _, _, cx| { - let title = handle.title(cx); - cx.new(move |_| DragPreview { title }) - } - }, - ) - .into_any_element() - } - }) - }) - .collect() - } - }) - .on_change({ - let state = state.clone(); - let panels: Vec = - pane.tabs.iter().map(|tab| tab.panel.clone()).collect(); - move |index, _, cx| { - if let Some(panel) = panels.get(index) { - state.update(cx, |dock, cx| dock.activate_panel(panel, cx)); - } - } - }) - .on_close({ - let state = state.clone(); - let panels: Vec = - pane.tabs.iter().map(|tab| tab.panel.clone()).collect(); - move |index, _, cx| { - if let Some(panel) = panels.get(index) { - state.update(cx, |dock, cx| dock.close_panel(panel, cx)); - } - } - }); - - let bar_id = SharedString::from(format!("{dock_id}-pane-{}-bar", pane.key)); - let strip_id = SharedString::from(format!("{dock_id}-pane-{}-strip", pane.key)); - - let prefix = titlebar.prefix.as_ref().map(|prefix| prefix()); - let suffix = titlebar.suffix.as_ref().map(|suffix| suffix()); - - h_flex() - .id(bar_id.clone()) - .debug_selector(move || bar_id.to_string()) - .flex_none() - .w_full() - .h(titlebar.height) - .items_center() - .pl(if titlebar.traffic_light_pad { - TRAFFIC_LIGHT_PAD - } else { - padding_x - }) - .pr(padding_x) - .when_some(prefix, |bar, element| { - bar.child(div().flex_none().mr_1().child(element)) - }) - .child(tabs) - .child(titlebar_strip( - div().id(strip_id.clone()).flex_1().self_stretch(), - strip_id, - window, - cx, - )) - .when_some(suffix, |bar, element| { - bar.child(div().flex_none().ml_1().child(element)) - }) - .when(titlebar.window_controls, |bar| { - bar.child(WindowControls::new(SharedString::from(format!( - "{dock_id}-pane-{}-controls", - pane.key - )))) - }) - .into_any_element() - } - }) - .items({ - let state = state.clone(); - let active = pane.active.clone(); - let panels: Vec = pane.tabs.iter().map(|tab| tab.panel.clone()).collect(); - - move |_, _| { - let mut items = Vec::new(); - - if let Some(active) = &active { - items.push(MenuItem::new("Close").icon(IconRole::Close).handler({ - let state = state.clone(); - let active = active.clone(); - move |_, cx| state.update(cx, |dock, cx| dock.close_panel(&active, cx)) - })); - - if panels.len() > 1 { - items.push(MenuItem::new("Close Others").handler({ - let state = state.clone(); - let active = active.clone(); - move |_, cx| state.update(cx, |dock, cx| dock.close_others(&active, cx)) - })); - } - } - - if let Some(first) = panels.first() { - items.push(MenuItem::new("Close Pane").handler({ - let state = state.clone(); - let first = first.clone(); - move |_, cx| state.update(cx, |dock, cx| dock.close_pane(&first, cx)) - })); - } - - items - } - }); - - v_flex() - .id(pane_id.clone()) - .debug_selector({ - let id = pane_id.clone(); - move || id.to_string() - }) - .size_full() - .overflow_hidden() - .child(menu) - .child(content) - .into_any_element() -} - -/// The five drop targets a live tab drag sees over a pane's content: -/// -/// - Four edge bands that split -/// - The center that moves the tab in. -fn render_drop_zones(state: &Entity, pane: &PaneView) -> Vec { - let Some(anchor) = pane - .active - .clone() - .or_else(|| pane.tabs.first().map(|tab| tab.panel.clone())) - else { - return Vec::new(); - }; - - vec![ - drop_zone(state, &anchor, Some(SplitDirection::Left)) - .absolute() - .top_0() - .bottom_0() - .left_0() - .w(relative(0.25)) - .into_any_element(), - drop_zone(state, &anchor, Some(SplitDirection::Right)) - .absolute() - .top_0() - .bottom_0() - .right_0() - .w(relative(0.25)) - .into_any_element(), - drop_zone(state, &anchor, Some(SplitDirection::Top)) - .absolute() - .top_0() - .left(relative(0.25)) - .right(relative(0.25)) - .h(relative(0.25)) - .into_any_element(), - drop_zone(state, &anchor, Some(SplitDirection::Bottom)) - .absolute() - .bottom_0() - .left(relative(0.25)) - .right(relative(0.25)) - .h(relative(0.25)) - .into_any_element(), - drop_zone(state, &anchor, None) - .absolute() - .inset(relative(0.25)) - .into_any_element(), - ] -} - -/// Renders a drop zone for panel dragging. -fn drop_zone( - state: &Entity, - anchor: &str, - direction: Option, -) -> gpui::Div { - let state = state.clone(); - let anchor = SharedString::from(anchor); - div() - .drag_over::(|zone, _, _, cx| zone.bg(cx.theme().colors.selection)) - .on_drop::(move |drag, _, cx| { - state.update(cx, |dock, cx| match direction { - Some(direction) => { - dock.split_panel_at(&drag.panel, &anchor, direction, cx); - } - None => dock.move_panel(&drag.panel, &anchor, cx), - }); - }) -} diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 1505b35..2fb54f1 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -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; diff --git a/crates/layout/src/panel.rs b/crates/layout/src/panel.rs new file mode 100644 index 0000000..a9a07b3 --- /dev/null +++ b/crates/layout/src/panel.rs @@ -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, + split: Option, +} + +impl Panel { + /// Creates the panel row. + pub fn new(id: I) -> Self + where + I: Into, + { + 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) + } +} diff --git a/crates/layout/src/resizable.rs b/crates/layout/src/resizable.rs index 1c8f19a..1778a05 100644 --- a/crates/layout/src/resizable.rs +++ b/crates/layout/src/resizable.rs @@ -14,6 +14,7 @@ use crate::resize_handle::ResizeHandle; type DebugSelector = std::rc::Rc 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, @@ -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 { - 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. diff --git a/crates/layout/src/resize_handle.rs b/crates/layout/src/resize_handle.rs index 7b8b7a9..a0b9422 100644 --- a/crates/layout/src/resize_handle.rs +++ b/crates/layout/src/resize_handle.rs @@ -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(); diff --git a/crates/layout/src/shell.rs b/crates/layout/src/shell.rs index 95dd905..1857451 100644 --- a/crates/layout/src/shell.rs +++ b/crates/layout/src/shell.rs @@ -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, - #[cfg(feature = "alert")] - alerts: Entity, -} - -impl LayoutState { - /// Creates the state: left sidebar visible, right sidebar hidden. - pub fn new(cx: &mut App) -> Entity { - 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) { - 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) { - 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.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.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) { - 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) { - 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) -> 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.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.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) -> 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.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.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, - /// The titlebar drawn above the regions, replacing the strips. titlebar: Option, - left_sidebar: Option, - right_sidebar: Option, - center: Option, - /// Whether the left strip renders the default sidebar toggle. - toggle_button: bool, + panel: Option, + #[cfg(feature = "toast")] + toasts: Option>, + #[cfg(feature = "alert")] + alerts: Option>, } impl Shell { - /// Creates the shell bound to `state`. - pub fn new(id: I, state: Entity) -> Self + /// Creates the shell. + pub fn new(id: I) -> Self where I: Into, { 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(mut self, content: E) -> Self + /// Sets the panel row filling the rest of the window. + pub fn panel(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(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) -> Self { + self.toasts = Some(toasts); + self + } + + /// Hosts the alert overlay stacked on `alerts`. + #[cfg(feature = "alert")] + pub fn alerts(mut self, alerts: Entity) -> 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(id: I, side: Side, state: &Entity, cx: &App) -> Button -where - I: Into, -{ - 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( - id: I, - width: Pixels, - content: AnyElement, - state: &Entity, - strip: Option, - window: &mut Window, - cx: &mut App, -) -> AnyElement -where - I: Into, -{ - 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( - id: I, - strip: Strip, - state: &Entity, - window: &mut Window, - cx: &mut App, -) -> AnyElement -where - I: Into, -{ - 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() -} diff --git a/crates/layout/src/titlebar.rs b/crates/layout/src/titlebar.rs index 355d8e4..8b45c42 100644 --- a/crates/layout/src/titlebar.rs +++ b/crates/layout/src/titlebar.rs @@ -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, + prefix: Vec, + tab_bar: Option, + suffix: Vec, } 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(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(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) { - 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"))) } } diff --git a/crates/layout/tests/.keep b/crates/layout/tests/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/crates/layout/tests/panel.rs b/crates/layout/tests/panel.rs new file mode 100644 index 0000000..6f2aecc --- /dev/null +++ b/crates/layout/tests/panel.rs @@ -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) -> 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) -> 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)); +} diff --git a/docs/CHECKLIST.md b/docs/CHECKLIST.md index 48b556f..ff1ad13 100644 --- a/docs/CHECKLIST.md +++ b/docs/CHECKLIST.md @@ -45,8 +45,8 @@ Gaps surfaced by the signed comparison; ordered by signed's usage. overlay, per-view config overrides (line height, gutter visibility). - [ ] **Pickers** — Calendar / DatePicker, TimeField, ColorPicker (decide at unit time). -- [ ] **Layout follow-ups** — persistence, pane zoom, bottom dock, - collapse-to-edge; each waits for a real consumer. +- [ ] **Layout follow-ups** — column persistence, drag-to-reorder sub panel + columns; each waits for a real consumer. - [ ] **Platform screenshot passes** — a Linux run (Omarchy / KDE / GNOME) and the first Windows hardware build, side by side with macOS. @@ -217,18 +217,22 @@ Gaps surfaced by the signed comparison; ordered by signed's usage. ### layout (`crates/layout`) - [x] ResizeHandle -- [x] Shell — left/right sidebar regions + center, application-owned - `LayoutState` - [x] Window frame — client-side decorations under `Decorations::Client` -- [x] Dock — pane tree, panel registry, tab context menus -- [x] Drag-to-split — `PanelDrag` payload, edge + center drop zones -- [x] Titlebar + window controls — app-owned window dragging, per-platform - buttons, `Theme::titlebar_height` -- [x] Sidebar auto-open — `PanelDescriptor::right_sidebar` + `DockSidebar` -- [x] Resizable group — stacked panes with drag dividers outside the dock, - per-pane floors, double-click reset, keyboard steps +- [x] Titlebar + window controls — app-owned window dragging from the bar + and its tab bar (`prefix` / `suffix` control clusters opt out so a + press on a control never starts a drag; Windows keeps the tab bar + clickable instead of draggable), macOS pad leads, per-platform + trailing buttons, `Theme::titlebar_height` +- [x] Shell — the titlebar over the panel row in the window frame, hosting + the toast and alert overlays +- [x] Panel — island layout on the muted app background: the main island + fills the window and can split once into two half-width islands with + a drag divider between them (double-click restores the half split) +- [x] Resizable group — stacked panes with drag dividers, per-pane floors, + double-click reset, keyboard steps ### gallery (`examples/gallery`) -- [x] Component browser — the shell with the catalog in its sidebar, every - element a dock panel +- [x] Component browser — the catalog menu in the titlebar's + menu, every + demo a tab in the titlebar's tab strip over the panel row; the welcome + tab opens tabs and sub panel columns diff --git a/examples/gallery/src/main.rs b/examples/gallery/src/main.rs index e277b15..37b6ee3 100644 --- a/examples/gallery/src/main.rs +++ b/examples/gallery/src/main.rs @@ -1,3 +1,4 @@ +use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; @@ -8,7 +9,7 @@ use gpui::{ Pixels, Render, SharedString, Styled as _, UniformListScrollHandle, WeakEntity, Window, WindowBounds, WindowOptions, actions, div, list, px, rems, size, uniform_list, }; -use gpui_native_core::alert::{Alert, AlertSeverity}; +use gpui_native_core::alert::{Alert, AlertSeverity, Alerts}; use gpui_native_core::avatar::Avatar; use gpui_native_core::badge::{Badge, BadgeVariant}; use gpui_native_core::button::{Button, ButtonVariant}; @@ -37,7 +38,7 @@ use gpui_native_core::slider::Slider; use gpui_native_core::spinner::{Spinner, SpinnerVariant}; use gpui_native_core::status_dot::{StatusDot, StatusDotVariant}; use gpui_native_core::switch::Switch; -use gpui_native_core::toast::{Toast, ToastAction}; +use gpui_native_core::toast::{Toast, ToastAction, Toasts}; use gpui_native_core::toggle::Toggle; use gpui_native_core::tooltip::Tooltip; use gpui_native_data::list::{List, ListItem}; @@ -49,10 +50,10 @@ use gpui_native_editor::diff::{DiffRowKind, DiffViewState}; use gpui_native_editor::highlight::Language; use gpui_native_editor::markdown::{ListMarker, MarkdownBlock, MarkdownViewState, TextView}; use gpui_native_icons::{IconAssets, IconRole, icon}; -use gpui_native_layout::dock::{Dock, DockSidebar, DockState, Panel, SplitDirection}; +use gpui_native_layout::panel::Panel; use gpui_native_layout::resizable::{Resizable, ResizableState}; use gpui_native_layout::resize_handle::ResizeHandle; -use gpui_native_layout::shell::{LayoutState, Shell}; +use gpui_native_layout::shell::Shell; use gpui_native_layout::titlebar::Titlebar; use gpui_native_theme::{ ActiveTheme as _, CODE_OVERSCROLL_MAX, Theme, ThemeVariant, active_preset, mode_override, @@ -219,120 +220,346 @@ fn gallery_commands() -> Vec { } struct Gallery { - layout_state: Entity, - dock_state: Entity, + toasts: Entity, + alerts: Entity, + /// Open demo tabs, in tab order. + tabs: Vec, + active: Option, + /// Created demo views, kept so state survives tab switches. + views: HashMap, + /// The panel the row is split with, if any. + split_panel: Option, palette: Option>, palette_runs: Vec, dialog_open: bool, alert_open: bool, - /// Whether the app sidebar paints the window's native material. - sidebar_transparent: bool, - /// Whether a film-grain overlay textures the window. - grain: bool, - /// Whether the shell draws the unified titlebar. - titlebar: bool, + /// Whether the titlebar's catalog menu is open. + menu_open: bool, } impl Gallery { - /// Every sidebar entry's panel id, in order. Headers carry `None`: the - /// sidebar's selection index counts them like any entry. - fn panel_ids() -> Vec> { + /// The catalog label of a demo tab. + fn label_of(id: &str) -> &'static str { CATALOG .iter() - .flat_map(|(_, panels)| { - let mut ids = vec![None]; - ids.extend(panels.iter().map(|(id, _)| Some(*id))); - ids - }) - .collect() + .flat_map(|(_, demos)| demos.iter()) + .find(|(demo, _)| *demo == id) + .map(|(_, label)| *label) + .unwrap_or("Untitled") } - fn render_shell(&self, cx: &App) -> Shell { - let panel_ids = Self::panel_ids(); - let selected = self - .dock_state - .read(cx) - .active_panel() - .as_deref() - .and_then(|active| { - panel_ids - .iter() - .position(|id| id.as_deref() == Some(active)) - }); + fn render_shell(&self, gallery: WeakEntity, cx: &App) -> Shell { + Shell::new("gallery-shell") + .titlebar(self.gallery_titlebar(gallery, cx)) + .panel(self.render_panel()) + .toasts(self.toasts.clone()) + .alerts(self.alerts.clone()) + } - let left_sidebar = Sidebar::new("gallery-sidebar") + /// The panel row: the active demo, split with the opened sub panel. + fn render_panel(&self) -> Panel { + let panel = match self + .active + .as_ref() + .and_then(|active| self.views.get(active).cloned()) + { + Some(view) => Panel::new("gallery-panel").main(view), + None => Panel::new("gallery-panel"), + }; + + match &self.split_panel { + Some(split) => panel.split(split.clone()), + None => panel, + } + } + + /// The demo titlebar: the app name, the open tabs, and the catalog menu. + fn gallery_titlebar(&self, gallery: WeakEntity, cx: &App) -> Titlebar { + let colors = cx.theme().colors; + let selected = self + .active + .as_ref() + .and_then(|active| self.tabs.iter().position(|tab| tab == active)) + .unwrap_or(0); + + let strip = Tabs::new("gallery-tabs") + .variant(TabsVariant::Pill) + .overflow_scroll(true) .selected(selected) - .transparent(self.sidebar_transparent) - .grain(self.grain) - .accessibility_label("Component catalog") - .entries(|_, _| { - CATALOG - .iter() - .flat_map(|(group, panels)| { - let mut entries = vec![SidebarEntry::header(*group)]; - entries.extend( - panels - .iter() - .map(|(id, label)| SidebarEntry::row(*id, *label)), - ); - entries - }) - .collect() + .tabs({ + let tabs = self.tabs.clone(); + move |_, _| { + tabs.iter() + .map(|id| Tab::new(id.clone(), Self::label_of(id)).closeable(true)) + .collect() + } }) .on_change({ - let dock_state = self.dock_state.clone(); + let tabs = self.tabs.clone(); + let gallery = gallery.clone(); move |index, window, cx| { - if let Some(Some(id)) = index.and_then(|index| panel_ids.get(index)) { - dock_state.update(cx, |dock, cx| dock.open_panel(id, window, cx)); + if let Some(id) = tabs.get(index) { + gallery + .update(cx, |gallery, cx| gallery.open_demo(id, window, cx)) + .log_err(); } } + }) + .on_close({ + let gallery = gallery.clone(); + move |index, _, cx| { + gallery + .update(cx, |gallery, cx| gallery.close_demo(index, cx)) + .log_err(); + } }); - let center = Dock::new("gallery-dock", self.dock_state.clone()) - // The pill bar is the titlebar strip whenever no right sidebar sits - // to its right and the shell titlebar has not taken the chrome over. - .window_controls( - !self.titlebar && !self.layout_state.read(cx).is_right_sidebar_visible(), - ) - .traffic_light_pad( - !self.titlebar && !self.layout_state.read(cx).is_left_sidebar_visible(), - ); - - let right_sidebar = DockSidebar::new("gallery-dock-sidebar", self.dock_state.clone()); - - Shell::new("gallery-shell", self.layout_state.clone()) - .left_sidebar(left_sidebar) - .center(center) - .right_sidebar(right_sidebar) - .when(self.titlebar, |shell| { - shell.titlebar(self.gallery_titlebar(cx)) - }) - } - - /// The demo titlebar: a sidebar toggle and the app title. - fn gallery_titlebar(&self, cx: &App) -> Titlebar { - let layout = self.layout_state.clone(); - let title_color = cx.theme().colors.muted_foreground; - Titlebar::new("gallery-titlebar") - .child( - Button::new("titlebar-toggle-left") - .icon(IconRole::PanelLeft) - .variant(ButtonVariant::Ghost) - .small() - .accessibility_label("Toggle left sidebar") - .on_click(move |_, _, cx| { - layout.update(cx, LayoutState::toggle_left_sidebar); - }), - ) .child( div() .text_sm() - .text_color(title_color) + .text_color(colors.muted_foreground) .child("gpui-native-kit"), ) + .tab_bar(strip) + .suffix( + h_flex().gap_1().child(self.catalog_menu(gallery)).child( + Button::new("titlebar-palette") + .icon(IconRole::Search) + .variant(ButtonVariant::Ghost) + .small() + .accessibility_label("Open the command palette") + .on_click({ + let palette = self.palette.clone(); + move |_, window, cx| { + if let Some(palette) = &palette { + palette.update(cx, |palette, cx| palette.toggle(window, cx)); + } + } + }), + ), + ) } + /// The catalog menu: every component demo, grouped, one item per demo. + fn catalog_menu(&self, gallery: WeakEntity) -> Menu { + Menu::new("gallery-catalog") + .open(self.menu_open) + .on_change({ + let gallery = gallery.clone(); + move |open, _, cx| { + gallery + .update(cx, |gallery, cx| { + gallery.menu_open = open; + cx.notify(); + }) + .log_err(); + } + }) + .trigger(|_, _| { + Button::new("gallery-catalog-trigger") + .icon(IconRole::Plus) + .variant(ButtonVariant::Ghost) + .small() + .accessibility_label("Open a component demo") + .into_any_element() + }) + .items(move |_, _| { + let mut items = Vec::new(); + for (index, (group, demos)) in CATALOG.iter().enumerate() { + if index > 0 { + items.push(MenuItem::separator()); + } + items.push(MenuItem::new(*group).disabled(true)); + for (id, label) in demos.iter() { + items.push(MenuItem::new(*label).handler({ + let id = *id; + let gallery = gallery.clone(); + move |window, cx| { + gallery + .update(cx, |gallery, cx| gallery.open_demo(id, window, cx)) + .log_err(); + } + })); + } + } + items + }) + } + + /// Opens a demo tab, creating its view on first open. + fn open_demo(&mut self, id: &str, window: &mut Window, cx: &mut Context) { + if !self.tabs.iter().any(|tab| tab.as_ref() == id) { + self.tabs.push(SharedString::from(id)); + } + self.active = Some(SharedString::from(id)); + if !self.views.contains_key(id) { + let gallery = cx.entity().downgrade(); + if let Some(view) = self.create_view(id, gallery, window, cx) { + self.views.insert(SharedString::from(id), view); + } + } + cx.notify(); + } + + /// Closes the demo tab at `index`, activating a neighbor. + fn close_demo(&mut self, index: usize, cx: &mut Context) { + let Some(id) = self.tabs.get(index).cloned() else { + return; + }; + self.tabs.remove(index); + self.views.remove(&id); + + let was_active = self.active.as_ref() == Some(&id); + if was_active { + self.active = self + .tabs + .get(index) + .or_else(|| { + index + .checked_sub(1) + .and_then(|previous| self.tabs.get(previous)) + }) + .cloned(); + } + cx.notify(); + } + + /// Opens the sub panel the row splits with. + fn open_split(&mut self, cx: &mut Context) { + if self.split_panel.is_some() { + return; + } + let view = cx.new(|_| column_details()); + self.split_panel = Some(view.into()); + cx.notify(); + } + + /// Closes the split, leaving the main panel alone. + fn close_split(&mut self, cx: &mut Context) { + if self.split_panel.is_none() { + return; + } + self.split_panel = None; + cx.notify(); + } + + /// Creates the view behind a demo tab. + fn create_view( + &self, + id: &str, + gallery: WeakEntity, + window: &mut Window, + cx: &mut Context, + ) -> Option { + let view: AnyView = match id { + "welcome" => cx.new(|_| WelcomePanel { gallery }).into(), + "button" => cx.new(|_| ButtonDemo { clicks: 0 }).into(), + "input" => cx.new(InputDemo::new).into(), + "field" => cx.new(|cx| FieldDemo::new(window, cx)).into(), + "combobox" => cx.new(|cx| ComboboxDemo::new(window, cx)).into(), + "status-dot" => cx.new(|_| StatusDotDemo).into(), + "checkbox" => cx.new(|_| CheckboxDemo { checked: false }).into(), + "radio" => cx + .new(|_| RadioDemo { + plan: SharedString::from("starter"), + }) + .into(), + "switch" => cx.new(|_| SwitchDemo { checked: true }).into(), + "toggle" => cx.new(|_| ToggleDemo { pressed: false }).into(), + "slider" => cx.new(|_| SliderDemo { volume: 40.0 }).into(), + "segmented" => cx + .new(|_| SegmentedDemo { + filter: ExploreFilter::default(), + }) + .into(), + "select" => cx + .new(|_| SelectDemo { + strategy: Some(Strategy::Curated), + }) + .into(), + "link" => cx.new(|_| LinkDemo { clicks: 0 }).into(), + "clipboard" => cx.new(|_| ClipboardDemo).into(), + "badge" => cx.new(|_| BadgeDemo).into(), + "avatar" => cx.new(|_| AvatarDemo).into(), + "progress" => cx.new(|_| ProgressDemo).into(), + "spinner" => cx.new(|_| SpinnerDemo).into(), + "list" => cx.new(|_| ListDemo { selected: None }).into(), + "tree" => cx + .new(|_| TreeDemo { + nodes: TreeDemo::demo(), + selected: None, + }) + .into(), + "tabs" => cx + .new(|_| TabsDemo { + selected: 0, + pill_tabs: vec![ + SharedString::from("Explorer"), + SharedString::from("Syncing"), + SharedString::from("Blame"), + ], + pill_selected: 0, + lead_selected: 0, + overflow_selected: 0, + overflow_open: false, + }) + .into(), + "alert" => cx + .new(|_| AlertDemo { + alerts: self.alerts.clone(), + dismissed: false, + }) + .into(), + "toast" => cx + .new(|_| ToastDemo { + toasts: self.toasts.clone(), + }) + .into(), + "dialog" => cx.new(|_| DialogDemo { gallery }).into(), + "command-palette" => { + let palette = self.palette.clone()?; + cx.new(|cx| CommandPaletteDemo::new(gallery, palette, cx)) + .into() + } + "menu" => cx.new(|_| MenuDemo { open: false }).into(), + "dropdown-menu" => cx + .new(|_| DropdownMenuDemo { + open_menu: None, + status: None, + }) + .into(), + "context-menu" => cx + .new(|_| ContextMenuDemo { + action: SharedString::from("Right-click the card"), + }) + .into(), + "popover" => cx.new(|_| PopoverDemo { open: false }).into(), + "tooltip" => cx.new(|_| TooltipDemo).into(), + "empty-state" => cx.new(|_| EmptyStateDemo).into(), + "scroll-area" => cx.new(|_| ScrollAreaDemo).into(), + "scrollbar" => cx.new(|_| ScrollbarDemo::new()).into(), + "code-view" => cx.new(CodeViewDemo::new).into(), + "diff-view" => cx.new(DiffViewDemo::new).into(), + "markdown-view" => cx.new(MarkdownViewDemo::new).into(), + "text-view" => cx.new(TextViewDemo::new).into(), + "sidebar" => cx.new(|_| SidebarDemo { selected: None }).into(), + "resize-handle" => cx + .new(|_| ResizeDemo { + width: rems(ResizeDemo::WIDTH_DEFAULT_REMS).to_pixels(window.rem_size()), + }) + .into(), + "resizable" => cx.new(ResizableDemo::new).into(), + "separator" => cx.new(|_| SeparatorDemo).into(), + "theme" => cx.new(|_| ThemeDemo).into(), + _ => return None, + }; + + Some(view) + } +} + +impl Gallery { fn render_dialog(open: bool, gallery: WeakEntity) -> Dialog { let gallery_change = gallery.clone(); Dialog::new("gallery-dialog") @@ -435,147 +662,6 @@ impl Gallery { ] }) } - - fn register_panels( - dock: &mut DockState, - layout_state: Entity, - palette: Entity, - gallery: WeakEntity, - cx: &mut Context, - ) { - let dock_state = cx.entity(); - - dock.register_panel("welcome", { - let layout_state = layout_state.clone(); - let dock_state = dock_state.clone(); - let gallery = gallery.clone(); - move |_, cx| { - cx.new(|_| WelcomePanel { - layout_state: layout_state.clone(), - dock_state: dock_state.clone(), - gallery: gallery.clone(), - }) - } - }); - dock.register_panel("button", |_, cx| cx.new(|_| ButtonDemo { clicks: 0 })); - dock.register_panel("input", |_, cx| cx.new(InputDemo::new)); - dock.register_panel("field", |window, cx| { - cx.new(|cx| FieldDemo::new(window, cx)) - }); - dock.register_panel("combobox", |window, cx| { - cx.new(|cx| ComboboxDemo::new(window, cx)) - }); - dock.register_panel("status-dot", |_, cx| cx.new(|_| StatusDotDemo)); - dock.register_panel("checkbox", |_, cx| { - cx.new(|_| CheckboxDemo { checked: false }) - }); - dock.register_panel("radio", |_, cx| { - cx.new(|_| RadioDemo { - plan: SharedString::from("starter"), - }) - }); - dock.register_panel("switch", |_, cx| cx.new(|_| SwitchDemo { checked: true })); - dock.register_panel("toggle", |_, cx| cx.new(|_| ToggleDemo { pressed: false })); - dock.register_panel("slider", |_, cx| cx.new(|_| SliderDemo { volume: 40.0 })); - dock.register_panel("segmented", |_, cx| { - cx.new(|_| SegmentedDemo { - filter: ExploreFilter::default(), - }) - }); - dock.register_panel("select", |_, cx| { - cx.new(|_| SelectDemo { - strategy: Some(Strategy::Curated), - }) - }); - dock.register_panel("link", |_, cx| cx.new(|_| LinkDemo { clicks: 0 })); - dock.register_panel("clipboard", |_, cx| cx.new(|_| ClipboardDemo)); - dock.register_panel("badge", |_, cx| cx.new(|_| BadgeDemo)); - dock.register_panel("avatar", |_, cx| cx.new(|_| AvatarDemo)); - dock.register_panel("progress", |_, cx| cx.new(|_| ProgressDemo)); - dock.register_panel("spinner", |_, cx| cx.new(|_| SpinnerDemo)); - dock.register_panel("list", |_, cx| cx.new(|_| ListDemo { selected: None })); - dock.register_panel("tree", |_, cx| { - cx.new(|_| TreeDemo { - nodes: TreeDemo::demo(), - selected: None, - }) - }); - dock.register_panel("tabs", |_, cx| { - cx.new(|_| TabsDemo { - selected: 0, - pill_tabs: vec![ - SharedString::from("Explorer"), - SharedString::from("Syncing"), - SharedString::from("Blame"), - ], - pill_selected: 0, - lead_selected: 0, - overflow_selected: 0, - overflow_open: false, - }) - }); - dock.register_panel("alert", { - let layout_state = layout_state.clone(); - move |_, cx| { - cx.new(|_| AlertDemo { - layout_state: layout_state.clone(), - dismissed: false, - }) - } - }); - dock.register_panel("toast", { - let layout_state = layout_state.clone(); - move |_, cx| { - cx.new(|_| ToastDemo { - layout_state: layout_state.clone(), - }) - } - }); - dock.register_panel("dialog", { - let gallery = gallery.clone(); - move |_, cx| { - cx.new(|_| DialogDemo { - gallery: gallery.clone(), - }) - } - }); - dock.register_panel("command-palette", { - let palette = palette.clone(); - move |_, cx| cx.new(|cx| CommandPaletteDemo::new(gallery.clone(), palette.clone(), cx)) - }); - dock.register_panel("menu", |_, cx| cx.new(|_| MenuDemo { open: false })); - dock.register_panel("dropdown-menu", |_, cx| { - cx.new(|_| DropdownMenuDemo { - open_menu: None, - status: None, - }) - }); - dock.register_panel("context-menu", |_, cx| { - cx.new(|_| ContextMenuDemo { - action: SharedString::from("Right-click the card"), - }) - }); - dock.register_panel("popover", |_, cx| cx.new(|_| PopoverDemo { open: false })); - dock.register_panel("tooltip", |_, cx| cx.new(|_| TooltipDemo)); - dock.register_panel("empty-state", |_, cx| cx.new(|_| EmptyStateDemo)); - dock.register_panel("scroll-area", |_, cx| cx.new(|_| ScrollAreaDemo)); - dock.register_panel("scrollbar", |_, cx| cx.new(|_| ScrollbarDemo::new())); - dock.register_panel("code-view", |_, cx| cx.new(CodeViewDemo::new)); - dock.register_panel("diff-view", |_, cx| cx.new(DiffViewDemo::new)); - dock.register_panel("markdown-view", |_, cx| cx.new(MarkdownViewDemo::new)); - dock.register_panel("text-view", |_, cx| cx.new(TextViewDemo::new)); - dock.register_panel("sidebar", |_, cx| { - cx.new(|_| SidebarDemo { selected: None }) - }); - dock.register_panel("resize-handle", |window, cx| { - cx.new(|_| ResizeDemo { - width: rems(ResizeDemo::WIDTH_DEFAULT_REMS).to_pixels(window.rem_size()), - }) - }); - dock.register_panel("resizable", |_, cx| cx.new(ResizableDemo::new)); - dock.register_panel("separator", |_, cx| cx.new(|_| SeparatorDemo)); - dock.register_panel("theme", |_, cx| cx.new(|_| ThemeDemo)); - } } impl Render for Gallery { @@ -587,7 +673,7 @@ impl Render for Gallery { // Dialogs are window-modal, so they mount at the window root; the // Dialog demo panel only flips these flags. let dialog = Self::render_dialog(self.dialog_open, gallery.clone()); - let alert_dialog = Self::render_alert_dialog(self.alert_open, gallery); + let alert_dialog = Self::render_alert_dialog(self.alert_open, gallery.clone()); div() .size_full() @@ -598,46 +684,25 @@ impl Render for Gallery { } }) .text_color(theme.colors.foreground) - .child(self.render_shell(cx)) + .child(self.render_shell(gallery.clone(), cx)) .child(dialog) .child(alert_dialog) .when_some(self.palette.clone(), |root, palette| root.child(palette)) } } -/// The dock introduction: how to drive the center dock, plus the shell's -/// sidebar toggles. +/// The layout introduction: opening tabs and sub panel columns. struct WelcomePanel { - layout_state: Entity, - dock_state: Entity, gallery: WeakEntity, } -impl Panel for WelcomePanel { - fn title(&self, _: &App) -> Option { - Some("Welcome".into()) - } - - fn right_sidebar(&mut self, _: &mut Window, cx: &mut App) -> Option { - Some( - cx.new(|_| RightDetails { - title: "Welcome", - body: "Panels can declare this view; activating one opens the sidebar.", - }) - .into(), - ) - } -} - impl Render for WelcomePanel { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; - let layout_left = self.layout_state.clone(); - let layout_right = self.layout_state.clone(); - let dock_state = self.dock_state.clone(); - let gallery = self.gallery.clone(); - let grain_gallery = self.gallery.clone(); - let titlebar_gallery = self.gallery.clone(); + let gallery_button = self.gallery.clone(); + let gallery_tabs = self.gallery.clone(); + let gallery_split = self.gallery.clone(); + let gallery_close = self.gallery.clone(); ScrollArea::new("welcome-demo") .size_full() @@ -656,95 +721,68 @@ impl Render for WelcomePanel { .gap_1() .text_sm() .text_color(colors.muted_foreground) - .child(div().child("Pick a component in the sidebar — it opens here as a tab.")) .child(div().child( - "Drag a tab to another pane's edge to split, or onto a tab bar to move it.", + "Open a demo from the + menu in the titlebar — it opens here as a tab.", )) .child(div().child( - "Right-click the tab bar to close a tab, close others, or close the pane.", - )) - .child(div().child("Seams between panes resize; double-click a seam to reset.")), + "Sub panels open as columns beside the main region; the row scrolls horizontally when they no longer fit.", + )), ) .child(demo_section( - "layout state", + "open tabs", colors, h_flex() .flex_wrap() .gap_2() .child( - Button::new("welcome-toggle-left") - .label("Toggle left sidebar") + Button::new("welcome-open-button") + .label("Open Button tab") .variant(ButtonVariant::Secondary) .small() - .on_click(move |_, _, cx| { - layout_left - .update(cx, LayoutState::toggle_left_sidebar); - }), - ) - .child( - Button::new("welcome-toggle-right") - .label("Toggle right sidebar") - .variant(ButtonVariant::Secondary) - .small() - .on_click(move |_, _, cx| { - layout_right - .update(cx, LayoutState::toggle_right_sidebar); - }), - ) - .child( - Button::new("welcome-toggle-blur") - .label("Toggle sidebar blur") - .variant(ButtonVariant::Secondary) - .small() - .on_click(move |_, _, cx| { - gallery + .on_click(move |_, window, cx| { + gallery_button .update(cx, |gallery, cx| { - gallery.sidebar_transparent = - !gallery.sidebar_transparent; - cx.notify(); + gallery.open_demo("button", window, cx); }) .log_err(); }), ) .child( - Button::new("welcome-toggle-grain") - .label("Toggle grain") + Button::new("welcome-open-tabs") + .label("Open Tabs tab") .variant(ButtonVariant::Secondary) .small() - .on_click(move |_, _, cx| { - grain_gallery + .on_click(move |_, window, cx| { + gallery_tabs .update(cx, |gallery, cx| { - gallery.grain = !gallery.grain; - cx.notify(); + gallery.open_demo("tabs", window, cx); }) .log_err(); }), - ) + ), + )) + .child(demo_section( + "sub panels", + colors, + h_flex() + .flex_wrap() + .gap_2() .child( - Button::new("welcome-toggle-titlebar") - .label("Toggle titlebar") + Button::new("welcome-open-split") + .label("Split panel") .variant(ButtonVariant::Secondary) .small() .on_click(move |_, _, cx| { - titlebar_gallery - .update(cx, |gallery, cx| { - gallery.titlebar = !gallery.titlebar; - cx.notify(); - }) - .log_err(); + gallery_split.update(cx, Gallery::open_split).log_err(); }), ) .child( - Button::new("welcome-split") - .label("Split active right") + Button::new("welcome-close-split") + .label("Close split") .variant(ButtonVariant::Secondary) .small() .on_click(move |_, _, cx| { - dock_state.update(cx, |dock, cx| { - if let Some(active) = dock.active_panel() { - dock.split_panel(&active, SplitDirection::Right, cx); - } - }); + gallery_close.update(cx, Gallery::close_split).log_err(); }), ), )), @@ -752,10 +790,18 @@ impl Render for WelcomePanel { } } -/// The right sidebar view a panel declares. +/// The sub panel column's content. +fn column_details() -> RightDetails { + RightDetails { + title: "Split column".into(), + body: "The row splits into two half-width panels. Drag the divider to resize them; double-click it to restore the half split.".into(), + } +} + +/// A sub panel column's note. struct RightDetails { - title: &'static str, - body: &'static str, + title: SharedString, + body: SharedString, } impl Render for RightDetails { @@ -764,14 +810,16 @@ impl Render for RightDetails { v_flex() .size_full() .gap_1() - .p_2() - .bg(colors.background) - .child(div().font_weight(FontWeight::MEDIUM).child(self.title)) + .child( + div() + .font_weight(FontWeight::MEDIUM) + .child(self.title.clone()), + ) .child( div() .text_sm() .text_color(colors.muted_foreground) - .child(self.body), + .child(self.body.clone()), ) } } @@ -791,12 +839,6 @@ impl ButtonDemo { } } -impl Panel for ButtonDemo { - fn title(&self, _: &App) -> Option { - Some("Button".into()) - } -} - impl Render for ButtonDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -961,12 +1003,6 @@ impl InputDemo { } } -impl Panel for InputDemo { - fn title(&self, _: &App) -> Option { - Some("Input".into()) - } -} - impl Render for InputDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -1051,12 +1087,6 @@ impl FieldDemo { } } -impl Panel for FieldDemo { - fn title(&self, _: &App) -> Option { - Some("Field".into()) - } -} - impl Render for FieldDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -1129,12 +1159,6 @@ impl Render for FieldDemo { struct StatusDotDemo; -impl Panel for StatusDotDemo { - fn title(&self, _: &App) -> Option { - Some("Status dot".into()) - } -} - impl Render for StatusDotDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -1303,12 +1327,6 @@ impl ComboboxDemo { } } -impl Panel for ComboboxDemo { - fn title(&self, _: &App) -> Option { - Some("Combobox".into()) - } -} - impl Render for ComboboxDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -1378,12 +1396,6 @@ struct CheckboxDemo { checked: bool, } -impl Panel for CheckboxDemo { - fn title(&self, _: &App) -> Option { - Some("Checkbox".into()) - } -} - impl Render for CheckboxDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -1426,12 +1438,6 @@ struct RadioDemo { plan: SharedString, } -impl Panel for RadioDemo { - fn title(&self, _: &App) -> Option { - Some("Radio".into()) - } -} - impl Render for RadioDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -1468,12 +1474,6 @@ struct SwitchDemo { checked: bool, } -impl Panel for SwitchDemo { - fn title(&self, _: &App) -> Option { - Some("Switch".into()) - } -} - impl Render for SwitchDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -1516,12 +1516,6 @@ struct ToggleDemo { pressed: bool, } -impl Panel for ToggleDemo { - fn title(&self, _: &App) -> Option { - Some("Toggle".into()) - } -} - impl Render for ToggleDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -1559,12 +1553,6 @@ struct SliderDemo { volume: f32, } -impl Panel for SliderDemo { - fn title(&self, _: &App) -> Option { - Some("Slider".into()) - } -} - impl Render for SliderDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -1602,12 +1590,6 @@ struct SegmentedDemo { filter: ExploreFilter, } -impl Panel for SegmentedDemo { - fn title(&self, _: &App) -> Option { - Some("Segmented".into()) - } -} - impl Render for SegmentedDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -1690,12 +1672,6 @@ struct SelectDemo { strategy: Option, } -impl Panel for SelectDemo { - fn title(&self, _: &App) -> Option { - Some("Select".into()) - } -} - impl Render for SelectDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -1744,12 +1720,6 @@ struct LinkDemo { clicks: usize, } -impl Panel for LinkDemo { - fn title(&self, _: &App) -> Option { - Some("Link".into()) - } -} - impl Render for LinkDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -1798,12 +1768,6 @@ impl Render for LinkDemo { struct ClipboardDemo; -impl Panel for ClipboardDemo { - fn title(&self, _: &App) -> Option { - Some("Clipboard".into()) - } -} - impl Render for ClipboardDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -1838,12 +1802,6 @@ impl Render for ClipboardDemo { struct SeparatorDemo; -impl Panel for SeparatorDemo { - fn title(&self, _: &App) -> Option { - Some("Separator".into()) - } -} - impl Render for SeparatorDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -1896,12 +1854,6 @@ impl ResizableDemo { } } -impl Panel for ResizableDemo { - fn title(&self, _: &App) -> Option { - Some("Resizable".into()) - } -} - impl Render for ResizableDemo { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -1941,12 +1893,6 @@ impl Render for ResizableDemo { struct BadgeDemo; -impl Panel for BadgeDemo { - fn title(&self, _: &App) -> Option { - Some("Badge".into()) - } -} - impl Render for BadgeDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -1984,12 +1930,6 @@ impl Render for BadgeDemo { struct AvatarDemo; -impl Panel for AvatarDemo { - fn title(&self, _: &App) -> Option { - Some("Avatar".into()) - } -} - impl Render for AvatarDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -2025,12 +1965,6 @@ impl Render for AvatarDemo { struct ProgressDemo; -impl Panel for ProgressDemo { - fn title(&self, _: &App) -> Option { - Some("Progress".into()) - } -} - impl Render for ProgressDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -2056,12 +1990,6 @@ impl Render for ProgressDemo { struct SpinnerDemo; -impl Panel for SpinnerDemo { - fn title(&self, _: &App) -> Option { - Some("Spinner".into()) - } -} - impl Render for SpinnerDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -2104,12 +2032,6 @@ struct ListDemo { selected: Option, } -impl Panel for ListDemo { - fn title(&self, _: &App) -> Option { - Some("List".into()) - } -} - impl Render for ListDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -2285,12 +2207,6 @@ impl TreeDemo { } } -impl Panel for TreeDemo { - fn title(&self, _: &App) -> Option { - Some("Tree".into()) - } -} - impl Render for TreeDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -2334,12 +2250,6 @@ struct TabsDemo { overflow_open: bool, } -impl Panel for TabsDemo { - fn title(&self, _: &App) -> Option { - Some("Tabs".into()) - } -} - impl Render for TabsDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -2511,22 +2421,16 @@ impl Render for TabsDemo { } struct AlertDemo { - layout_state: Entity, + alerts: Entity, dismissed: bool, } -impl Panel for AlertDemo { - fn title(&self, _: &App) -> Option { - Some("Alert".into()) - } -} - impl Render for AlertDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); - let alerts_info = self.layout_state.clone(); - let alerts_warning = self.layout_state.clone(); - let alerts_clear = self.layout_state.clone(); + let alerts_info = self.alerts.clone(); + let alerts_warning = self.alerts.clone(); + let alerts_clear = self.alerts.clone(); let colors = cx.theme().colors; ScrollArea::new("alert-demo").size_full().child( @@ -2569,8 +2473,8 @@ impl Render for AlertDemo { .label("Push info") .variant(ButtonVariant::Secondary) .on_click(move |_, _, cx| { - alerts_info.update(cx, |state, cx| { - state.push_alert( + alerts_info.update(cx, |alerts, cx| { + alerts.push( Alert::new("alert-demo-pushed-info") .title("Backed up") .message("Everything is in sync.") @@ -2585,8 +2489,8 @@ impl Render for AlertDemo { .label("Push warning") .variant(ButtonVariant::Secondary) .on_click(move |_, _, cx| { - alerts_warning.update(cx, |state, cx| { - state.push_alert( + alerts_warning.update(cx, |alerts, cx| { + alerts.push( Alert::new("alert-demo-pushed-warning") .title("Storage almost full") .message("1.2 GB remaining on this device.") @@ -2601,7 +2505,7 @@ impl Render for AlertDemo { .label("Clear all") .variant(ButtonVariant::Secondary) .on_click(move |_, _, cx| { - alerts_clear.update(cx, |state, cx| state.clear_alerts(cx)); + alerts_clear.update(cx, |alerts, cx| alerts.clear(cx)); }), ), )), @@ -2610,20 +2514,14 @@ impl Render for AlertDemo { } struct ToastDemo { - layout_state: Entity, -} - -impl Panel for ToastDemo { - fn title(&self, _: &App) -> Option { - Some("Toast".into()) - } + toasts: Entity, } impl Render for ToastDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let toasts_undo = self.layout_state.clone(); - let toasts_saved = self.layout_state.clone(); - let toasts_connection = self.layout_state.clone(); + let toasts_undo = self.toasts.clone(); + let toasts_saved = self.toasts.clone(); + let toasts_connection = self.toasts.clone(); let colors = cx.theme().colors; ScrollArea::new("toast-demo") @@ -2639,8 +2537,8 @@ impl Render for ToastDemo { .label("Deleted (with undo)") .variant(ButtonVariant::Secondary) .on_click(move |_, _, cx| { - toasts_undo.update(cx, |state, cx| { - state.push_toast( + toasts_undo.update(cx, |toasts, cx| { + toasts.push( Toast::new("Draft deleted").action(ToastAction::new( "Undo", |cx| { @@ -2658,8 +2556,8 @@ impl Render for ToastDemo { .label("Saved (with icon)") .variant(ButtonVariant::Secondary) .on_click(move |_, _, cx| { - toasts_saved.update(cx, |state, cx| { - state.push_toast( + toasts_saved.update(cx, |toasts, cx| { + toasts.push( Toast::new("Workspace saved").icon(IconRole::Check), cx, ); @@ -2671,8 +2569,8 @@ impl Render for ToastDemo { .label("Connection lost (sticky)") .variant(ButtonVariant::Secondary) .on_click(move |_, _, cx| { - toasts_connection.update(cx, |state, cx| { - state.push_toast( + toasts_connection.update(cx, |toasts, cx| { + toasts.push( Toast::new("Connection lost") .icon(IconRole::Warning) .duration(Duration::ZERO), @@ -2689,12 +2587,6 @@ struct DialogDemo { gallery: WeakEntity, } -impl Panel for DialogDemo { - fn title(&self, _: &App) -> Option { - Some("Dialog".into()) - } -} - impl Render for DialogDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let gallery_dialog = self.gallery.clone(); @@ -2761,12 +2653,6 @@ impl CommandPaletteDemo { } } -impl Panel for CommandPaletteDemo { - fn title(&self, _: &App) -> Option { - Some("Command palette".into()) - } -} - impl Render for CommandPaletteDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -2833,12 +2719,6 @@ struct MenuDemo { open: bool, } -impl Panel for MenuDemo { - fn title(&self, _: &App) -> Option { - Some("Menu".into()) - } -} - impl Render for MenuDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -2910,12 +2790,6 @@ impl DropdownMenuDemo { } } -impl Panel for DropdownMenuDemo { - fn title(&self, _: &App) -> Option { - Some("Dropdown menu".into()) - } -} - impl Render for DropdownMenuDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -3067,12 +2941,6 @@ struct ContextMenuDemo { action: SharedString, } -impl Panel for ContextMenuDemo { - fn title(&self, _: &App) -> Option { - Some("Context menu".into()) - } -} - impl Render for ContextMenuDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -3128,12 +2996,6 @@ struct PopoverDemo { open: bool, } -impl Panel for PopoverDemo { - fn title(&self, _: &App) -> Option { - Some("Popover".into()) - } -} - impl Render for PopoverDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -3175,12 +3037,6 @@ impl Render for PopoverDemo { struct TooltipDemo; -impl Panel for TooltipDemo { - fn title(&self, _: &App) -> Option { - Some("Tooltip".into()) - } -} - impl Render for TooltipDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -3226,12 +3082,6 @@ impl Render for TooltipDemo { struct EmptyStateDemo; -impl Panel for EmptyStateDemo { - fn title(&self, _: &App) -> Option { - Some("Empty state".into()) - } -} - impl Render for EmptyStateDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); @@ -3278,12 +3128,6 @@ impl Render for EmptyStateDemo { struct ScrollAreaDemo; -impl Panel for ScrollAreaDemo { - fn title(&self, _: &App) -> Option { - Some("Scroll area".into()) - } -} - impl Render for ScrollAreaDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); @@ -3366,12 +3210,6 @@ impl ScrollbarDemo { } } -impl Panel for ScrollbarDemo { - fn title(&self, _: &App) -> Option { - Some("Scrollbar".into()) - } -} - impl Render for ScrollbarDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); @@ -3581,12 +3419,6 @@ impl CodeViewDemo { } } -impl Panel for CodeViewDemo { - fn title(&self, _: &App) -> Option { - Some("Code view".into()) - } -} - impl Render for CodeViewDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -3757,12 +3589,6 @@ impl DiffViewDemo { } } -impl Panel for DiffViewDemo { - fn title(&self, _: &App) -> Option { - Some("Diff view".into()) - } -} - impl Render for DiffViewDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -3983,12 +3809,6 @@ impl MarkdownViewDemo { } } -impl Panel for MarkdownViewDemo { - fn title(&self, _: &App) -> Option { - Some("Markdown view".into()) - } -} - impl Render for MarkdownViewDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -4065,12 +3885,6 @@ impl TextViewDemo { } } -impl Panel for TextViewDemo { - fn title(&self, _: &App) -> Option { - Some("Text view".into()) - } -} - impl Render for TextViewDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let colors = cx.theme().colors; @@ -4118,12 +3932,6 @@ struct SidebarDemo { selected: Option, } -impl Panel for SidebarDemo { - fn title(&self, _: &App) -> Option { - Some("Sidebar".into()) - } -} - impl Render for SidebarDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -4292,12 +4100,6 @@ impl ResizeDemo { const WIDTH_MAX_REMS: f32 = 20.; } -impl Panel for ResizeDemo { - fn title(&self, _: &App) -> Option { - Some("Resize handle".into()) - } -} - impl Render for ResizeDemo { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let view = cx.entity(); @@ -4376,12 +4178,6 @@ impl Render for ResizeDemo { struct ThemeDemo; -impl Panel for ThemeDemo { - fn title(&self, _: &App) -> Option { - Some("Theme".into()) - } -} - impl Render for ThemeDemo { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); @@ -4546,18 +4342,6 @@ fn main() { KeyBinding::new("ctrl-k", OpenCommandPalette, None), ]); - let layout_state = LayoutState::new(cx); - let dock_state = DockState::new(cx); - let layout_for_dock = layout_state.clone(); - - dock_state.update(cx, |dock, _| { - dock.on_open_right_sidebar(move |cx| { - layout_for_dock.update(cx, |state, cx| { - state.set_right_sidebar_visible(true, cx); - }); - }); - }); - let bounds = Bounds::centered(None, size(px(960.0), px(640.0)), cx); let theme = cx.theme(); @@ -4585,16 +4369,20 @@ fn main() { cx.refresh_windows(); }) .detach(); + let toasts = cx.new(|_| Toasts::default()); + let alerts = cx.new(|_| Alerts::default()); let gallery = cx.new(|_| Gallery { - layout_state: layout_state.clone(), - dock_state: dock_state.clone(), + toasts: toasts.clone(), + alerts: alerts.clone(), + tabs: Vec::new(), + active: None, + views: HashMap::new(), + split_panel: None, palette: None, palette_runs: Vec::new(), dialog_open: false, alert_open: false, - sidebar_transparent: true, - grain: true, - titlebar: false, + menu_open: false, }); let palette = cx.new(|cx| { @@ -4628,15 +4416,7 @@ fn main() { cx.notify(); }); - dock_state.update(cx, |dock, cx| { - Gallery::register_panels( - dock, - layout_state.clone(), - palette.clone(), - gallery.downgrade(), - cx, - ); - + gallery.update(cx, |gallery, cx| { let first = if std::env::var("GPUI_FIELD_AUTOPLAY").is_ok() { eprintln!("[field-probe] autoplay: opening field panel"); "field" @@ -4644,7 +4424,7 @@ fn main() { "welcome" }; - dock.open_panel(first, window, cx); + gallery.open_demo(first, window, cx); }); gallery