style: cargo fmt with the workspace tab policy (hard_tabs)

Whitespace only; the fork has no own rustfmt.toml so the Oak root
policy applies.
This commit is contained in:
2026-08-11 23:06:13 +08:00
parent 507d7e6e8d
commit af5482d774
318 changed files with 132564 additions and 132170 deletions
File diff suppressed because it is too large Load Diff
+46 -36
View File
@@ -27,12 +27,12 @@
//! Everything here is subject to change when the feature is implemented for
//! real.
use crate::colors::DefaultColors;
use crate::dock::PanelHandle;
use crate::{
div, px, Context, IntoElement, ParentElement, Pixels, Point, Render, Styled, Window,
WindowBounds,
Context, IntoElement, ParentElement, Pixels, Point, Render, Styled, Window, WindowBounds, div,
px,
};
use crate::colors::DefaultColors;
/// A window hosting a single undocked panel.
///
@@ -46,43 +46,53 @@ use crate::colors::DefaultColors;
/// [`DockLayoutState`](crate::dock::DockLayoutState) can restore the window
/// geometry.
pub struct FloatingPanelWindow {
/// The panel hosted by this window.
panel: PanelHandle,
/// Last known window position, mirrored into layout snapshots.
#[allow(dead_code)] // read once floating-window geometry is persisted
origin: Point<Pixels>,
/// The panel hosted by this window.
panel: PanelHandle,
/// Last known window position, mirrored into layout snapshots.
#[allow(dead_code)] // read once floating-window geometry is persisted
origin: Point<Pixels>,
}
impl FloatingPanelWindow {
/// Creates the content view for a new floating window hosting `panel`.
///
/// The caller is responsible for opening the window with
/// `cx.open_window` and remembering its handle so it can be closed when
/// the panel re-docks. `initial_bounds` comes from the saved layout, or
/// from a sensible default near the main window.
pub fn new(
panel: PanelHandle,
initial_bounds: Option<WindowBounds>,
cx: &mut Context<Self>,
) -> Self {
let _ = cx;
let origin = initial_bounds
.map(|bounds| bounds.get_bounds().origin)
.unwrap_or_else(|| Point::new(px(0.0), px(0.0)));
Self { panel, origin }
}
/// Creates the content view for a new floating window hosting `panel`.
///
/// The caller is responsible for opening the window with
/// `cx.open_window` and remembering its handle so it can be closed when
/// the panel re-docks. `initial_bounds` comes from the saved layout, or
/// from a sensible default near the main window.
pub fn new(
panel: PanelHandle,
initial_bounds: Option<WindowBounds>,
cx: &mut Context<Self>,
) -> Self {
let _ = cx;
let origin = initial_bounds
.map(|bounds| bounds.get_bounds().origin)
.unwrap_or_else(|| Point::new(px(0.0), px(0.0)));
Self { panel, origin }
}
}
impl Render for FloatingPanelWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let _ = window;
let title = self.panel.title().clone();
let view = self.panel.view().clone();
div().flex().flex_col().h_full().bg(cx.default_colors().clone().background)
.child(
div().flex().flex_row().items_center().w_full().px_2().py_1()
.child(div().flex_1().text_xs().truncate().child(title)),
)
.child(div().flex_1().min_h_0().overflow_hidden().child(view))
}
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let _ = window;
let title = self.panel.title().clone();
let view = self.panel.view().clone();
div()
.flex()
.flex_col()
.h_full()
.bg(cx.default_colors().clone().background)
.child(
div()
.flex()
.flex_row()
.items_center()
.w_full()
.px_2()
.py_1()
.child(div().flex_1().text_xs().truncate().child(title)),
)
.child(div().flex_1().min_h_0().overflow_hidden().child(view))
}
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -85,6 +85,6 @@ pub use dock_area::{DockArea, DockEvent};
pub use floating::FloatingPanelWindow;
pub(crate) use layout::path_key;
pub use layout::{
DockLayout, DockLayoutState, DockNode, DropTarget, DropZone, NodePath, PanelRegistry,
DockLayout, DockLayoutState, DockNode, DropTarget, DropZone, NodePath, PanelRegistry,
};
pub use panel::{DockPanel, PanelEvent, PanelHandle, PanelId};
+141 -141
View File
@@ -8,8 +8,8 @@
//! needs without downcasting.
use crate::{
AnyElement, AnyView, App, Context, Entity, EventEmitter, Render, SharedString, Subscription,
Window,
AnyElement, AnyView, App, Context, Entity, EventEmitter, Render, SharedString, Subscription,
Window,
};
use serde::{Deserialize, Serialize};
use std::fmt;
@@ -31,25 +31,25 @@ use std::fmt;
pub struct PanelId(u64);
impl PanelId {
/// Creates a panel id from a raw numeric value.
///
/// The value only needs to be unique within the owning
/// [`DockArea`](crate::dock::DockArea)(crate::dock::DockArea); a simple per-application counter
/// (or a hash of a stable name) is sufficient.
pub const fn new(raw: u64) -> Self {
Self(raw)
}
/// Creates a panel id from a raw numeric value.
///
/// The value only needs to be unique within the owning
/// [`DockArea`](crate::dock::DockArea)(crate::dock::DockArea); a simple per-application counter
/// (or a hash of a stable name) is sufficient.
pub const fn new(raw: u64) -> Self {
Self(raw)
}
/// Returns the raw numeric value backing this id.
pub const fn raw(self) -> u64 {
self.0
}
/// Returns the raw numeric value backing this id.
pub const fn raw(self) -> u64 {
self.0
}
}
impl fmt::Display for PanelId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "panel-{}", self.0)
}
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "panel-{}", self.0)
}
}
/// Events a dock panel can emit to its containing [`DockArea`](crate::dock::DockArea)(crate::dock::DockArea).
@@ -60,24 +60,24 @@ impl fmt::Display for PanelId {
/// flow — without the panel needing a direct reference to the dock.
#[derive(Clone, Debug)]
pub enum PanelEvent {
/// The panel asked to be closed (e.g. its own close affordance was
/// invoked).
///
/// The dock area does not remove the panel unconditionally: it first
/// consults [`DockPanel::should_close`], then calls [`DockPanel::on_close`]
/// and removes the panel only if closing was confirmed.
CloseRequested,
/// The panel's content gained keyboard focus.
///
/// The dock area uses this to keep its own `focused_panel` bookkeeping in
/// sync and to emit
/// [`DockEvent::PanelFocused`](crate::dock::DockEvent::PanelFocused).
Focused,
/// The panel's title changed; the tab strip should re-render the label.
///
/// The new title is read back through [`DockPanel::title`] rather than
/// carried in the event, so panels never have to clone it.
TitleChanged,
/// The panel asked to be closed (e.g. its own close affordance was
/// invoked).
///
/// The dock area does not remove the panel unconditionally: it first
/// consults [`DockPanel::should_close`], then calls [`DockPanel::on_close`]
/// and removes the panel only if closing was confirmed.
CloseRequested,
/// The panel's content gained keyboard focus.
///
/// The dock area uses this to keep its own `focused_panel` bookkeeping in
/// sync and to emit
/// [`DockEvent::PanelFocused`](crate::dock::DockEvent::PanelFocused).
Focused,
/// The panel's title changed; the tab strip should re-render the label.
///
/// The new title is read back through [`DockPanel::title`] rather than
/// carried in the event, so panels never have to clone it.
TitleChanged,
}
/// A view that can live inside a [`DockArea`](crate::dock::DockArea)(crate::dock::DockArea).
@@ -120,56 +120,56 @@ pub enum PanelEvent {
/// }
/// ```
pub trait DockPanel: Render + EventEmitter<PanelEvent> + 'static {
/// Returns the stable id of this panel.
///
/// Must return the same value for the whole lifetime of the view and must
/// be unique among all panels added to one dock area.
fn panel_id(&self) -> PanelId;
/// Returns the stable id of this panel.
///
/// Must return the same value for the whole lifetime of the view and must
/// be unique among all panels added to one dock area.
fn panel_id(&self) -> PanelId;
/// Returns the plain-text title shown in the tab strip and, where
/// relevant, in window titles for floated panels.
///
/// Called on every render of the containing tab bar, so it should be
/// cheap. Emit [`PanelEvent::TitleChanged`] after changing whatever state
/// feeds this.
fn title(&self, cx: &App) -> SharedString;
/// Returns the plain-text title shown in the tab strip and, where
/// relevant, in window titles for floated panels.
///
/// Called on every render of the containing tab bar, so it should be
/// cheap. Emit [`PanelEvent::TitleChanged`] after changing whatever state
/// feeds this.
fn title(&self, cx: &App) -> SharedString;
/// Returns the element rendered inside this panel's tab.
///
/// The default tab bar renders [`title`](DockPanel::title) when this is
/// not customized, but panels may return richer content (icon, dirty
/// indicator, close-on-middle-click affordances). The returned element
/// must not handle close or drag interactions itself — the tab strip
/// overlays those.
fn tab_content(&self, cx: &App) -> AnyElement;
/// Returns the element rendered inside this panel's tab.
///
/// The default tab bar renders [`title`](DockPanel::title) when this is
/// not customized, but panels may return richer content (icon, dirty
/// indicator, close-on-middle-click affordances). The returned element
/// must not handle close or drag interactions itself — the tab strip
/// overlays those.
fn tab_content(&self, cx: &App) -> AnyElement;
/// Whether this panel shows a close button and can be closed by the user.
///
/// Non-closable panels can still be removed programmatically via
/// [`DockArea::remove_panel`](crate::dock::DockArea::remove_panel).
/// Defaults to `true`.
fn closable(&self) -> bool {
true
}
/// Whether this panel shows a close button and can be closed by the user.
///
/// Non-closable panels can still be removed programmatically via
/// [`DockArea::remove_panel`](crate::dock::DockArea::remove_panel).
/// Defaults to `true`.
fn closable(&self) -> bool {
true
}
/// Called when the user has asked to close this panel, before removal.
///
/// Return `true` to allow the close, `false` to veto it (for example
/// after showing an "unsaved changes" dialog). This may be called on the
/// same event-loop turn as the close request, so asynchronous
/// confirmations should veto now and re-trigger closing later through
/// [`DockArea::remove_panel`](crate::dock::DockArea::remove_panel).
/// Defaults to `true`.
fn should_close(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
true
}
/// Called when the user has asked to close this panel, before removal.
///
/// Return `true` to allow the close, `false` to veto it (for example
/// after showing an "unsaved changes" dialog). This may be called on the
/// same event-loop turn as the close request, so asynchronous
/// confirmations should veto now and re-trigger closing later through
/// [`DockArea::remove_panel`](crate::dock::DockArea::remove_panel).
/// Defaults to `true`.
fn should_close(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
true
}
/// Called after a close was confirmed and before the panel is removed
/// from the layout.
///
/// Use this to release resources tied to the dock (subscriptions,
/// scratch entities). The default implementation does nothing.
fn on_close(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
/// Called after a close was confirmed and before the panel is removed
/// from the layout.
///
/// Use this to release resources tied to the dock (subscriptions,
/// scratch entities). The default implementation does nothing.
fn on_close(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
}
/// A type-erased panel plus the metadata the dock chrome needs.
@@ -182,74 +182,74 @@ pub trait DockPanel: Render + EventEmitter<PanelEvent> + 'static {
/// Construct with [`PanelHandle::new`]; pass to
/// [`DockArea::add_panel`](crate::dock::DockArea::add_panel)(crate::dock::DockArea::add_panel).
pub struct PanelHandle {
id: PanelId,
view: AnyView,
title: SharedString,
closable: bool,
/// Subscription to the panel's [`PanelEvent`]s while it is held by a
/// dock area, installed by [`DockArea`](crate::dock::DockArea) when the
/// panel is added.
subscription: Option<Subscription>,
id: PanelId,
view: AnyView,
title: SharedString,
closable: bool,
/// Subscription to the panel's [`PanelEvent`]s while it is held by a
/// dock area, installed by [`DockArea`](crate::dock::DockArea) when the
/// panel is added.
subscription: Option<Subscription>,
}
impl PanelHandle {
/// Wraps a panel view, snapshotting its current metadata.
///
/// `panel` must implement [`DockPanel`](crate::dock::DockPanel). The handle keeps the view alive
/// for as long as it is stored in the dock area.
///
/// # Panics
///
/// Does not panic, but adding two handles with the same
/// [`DockPanel::panel_id`] to one dock area is rejected there.
pub fn new<P: DockPanel>(panel: Entity<P>, cx: &App) -> Self {
let id = panel.read(cx).panel_id();
let title = panel.read(cx).title(cx);
let closable = panel.read(cx).closable();
Self {
id,
view: panel.into(),
title,
closable,
subscription: None,
}
}
/// Wraps a panel view, snapshotting its current metadata.
///
/// `panel` must implement [`DockPanel`](crate::dock::DockPanel). The handle keeps the view alive
/// for as long as it is stored in the dock area.
///
/// # Panics
///
/// Does not panic, but adding two handles with the same
/// [`DockPanel::panel_id`] to one dock area is rejected there.
pub fn new<P: DockPanel>(panel: Entity<P>, cx: &App) -> Self {
let id = panel.read(cx).panel_id();
let title = panel.read(cx).title(cx);
let closable = panel.read(cx).closable();
Self {
id,
view: panel.into(),
title,
closable,
subscription: None,
}
}
/// Returns the id the panel reported at snapshot time.
pub fn panel_id(&self) -> PanelId {
self.id
}
/// Returns the id the panel reported at snapshot time.
pub fn panel_id(&self) -> PanelId {
self.id
}
/// Returns the cached tab title.
///
/// May be stale between a title change and the dock area processing
/// [`PanelEvent::TitleChanged`]; treat as display-only.
pub fn title(&self) -> &SharedString {
&self.title
}
/// Returns the cached tab title.
///
/// May be stale between a title change and the dock area processing
/// [`PanelEvent::TitleChanged`]; treat as display-only.
pub fn title(&self) -> &SharedString {
&self.title
}
/// Returns the cached value of [`DockPanel::closable`].
pub fn closable(&self) -> bool {
self.closable
}
/// Returns the cached value of [`DockPanel::closable`].
pub fn closable(&self) -> bool {
self.closable
}
/// Returns the type-erased panel view.
pub fn view(&self) -> &AnyView {
&self.view
}
/// Returns the type-erased panel view.
pub fn view(&self) -> &AnyView {
&self.view
}
/// Returns the subscription to this panel's [`PanelEvent`]s, if the dock
/// area has installed one.
#[allow(dead_code)] // reserved for the dock's panel-event bookkeeping
pub(crate) fn subscription(&self) -> &Option<Subscription> {
&self.subscription
}
/// Returns the subscription to this panel's [`PanelEvent`]s, if the dock
/// area has installed one.
#[allow(dead_code)] // reserved for the dock's panel-event bookkeeping
pub(crate) fn subscription(&self) -> &Option<Subscription> {
&self.subscription
}
/// Installs (or replaces) the subscription to this panel's [`PanelEvent`]s.
///
/// Used by [`DockArea`](crate::dock::DockArea) when the panel is added or
/// restored; the previous subscription, if any, is dropped.
pub(crate) fn set_subscription(&mut self, subscription: Option<Subscription>) {
self.subscription = subscription;
}
/// Installs (or replaces) the subscription to this panel's [`PanelEvent`]s.
///
/// Used by [`DockArea`](crate::dock::DockArea) when the panel is added or
/// restored; the previous subscription, if any, is dropped.
pub(crate) fn set_subscription(&mut self, subscription: Option<Subscription>) {
self.subscription = subscription;
}
}
+165 -169
View File
@@ -6,47 +6,46 @@
//! split's `ratio` through
//! [`DockLayout::resize_split`](crate::dock::DockLayout::resize_split).
use crate::{
div, px, App, AppContext, Axis, ClickEvent, Context, ElementId, EventEmitter,
InteractiveElement, IntoElement, Pixels, Point, Render, StatefulInteractiveElement, Styled,
Window,
};
use crate::colors::DefaultColors;
use crate::{
App, AppContext, Axis, ClickEvent, Context, ElementId, EventEmitter, InteractiveElement,
IntoElement, Pixels, Point, Render, StatefulInteractiveElement, Styled, Window, div, px,
};
use super::{NodePath, path_key};
/// Events emitted by a [`SplitHandle`] toward its owning [`DockArea`].
#[derive(Clone, Debug)]
pub(crate) enum SplitHandleEvent {
/// The user dragged the handle; the boundary at `index` of the split at
/// `path` should be resized to `ratio` (child `index`'s share of the
/// pair, already clamped to the allowed range).
ResizeRequested {
/// Path of the split node to resize.
path: NodePath,
/// The boundary being moved: between children `index` and `index + 1`.
index: usize,
/// Desired new ratio, already clamped to the allowed range.
ratio: f32,
},
/// The user double-clicked the handle; the boundary at `index` of the
/// split at `path` should be reset to [`SplitHandle::RESET_RATIO`].
ResetRequested {
/// Path of the split node to resize.
path: NodePath,
/// The boundary being moved: between children `index` and `index + 1`.
index: usize,
},
/// The user dragged the handle; the boundary at `index` of the split at
/// `path` should be resized to `ratio` (child `index`'s share of the
/// pair, already clamped to the allowed range).
ResizeRequested {
/// Path of the split node to resize.
path: NodePath,
/// The boundary being moved: between children `index` and `index + 1`.
index: usize,
/// Desired new ratio, already clamped to the allowed range.
ratio: f32,
},
/// The user double-clicked the handle; the boundary at `index` of the
/// split at `path` should be reset to [`SplitHandle::RESET_RATIO`].
ResetRequested {
/// Path of the split node to resize.
path: NodePath,
/// The boundary being moved: between children `index` and `index + 1`.
index: usize,
},
}
/// The payload of a handle drag; carried by the drag-and-drop system so the
/// split container can identify which handle is being dragged.
#[derive(Clone, Debug)]
pub(crate) struct SplitHandleDrag {
/// Path of the split being resized.
pub(crate) path: NodePath,
/// The boundary being dragged: between children `index` and `index + 1`.
pub(crate) index: usize,
/// Path of the split being resized.
pub(crate) path: NodePath,
/// The boundary being dragged: between children `index` and `index + 1`.
pub(crate) index: usize,
}
/// A resize handle between two children of a split node.
@@ -73,171 +72,168 @@ pub(crate) struct SplitHandleDrag {
/// in the tree; paths are re-derived on every render, never stored across
/// frames.
pub(crate) struct SplitHandle {
/// Axis along which the parent split lays out its children; the handle
/// itself extends along the perpendicular axis.
direction: Axis,
/// Path of the split node this handle resizes, valid for the current
/// frame only.
path: NodePath,
/// Boundary this handle moves: between children `index` and `index + 1`.
index: usize,
/// Pointer position where the current drag started, if dragging.
drag_origin: Option<Pixels>,
/// Axis along which the parent split lays out its children; the handle
/// itself extends along the perpendicular axis.
direction: Axis,
/// Path of the split node this handle resizes, valid for the current
/// frame only.
path: NodePath,
/// Boundary this handle moves: between children `index` and `index + 1`.
index: usize,
/// Pointer position where the current drag started, if dragging.
drag_origin: Option<Pixels>,
}
impl SplitHandle {
/// Thickness of the handle's interactive area, in logical pixels. The
/// visual divider may be thinner; the wider hitbox makes the handle
/// grabbable.
pub(crate) const HITBOX: Pixels = Pixels(6.0);
/// Thickness of the handle's interactive area, in logical pixels. The
/// visual divider may be thinner; the wider hitbox makes the handle
/// grabbable.
pub(crate) const HITBOX: Pixels = Pixels(6.0);
/// Minimum extent, in logical pixels, that a split child may be resized
/// to by dragging. Expressed as a fraction of the parent extent when
/// computing the drag clamp.
pub(crate) const MIN_CHILD_EXTENT: Pixels = Pixels(120.0);
/// Minimum extent, in logical pixels, that a split child may be resized
/// to by dragging. Expressed as a fraction of the parent extent when
/// computing the drag clamp.
pub(crate) const MIN_CHILD_EXTENT: Pixels = Pixels(120.0);
/// The ratio a double-click resets to (even split).
pub(crate) const RESET_RATIO: f32 = 0.5;
/// The ratio a double-click resets to (even split).
pub(crate) const RESET_RATIO: f32 = 0.5;
/// Creates a handle for the boundary at `index` of the split at `path`.
pub(crate) fn new(direction: Axis, path: NodePath, index: usize) -> Self {
Self {
direction,
path,
index,
drag_origin: None,
}
}
/// Creates a handle for the boundary at `index` of the split at `path`.
pub(crate) fn new(direction: Axis, path: NodePath, index: usize) -> Self {
Self {
direction,
path,
index,
drag_origin: None,
}
}
/// Begins a drag, remembering the pointer origin.
pub(crate) fn begin_drag(&mut self, origin: Pixels) {
self.drag_origin = Some(origin);
}
/// Begins a drag, remembering the pointer origin.
pub(crate) fn begin_drag(&mut self, origin: Pixels) {
self.drag_origin = Some(origin);
}
/// Applies an in-progress drag: converts the pointer delta to a ratio
/// delta relative to the pair extent and emits a
/// [`SplitHandleEvent::ResizeRequested`].
///
/// `start_ratio` is the share of the `index` child within its pair at
/// drag start, re-read from the layout by the owning dock area on every
/// move so external edits during the drag are respected; `pair_extent` is
/// the combined on-screen extent of the two children, in pixels.
pub(crate) fn drag_to(
&mut self,
position: Pixels,
pair_extent: Pixels,
start_ratio: f32,
cx: &mut Context<Self>,
) {
let Some(origin) = self.drag_origin else {
return;
};
if pair_extent.0 <= 0.0 {
return;
}
// Keep both children above MIN_CHILD_EXTENT, but never clamp harder
// than a quarter of the pair so tiny parents stay resizable.
let min_ratio = (Self::MIN_CHILD_EXTENT.0 / pair_extent.0).min(0.25);
let max_ratio = 1.0 - min_ratio;
let ratio = (start_ratio + (position.0 - origin.0) / pair_extent.0)
.clamp(min_ratio, max_ratio);
cx.emit(SplitHandleEvent::ResizeRequested {
path: self.path.clone(),
index: self.index,
ratio,
});
cx.notify();
}
/// Applies an in-progress drag: converts the pointer delta to a ratio
/// delta relative to the pair extent and emits a
/// [`SplitHandleEvent::ResizeRequested`].
///
/// `start_ratio` is the share of the `index` child within its pair at
/// drag start, re-read from the layout by the owning dock area on every
/// move so external edits during the drag are respected; `pair_extent` is
/// the combined on-screen extent of the two children, in pixels.
pub(crate) fn drag_to(
&mut self,
position: Pixels,
pair_extent: Pixels,
start_ratio: f32,
cx: &mut Context<Self>,
) {
let Some(origin) = self.drag_origin else {
return;
};
if pair_extent.0 <= 0.0 {
return;
}
// Keep both children above MIN_CHILD_EXTENT, but never clamp harder
// than a quarter of the pair so tiny parents stay resizable.
let min_ratio = (Self::MIN_CHILD_EXTENT.0 / pair_extent.0).min(0.25);
let max_ratio = 1.0 - min_ratio;
let ratio =
(start_ratio + (position.0 - origin.0) / pair_extent.0).clamp(min_ratio, max_ratio);
cx.emit(SplitHandleEvent::ResizeRequested {
path: self.path.clone(),
index: self.index,
ratio,
});
cx.notify();
}
/// Ends the current drag, if any.
pub(crate) fn end_drag(&mut self) {
self.drag_origin = None;
}
/// Ends the current drag, if any.
pub(crate) fn end_drag(&mut self) {
self.drag_origin = None;
}
/// Emits a [`SplitHandleEvent::ResetRequested`] for a double-click.
pub(crate) fn reset(&mut self, cx: &mut Context<Self>) {
cx.emit(SplitHandleEvent::ResetRequested {
path: self.path.clone(),
index: self.index,
});
cx.notify();
}
/// Emits a [`SplitHandleEvent::ResetRequested`] for a double-click.
pub(crate) fn reset(&mut self, cx: &mut Context<Self>) {
cx.emit(SplitHandleEvent::ResetRequested {
path: self.path.clone(),
index: self.index,
});
cx.notify();
}
}
impl EventEmitter<SplitHandleEvent> for SplitHandle {}
impl Render for SplitHandle {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = cx.default_colors().clone();
let direction = self.direction;
let handle = cx.entity();
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = cx.default_colors().clone();
let direction = self.direction;
let handle = cx.entity();
// Begins the drag on the handle (recording the pointer origin) and
// returns the ghost view shown under the pointer.
let ghost_ctor = move |_drag: &SplitHandleDrag,
origin: Point<Pixels>,
_window: &mut Window,
cx: &mut App| {
handle.update(cx, |handle, _cx| {
handle.begin_drag(if direction == Axis::Horizontal {
origin.x
} else {
origin.y
});
});
cx.new(|_cx| SplitDragGhost { direction })
};
// Begins the drag on the handle (recording the pointer origin) and
// returns the ghost view shown under the pointer.
let ghost_ctor = move |_drag: &SplitHandleDrag,
origin: Point<Pixels>,
_window: &mut Window,
cx: &mut App| {
handle.update(cx, |handle, _cx| {
handle.begin_drag(if direction == Axis::Horizontal {
origin.x
} else {
origin.y
});
});
cx.new(|_cx| SplitDragGhost { direction })
};
let mut root = div()
.id(ElementId::named_usize("dock-split-handle", path_key(&self.path)))
.flex_none()
.bg(colors.separator)
.on_click(cx.listener(move |this, event: &ClickEvent, _window, cx| {
if event.click_count() >= 2 {
this.reset(cx);
}
}));
let mut root = div()
.id(ElementId::named_usize(
"dock-split-handle",
path_key(&self.path),
))
.flex_none()
.bg(colors.separator)
.on_click(cx.listener(move |this, event: &ClickEvent, _window, cx| {
if event.click_count() >= 2 {
this.reset(cx);
}
}));
// A horizontal split stacks children side by side, so its divider is
// a vertical bar and vice versa.
match direction {
Axis::Horizontal => {
root = root
.w(px(Self::HITBOX.0))
.h_full()
.cursor_col_resize();
}
Axis::Vertical => {
root = root
.w_full()
.h(px(Self::HITBOX.0))
.cursor_row_resize();
}
}
// A horizontal split stacks children side by side, so its divider is
// a vertical bar and vice versa.
match direction {
Axis::Horizontal => {
root = root.w(px(Self::HITBOX.0)).h_full().cursor_col_resize();
}
Axis::Vertical => {
root = root.w_full().h(px(Self::HITBOX.0)).cursor_row_resize();
}
}
root.on_drag(
SplitHandleDrag {
path: self.path.clone(),
index: self.index,
},
ghost_ctor,
)
}
root.on_drag(
SplitHandleDrag {
path: self.path.clone(),
index: self.index,
},
ghost_ctor,
)
}
}
/// The floating view shown under the pointer while a handle is being dragged.
struct SplitDragGhost {
direction: Axis,
direction: Axis,
}
impl Render for SplitDragGhost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = cx.default_colors().clone();
let mut ghost = div().bg(colors.border).rounded_sm();
match self.direction {
Axis::Horizontal => ghost = ghost.w(px(2.0)).h(px(64.0)),
Axis::Vertical => ghost = ghost.w(px(64.0)).h(px(2.0)),
}
ghost
}
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = cx.default_colors().clone();
let mut ghost = div().bg(colors.border).rounded_sm();
match self.direction {
Axis::Horizontal => ghost = ghost.w(px(2.0)).h(px(64.0)),
Axis::Vertical => ghost = ghost.w(px(64.0)).h(px(2.0)),
}
ghost
}
}
+256 -247
View File
@@ -7,46 +7,46 @@
//! tracks the active tab, hosts close buttons, and is the drag source for
//! both tab reordering and dock drags.
use crate::{
div, px, App, AppContext, ClickEvent, Context, DragMoveEvent, ElementId, EventEmitter,
InteractiveElement, IntoElement, ParentElement, Pixels, Point, Render, ScrollDelta,
ScrollWheelEvent, SharedString, StatefulInteractiveElement, Styled, Window,
};
use crate::colors::DefaultColors;
use crate::{
App, AppContext, ClickEvent, Context, DragMoveEvent, ElementId, EventEmitter,
InteractiveElement, IntoElement, ParentElement, Pixels, Point, Render, ScrollDelta,
ScrollWheelEvent, SharedString, StatefulInteractiveElement, Styled, Window, div, px,
};
use super::PanelId;
/// Events emitted by a [`TabBar`] toward its owning [`DockArea`].
#[derive(Clone, Debug)]
pub(crate) enum TabBarEvent {
/// The tab order or the active tab changed in place.
Reordered {
/// The new tab order (mirrors the owning `Tabs` node's `panels`).
tabs: Vec<PanelId>,
/// Index of the active tab in `tabs`.
active: usize,
},
/// The user clicked the close button of a tab.
CloseRequested(PanelId),
/// A tab was dragged out of the strip; the dock area takes over the drag.
DockDragStarted {
/// The panel being dragged.
panel: PanelId,
/// Pointer position in window coordinates.
position: Point<Pixels>,
},
/// The tab order or the active tab changed in place.
Reordered {
/// The new tab order (mirrors the owning `Tabs` node's `panels`).
tabs: Vec<PanelId>,
/// Index of the active tab in `tabs`.
active: usize,
},
/// The user clicked the close button of a tab.
CloseRequested(PanelId),
/// A tab was dragged out of the strip; the dock area takes over the drag.
DockDragStarted {
/// The panel being dragged.
panel: PanelId,
/// Pointer position in window coordinates.
position: Point<Pixels>,
},
}
/// A single tab's computed geometry within the strip, cached during render
/// for hit-testing (close button, reorder, drag start).
pub(crate) struct TabGeometry {
/// The panel this tab shows.
#[allow(dead_code)] // retained for future hit-testing of individual tabs
pub panel: PanelId,
/// Left edge of the tab relative to the strip.
pub x: Pixels,
/// Width of the tab.
pub width: Pixels,
/// The panel this tab shows.
#[allow(dead_code)] // retained for future hit-testing of individual tabs
pub panel: PanelId,
/// Left edge of the tab relative to the strip.
pub x: Pixels,
/// Width of the tab.
pub width: Pixels,
}
/// The tab strip for one `Tabs` node.
@@ -75,252 +75,261 @@ pub(crate) struct TabGeometry {
/// `active < tabs.len()`; the dock area re-creates or syncs the strip
/// whenever the tree changes rather than the strip mutating the tree itself.
pub(crate) struct TabBar {
/// Panels in tab order, mirroring the owning `Tabs` node.
tabs: Vec<PanelId>,
/// Index of the active tab.
active: usize,
/// Horizontal scroll offset for overflowed strips.
scroll_offset: Pixels,
/// Per-tab geometry from the last frame, for hit-testing.
geometry: Vec<TabGeometry>,
/// Tab titles from the last sync, rendered as the tab labels.
titles: Vec<SharedString>,
/// Per-tab closability from the last sync.
closable: Vec<bool>,
/// Panels in tab order, mirroring the owning `Tabs` node.
tabs: Vec<PanelId>,
/// Index of the active tab.
active: usize,
/// Horizontal scroll offset for overflowed strips.
scroll_offset: Pixels,
/// Per-tab geometry from the last frame, for hit-testing.
geometry: Vec<TabGeometry>,
/// Tab titles from the last sync, rendered as the tab labels.
titles: Vec<SharedString>,
/// Per-tab closability from the last sync.
closable: Vec<bool>,
}
impl TabBar {
/// Minimum width a tab is allowed to shrink to before the strip starts
/// scrolling instead.
pub(crate) const MIN_TAB_WIDTH: Pixels = Pixels(80.0);
/// Minimum width a tab is allowed to shrink to before the strip starts
/// scrolling instead.
pub(crate) const MIN_TAB_WIDTH: Pixels = Pixels(80.0);
/// Creates a strip for the given tabs; `active` is clamped into range.
pub(crate) fn new(tabs: Vec<PanelId>, active: usize) -> Self {
Self {
active: active.min(tabs.len().saturating_sub(1)),
tabs,
scroll_offset: Pixels(0.0),
geometry: Vec::new(),
titles: Vec::new(),
closable: Vec::new(),
}
}
/// Creates a strip for the given tabs; `active` is clamped into range.
pub(crate) fn new(tabs: Vec<PanelId>, active: usize) -> Self {
Self {
active: active.min(tabs.len().saturating_sub(1)),
tabs,
scroll_offset: Pixels(0.0),
geometry: Vec::new(),
titles: Vec::new(),
closable: Vec::new(),
}
}
/// Syncs the strip with the owning node after a tree edit, preserving
/// scroll position where possible.
///
/// Called from the dock area during render, so it must not notify.
pub(crate) fn sync(
&mut self,
tabs: &[PanelId],
active: usize,
titles: &[SharedString],
closable: &[bool],
_cx: &mut Context<Self>,
) {
self.tabs = tabs.to_vec();
self.titles = titles.to_vec();
self.closable = closable.to_vec();
self.active = active.min(self.tabs.len().saturating_sub(1));
}
/// Syncs the strip with the owning node after a tree edit, preserving
/// scroll position where possible.
///
/// Called from the dock area during render, so it must not notify.
pub(crate) fn sync(
&mut self,
tabs: &[PanelId],
active: usize,
titles: &[SharedString],
closable: &[bool],
_cx: &mut Context<Self>,
) {
self.tabs = tabs.to_vec();
self.titles = titles.to_vec();
self.closable = closable.to_vec();
self.active = active.min(self.tabs.len().saturating_sub(1));
}
/// Returns the index of the tab containing `point` (strip-relative
/// coordinates), using the cached geometry.
pub(crate) fn tab_index_at(&self, point: Point<Pixels>) -> Option<usize> {
let count = self.geometry.partition_point(|tab| tab.x.0 <= point.x.0);
if count == 0 {
return None;
}
// `count - 1` is the last tab whose left edge is left of the point;
// tabs are contiguous, so that tab contains the point.
Some(count - 1)
}
/// Returns the index of the tab containing `point` (strip-relative
/// coordinates), using the cached geometry.
pub(crate) fn tab_index_at(&self, point: Point<Pixels>) -> Option<usize> {
let count = self.geometry.partition_point(|tab| tab.x.0 <= point.x.0);
if count == 0 {
return None;
}
// `count - 1` is the last tab whose left edge is left of the point;
// tabs are contiguous, so that tab contains the point.
Some(count - 1)
}
/// Reorders the tab at `from` to position `to`, keeping the active tab
/// pointing at the same panel, and emits [`TabBarEvent::Reordered`] so
/// the dock area can rewrite the owning node.
///
/// No-op if either index is out of range or `from == to`.
pub(crate) fn move_tab(&mut self, from: usize, to: usize, cx: &mut Context<Self>) {
if from >= self.tabs.len() || to >= self.tabs.len() || from == to {
return;
}
let active_panel = self.tabs.get(self.active).copied();
let panel = self.tabs.remove(from);
let insert_at = if to > from { to - 1 } else { to };
self.tabs.insert(insert_at, panel);
self.active = active_panel
.and_then(|p| self.tabs.iter().position(|tab| *tab == p))
.unwrap_or(0);
cx.emit(TabBarEvent::Reordered {
tabs: self.tabs.clone(),
active: self.active,
});
cx.notify();
}
/// Reorders the tab at `from` to position `to`, keeping the active tab
/// pointing at the same panel, and emits [`TabBarEvent::Reordered`] so
/// the dock area can rewrite the owning node.
///
/// No-op if either index is out of range or `from == to`.
pub(crate) fn move_tab(&mut self, from: usize, to: usize, cx: &mut Context<Self>) {
if from >= self.tabs.len() || to >= self.tabs.len() || from == to {
return;
}
let active_panel = self.tabs.get(self.active).copied();
let panel = self.tabs.remove(from);
let insert_at = if to > from { to - 1 } else { to };
self.tabs.insert(insert_at, panel);
self.active = active_panel
.and_then(|p| self.tabs.iter().position(|tab| *tab == p))
.unwrap_or(0);
cx.emit(TabBarEvent::Reordered {
tabs: self.tabs.clone(),
active: self.active,
});
cx.notify();
}
/// Makes the tab at `index` active, scrolling it into view first.
fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
if index >= self.tabs.len() {
return;
}
self.active = index;
self.scroll_tab_into_view(index, window, cx);
cx.emit(TabBarEvent::Reordered {
tabs: self.tabs.clone(),
active: self.active,
});
cx.notify();
}
/// Makes the tab at `index` active, scrolling it into view first.
fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
if index >= self.tabs.len() {
return;
}
self.active = index;
self.scroll_tab_into_view(index, window, cx);
cx.emit(TabBarEvent::Reordered {
tabs: self.tabs.clone(),
active: self.active,
});
cx.notify();
}
/// Scrolls the strip so the tab at `index` is fully visible.
///
/// The strip does not know the exact width of the visible viewport, so
/// this approximates it with the window width — good enough to bring an
/// overflowing tab back into view.
fn scroll_tab_into_view(&mut self, index: usize, window: &mut Window, _cx: &mut Context<Self>) {
let Some(geometry) = self.geometry.get(index) else {
return;
};
let viewport = window.viewport_size().width.0;
let left = geometry.x.0;
let right = geometry.x.0 + geometry.width.0;
let scrolled = self.scroll_offset.0;
if left < scrolled {
self.scroll_offset = Pixels(left.max(0.0));
} else if right > scrolled + viewport {
self.scroll_offset = Pixels((right - viewport).max(0.0));
}
}
/// Scrolls the strip so the tab at `index` is fully visible.
///
/// The strip does not know the exact width of the visible viewport, so
/// this approximates it with the window width — good enough to bring an
/// overflowing tab back into view.
fn scroll_tab_into_view(&mut self, index: usize, window: &mut Window, _cx: &mut Context<Self>) {
let Some(geometry) = self.geometry.get(index) else {
return;
};
let viewport = window.viewport_size().width.0;
let left = geometry.x.0;
let right = geometry.x.0 + geometry.width.0;
let scrolled = self.scroll_offset.0;
if left < scrolled {
self.scroll_offset = Pixels(left.max(0.0));
} else if right > scrolled + viewport {
self.scroll_offset = Pixels((right - viewport).max(0.0));
}
}
}
impl EventEmitter<TabBarEvent> for TabBar {}
impl Render for TabBar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = cx.default_colors().clone();
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = cx.default_colors().clone();
// Recompute per-tab geometry from the current order and scroll offset.
self.geometry = self
.tabs
.iter()
.enumerate()
.map(|(index, &panel)| TabGeometry {
panel,
x: Pixels(index as f32 * Self::MIN_TAB_WIDTH.0 - self.scroll_offset.0),
width: Self::MIN_TAB_WIDTH,
})
.collect();
// Recompute per-tab geometry from the current order and scroll offset.
self.geometry = self
.tabs
.iter()
.enumerate()
.map(|(index, &panel)| TabGeometry {
panel,
x: Pixels(index as f32 * Self::MIN_TAB_WIDTH.0 - self.scroll_offset.0),
width: Self::MIN_TAB_WIDTH,
})
.collect();
let mut root = div()
.flex()
.flex_row()
.items_center()
.h(px(32.0))
.w_full()
.overflow_hidden()
.on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _window, cx| {
let delta = match event.delta {
ScrollDelta::Pixels(delta) => delta.x.0,
ScrollDelta::Lines(delta) => delta.x * 20.0,
};
this.scroll_offset = Pixels((this.scroll_offset.0 + delta).max(0.0));
cx.notify();
}))
.on_drag_move::<PanelId>(cx.listener(|this, event: &DragMoveEvent<PanelId>, _window, cx| {
let dragged = *event.drag(cx);
// Ignore drags of panels that don't belong to this strip
// (e.g. a dock-level drag from another group passing over).
if !this.tabs.contains(&dragged) {
return;
}
if event.bounds.contains(&event.event.position) {
if let Some(to) = this.tab_index_at(event.event.position) {
if let Some(from) = this.tabs.iter().position(|tab| *tab == dragged) {
this.move_tab(from, to, cx);
}
}
} else {
// The tab left the strip: hand the drag to the dock area.
cx.emit(TabBarEvent::DockDragStarted {
panel: dragged,
position: event.event.position,
});
}
}));
let mut root = div()
.flex()
.flex_row()
.items_center()
.h(px(32.0))
.w_full()
.overflow_hidden()
.on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _window, cx| {
let delta = match event.delta {
ScrollDelta::Pixels(delta) => delta.x.0,
ScrollDelta::Lines(delta) => delta.x * 20.0,
};
this.scroll_offset = Pixels((this.scroll_offset.0 + delta).max(0.0));
cx.notify();
}))
.on_drag_move::<PanelId>(cx.listener(
|this, event: &DragMoveEvent<PanelId>, _window, cx| {
let dragged = *event.drag(cx);
// Ignore drags of panels that don't belong to this strip
// (e.g. a dock-level drag from another group passing over).
if !this.tabs.contains(&dragged) {
return;
}
if event.bounds.contains(&event.event.position) {
if let Some(to) = this.tab_index_at(event.event.position) {
if let Some(from) = this.tabs.iter().position(|tab| *tab == dragged) {
this.move_tab(from, to, cx);
}
}
} else {
// The tab left the strip: hand the drag to the dock area.
cx.emit(TabBarEvent::DockDragStarted {
panel: dragged,
position: event.event.position,
});
}
},
));
for (index, &panel) in self.tabs.iter().enumerate() {
let active = index == self.active;
let title = self
.titles
.get(index)
.cloned()
.unwrap_or_else(|| SharedString::from("Tab"));
let closable = self.closable.get(index).copied().unwrap_or(false);
for (index, &panel) in self.tabs.iter().enumerate() {
let active = index == self.active;
let title = self
.titles
.get(index)
.cloned()
.unwrap_or_else(|| SharedString::from("Tab"));
let closable = self.closable.get(index).copied().unwrap_or(false);
// Ghost shown under the pointer while this tab is being dragged.
let ghost_title = title.clone();
let ghost_ctor = move |_panel: &PanelId,
_origin: Point<Pixels>,
_window: &mut Window,
cx: &mut App| {
cx.new(|_cx| TabDragGhost { title: ghost_title.clone() })
};
// Ghost shown under the pointer while this tab is being dragged.
let ghost_title = title.clone();
let ghost_ctor = move |_panel: &PanelId,
_origin: Point<Pixels>,
_window: &mut Window,
cx: &mut App| {
cx.new(|_cx| TabDragGhost {
title: ghost_title.clone(),
})
};
let mut tab = div()
.id(ElementId::named_usize("dock-tab", panel.raw() as usize))
.w(px(Self::MIN_TAB_WIDTH.0))
.flex_none()
.h_full()
.cursor_pointer()
.bg(if active { colors.selected } else { colors.background })
.text_color(if active { colors.text } else { colors.disabled })
.child(title)
.on_click(cx.listener(move |this, _event: &ClickEvent, window, cx| {
this.activate(index, window, cx);
}))
.on_drag(panel, ghost_ctor);
let mut tab = div()
.id(ElementId::named_usize("dock-tab", panel.raw() as usize))
.w(px(Self::MIN_TAB_WIDTH.0))
.flex_none()
.h_full()
.cursor_pointer()
.bg(if active {
colors.selected
} else {
colors.background
})
.text_color(if active { colors.text } else { colors.disabled })
.child(title)
.on_click(cx.listener(move |this, _event: &ClickEvent, window, cx| {
this.activate(index, window, cx);
}))
.on_drag(panel, ghost_ctor);
if closable {
tab = tab.child(
div()
.id(ElementId::named_usize("dock-tab-close", panel.raw() as usize))
.cursor_pointer()
.text_xs()
.text_color(colors.disabled)
.child("✕")
.on_click(cx.listener(
move |_this, _event: &ClickEvent, _window, cx| {
cx.stop_propagation();
cx.emit(TabBarEvent::CloseRequested(panel));
},
)),
);
}
if closable {
tab = tab.child(
div()
.id(ElementId::named_usize(
"dock-tab-close",
panel.raw() as usize,
))
.cursor_pointer()
.text_xs()
.text_color(colors.disabled)
.child("✕")
.on_click(cx.listener(move |_this, _event: &ClickEvent, _window, cx| {
cx.stop_propagation();
cx.emit(TabBarEvent::CloseRequested(panel));
})),
);
}
root = root.child(tab);
}
root = root.child(tab);
}
root
}
root
}
}
/// The floating view shown under the pointer while a tab is being dragged.
struct TabDragGhost {
title: SharedString,
title: SharedString,
}
impl Render for TabDragGhost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = cx.default_colors().clone();
div()
.px_2()
.py_1()
.rounded_md()
.bg(colors.background)
.border_1()
.border_color(colors.border)
.shadow_md()
.child(self.title.clone())
}
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = cx.default_colors().clone();
div()
.px_2()
.py_1()
.rounded_md()
.bg(colors.background)
.border_1()
.border_color(colors.border)
.shadow_md()
.child(self.title.clone())
}
}