refactor root component

This commit is contained in:
2026-01-16 15:29:34 +07:00
parent 4c4fe0cc0c
commit 81b1f2b293
21 changed files with 445 additions and 412 deletions

View File

@@ -2,168 +2,63 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder;
use gpui::{
div, AnyView, App, AppContext, Context, Decorations, Entity, FocusHandle, InteractiveElement,
IntoElement, ParentElement as _, Render, SharedString, Styled, Window,
canvas, div, point, px, AnyView, App, AppContext, Bounds, Context, CursorStyle, Decorations,
Edges, Entity, FocusHandle, HitboxBehavior, Hsla, InteractiveElement, IntoElement, MouseButton,
ParentElement as _, Pixels, Point, Render, ResizeEdge, SharedString, Size, Styled,
WeakFocusHandle, Window,
};
use theme::{
ActiveTheme, CLIENT_SIDE_DECORATION_BORDER, CLIENT_SIDE_DECORATION_ROUNDING,
CLIENT_SIDE_DECORATION_SHADOW,
};
use theme::{ActiveTheme, CLIENT_SIDE_DECORATION_ROUNDING};
use crate::input::InputState;
use crate::modal::Modal;
use crate::notification::{Notification, NotificationList};
use crate::window_border;
/// Extension trait for [`WindowContext`] and [`ViewContext`] to add drawer functionality.
pub trait ContextModal: Sized {
/// Opens a Modal.
fn open_modal<F>(&mut self, cx: &mut App, build: F)
where
F: Fn(Modal, &mut Window, &mut App) -> Modal + 'static;
/// Return true, if there is an active Modal.
fn has_active_modal(&mut self, cx: &mut App) -> bool;
/// Closes the last active Modal.
fn close_modal(&mut self, cx: &mut App);
/// Closes all active Modals.
fn close_all_modals(&mut self, cx: &mut App);
/// Returns number of notifications.
fn notifications(&mut self, cx: &mut App) -> Rc<Vec<Entity<Notification>>>;
/// Pushes a notification to the notification list.
fn push_notification(&mut self, note: impl Into<Notification>, cx: &mut App);
/// Clears a notification by its ID.
fn clear_notification_by_id(&mut self, id: SharedString, cx: &mut App);
/// Clear all notifications
fn clear_notifications(&mut self, cx: &mut App);
/// Return current focused Input entity.
fn focused_input(&mut self, cx: &mut App) -> Option<Entity<InputState>>;
/// Returns true if there is a focused Input entity.
fn has_focused_input(&mut self, cx: &mut App) -> bool;
}
impl ContextModal for Window {
fn open_modal<F>(&mut self, cx: &mut App, build: F)
where
F: Fn(Modal, &mut Window, &mut App) -> Modal + 'static,
{
Root::update(self, cx, move |root, window, cx| {
// Only save focus handle if there are no active modals.
// This is used to restore focus when all modals are closed.
if root.active_modals.is_empty() {
root.previous_focus_handle = window.focused(cx);
}
let focus_handle = cx.focus_handle();
focus_handle.focus(window, cx);
root.active_modals.push(ActiveModal {
focus_handle,
builder: Rc::new(build),
});
cx.notify();
})
}
fn has_active_modal(&mut self, cx: &mut App) -> bool {
!Root::read(self, cx).active_modals.is_empty()
}
fn close_modal(&mut self, cx: &mut App) {
Root::update(self, cx, move |root, window, cx| {
root.active_modals.pop();
if let Some(top_modal) = root.active_modals.last() {
// Focus the next modal.
top_modal.focus_handle.focus(window, cx);
} else {
// Restore focus if there are no more modals.
root.focus_back(window, cx);
}
cx.notify();
})
}
fn close_all_modals(&mut self, cx: &mut App) {
Root::update(self, cx, |root, window, cx| {
root.active_modals.clear();
root.focus_back(window, cx);
cx.notify();
})
}
fn push_notification(&mut self, note: impl Into<Notification>, cx: &mut App) {
let note = note.into();
Root::update(self, cx, move |root, window, cx| {
root.notification
.update(cx, |view, cx| view.push(note, window, cx));
cx.notify();
})
}
fn clear_notifications(&mut self, cx: &mut App) {
Root::update(self, cx, move |root, window, cx| {
root.notification
.update(cx, |view, cx| view.clear(window, cx));
cx.notify();
})
}
fn clear_notification_by_id(&mut self, id: SharedString, cx: &mut App) {
Root::update(self, cx, move |root, window, cx| {
root.notification.update(cx, |view, cx| {
view.close(id.clone(), window, cx);
});
cx.notify();
})
}
fn notifications(&mut self, cx: &mut App) -> Rc<Vec<Entity<Notification>>> {
let entity = Root::read(self, cx).notification.clone();
Rc::new(entity.read(cx).notifications())
}
fn has_focused_input(&mut self, cx: &mut App) -> bool {
Root::read(self, cx).focused_input.is_some()
}
fn focused_input(&mut self, cx: &mut App) -> Option<Entity<InputState>> {
Root::read(self, cx).focused_input.clone()
}
}
type Builder = Rc<dyn Fn(Modal, &mut Window, &mut App) -> Modal + 'static>;
#[derive(Clone)]
pub(crate) struct ActiveModal {
#[allow(clippy::type_complexity)]
pub struct ActiveModal {
focus_handle: FocusHandle,
builder: Builder,
/// The previous focused handle before opening the modal.
previous_focused_handle: Option<WeakFocusHandle>,
builder: Rc<dyn Fn(Modal, &mut Window, &mut App) -> Modal + 'static>,
}
impl ActiveModal {
fn new(
focus_handle: FocusHandle,
previous_focused_handle: Option<WeakFocusHandle>,
builder: impl Fn(Modal, &mut Window, &mut App) -> Modal + 'static,
) -> Self {
Self {
focus_handle,
previous_focused_handle,
builder: Rc::new(builder),
}
}
}
/// Root is a view for the App window for as the top level view (Must be the first view in the window).
///
/// It is used to manage the Modal, and Notification.
pub struct Root {
/// All active models
pub(crate) active_modals: Vec<ActiveModal>,
pub notification: Entity<NotificationList>,
pub focused_input: Option<Entity<InputState>>,
/// Used to store the focus handle of the previous view.
///
/// When the Modal closes, we will focus back to the previous view.
previous_focus_handle: Option<FocusHandle>,
/// Notification layer
pub(crate) notification: Entity<NotificationList>,
/// Current focused input
pub(crate) focused_input: Option<Entity<InputState>>,
/// App view
view: AnyView,
}
impl Root {
pub fn new(view: AnyView, window: &mut Window, cx: &mut Context<Self>) -> Self {
Self {
previous_focus_handle: None,
focused_input: None,
active_modals: Vec::new(),
notification: cx.new(|cx| NotificationList::new(window, cx)),
@@ -188,13 +83,11 @@ impl Root {
.read(cx)
}
fn focus_back(&mut self, window: &mut Window, cx: &mut App) {
if let Some(handle) = self.previous_focus_handle.clone() {
window.focus(&handle, cx);
}
pub fn view(&self) -> &AnyView {
&self.view
}
/// Render Notification layer.
/// Render the notification layer.
pub fn render_notification_layer(
window: &mut Window,
cx: &mut App,
@@ -210,10 +103,9 @@ impl Root {
)
}
/// Render the Modal layer.
/// Render the modal layer.
pub fn render_modal_layer(window: &mut Window, cx: &mut App) -> Option<impl IntoElement> {
let root = window.root::<Root>()??;
let active_modals = root.read(cx).active_modals.clone();
if active_modals.is_empty() {
@@ -255,50 +147,271 @@ impl Root {
Some(div().children(modals))
}
/// Return the root view of the Root.
pub fn view(&self) -> &AnyView {
&self.view
/// Open a modal.
pub fn open_modal<F>(&mut self, builder: F, window: &mut Window, cx: &mut Context<'_, Self>)
where
F: Fn(Modal, &mut Window, &mut App) -> Modal + 'static,
{
let previous_focused_handle = window.focused(cx).map(|h| h.downgrade());
let focus_handle = cx.focus_handle();
focus_handle.focus(window, cx);
self.active_modals.push(ActiveModal::new(
focus_handle,
previous_focused_handle,
builder,
));
cx.notify();
}
/// Replace the root view of the Root.
pub fn replace_view(&mut self, view: AnyView) {
self.view = view;
/// Close the topmost modal.
pub fn close_modal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.focused_input = None;
if let Some(handle) = self
.active_modals
.pop()
.and_then(|d| d.previous_focused_handle)
.and_then(|h| h.upgrade())
{
window.focus(&handle, cx);
}
cx.notify();
}
/// Close all modals.
pub fn close_all_modals(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.focused_input = None;
self.active_modals.clear();
let previous_focused_handle = self
.active_modals
.first()
.and_then(|d| d.previous_focused_handle.clone());
if let Some(handle) = previous_focused_handle.and_then(|h| h.upgrade()) {
window.focus(&handle, cx);
}
cx.notify();
}
/// Check if there are any active modals.
pub fn has_active_modals(&self) -> bool {
!self.active_modals.is_empty()
}
/// Push a notification to the notification layer.
pub fn push_notification<T>(&mut self, note: T, window: &mut Window, cx: &mut Context<'_, Root>)
where
T: Into<Notification>,
{
self.notification
.update(cx, |view, cx| view.push(note, window, cx));
cx.notify();
}
pub fn clear_notification<T>(&mut self, id: T, window: &mut Window, cx: &mut Context<Self>)
where
T: Into<SharedString>,
{
self.notification
.update(cx, |view, cx| view.close(id.into(), window, cx));
cx.notify();
}
/// Clear all notifications from the notification layer.
pub fn clear_notifications(&mut self, window: &mut Window, cx: &mut Context<'_, Root>) {
self.notification
.update(cx, |view, cx| view.clear(window, cx));
cx.notify();
}
}
impl Render for Root {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let base_font_size = cx.theme().font_size;
let rem_size = cx.theme().font_size;
let font_family = cx.theme().font_family.clone();
let decorations = window.window_decorations();
window.set_rem_size(base_font_size);
// Set the base font size
window.set_rem_size(rem_size);
window_border().child(
div()
.id("root")
.map(|this| match decorations {
Decorations::Server => this,
Decorations::Client { tiling, .. } => this
.when(!(tiling.top || tiling.right), |el| {
el.rounded_tr(CLIENT_SIDE_DECORATION_ROUNDING)
})
.when(!(tiling.top || tiling.left), |el| {
el.rounded_tl(CLIENT_SIDE_DECORATION_ROUNDING)
})
.when(!(tiling.bottom || tiling.right), |el| {
el.rounded_br(CLIENT_SIDE_DECORATION_ROUNDING)
})
.when(!(tiling.bottom || tiling.left), |el| {
el.rounded_bl(CLIENT_SIDE_DECORATION_ROUNDING)
}),
})
.relative()
.size_full()
.font_family(font_family)
.bg(cx.theme().background)
.text_color(cx.theme().text)
.child(self.view.clone()),
)
// Set the client inset (linux only)
window.set_client_inset(CLIENT_SIDE_DECORATION_SHADOW);
div()
.id("window")
.size_full()
.bg(gpui::transparent_black())
.map(|div| match decorations {
Decorations::Server => div,
Decorations::Client { tiling } => div
.bg(gpui::transparent_black())
.child(
canvas(
|_bounds, window, _cx| {
window.insert_hitbox(
Bounds::new(
point(px(0.0), px(0.0)),
window.window_bounds().get_bounds().size,
),
HitboxBehavior::Normal,
)
},
move |_bounds, hitbox, window, _cx| {
let mouse = window.mouse_position();
let size = window.window_bounds().get_bounds().size;
let Some(edge) =
resize_edge(mouse, CLIENT_SIDE_DECORATION_SHADOW, size)
else {
return;
};
window.set_cursor_style(
match edge {
ResizeEdge::Top | ResizeEdge::Bottom => {
CursorStyle::ResizeUpDown
}
ResizeEdge::Left | ResizeEdge::Right => {
CursorStyle::ResizeLeftRight
}
ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
CursorStyle::ResizeUpLeftDownRight
}
ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
CursorStyle::ResizeUpRightDownLeft
}
},
&hitbox,
);
},
)
.size_full()
.absolute(),
)
.when(!(tiling.top || tiling.right), |div| {
div.rounded_tr(CLIENT_SIDE_DECORATION_ROUNDING)
})
.when(!(tiling.top || tiling.left), |div| {
div.rounded_tl(CLIENT_SIDE_DECORATION_ROUNDING)
})
.when(!(tiling.bottom || tiling.right), |div| {
div.rounded_br(CLIENT_SIDE_DECORATION_ROUNDING)
})
.when(!(tiling.bottom || tiling.left), |div| {
div.rounded_bl(CLIENT_SIDE_DECORATION_ROUNDING)
})
.when(!tiling.top, |div| div.pt(CLIENT_SIDE_DECORATION_SHADOW))
.when(!tiling.bottom, |div| div.pb(CLIENT_SIDE_DECORATION_SHADOW))
.when(!tiling.left, |div| div.pl(CLIENT_SIDE_DECORATION_SHADOW))
.when(!tiling.right, |div| div.pr(CLIENT_SIDE_DECORATION_SHADOW))
.on_mouse_down(MouseButton::Left, move |e, window, _cx| {
let size = window.window_bounds().get_bounds().size;
let pos = e.position;
match resize_edge(pos, CLIENT_SIDE_DECORATION_SHADOW, size) {
Some(edge) => window.start_window_resize(edge),
None => window.start_window_move(),
};
}),
})
.child(
div()
.map(|div| match decorations {
Decorations::Server => div,
Decorations::Client { tiling } => div
.border_color(cx.theme().window_border)
.when(!(tiling.bottom || tiling.right), |div| {
div.rounded_br(CLIENT_SIDE_DECORATION_ROUNDING)
})
.when(!(tiling.bottom || tiling.left), |div| {
div.rounded_bl(CLIENT_SIDE_DECORATION_ROUNDING)
})
.when(!tiling.top, |div| {
div.border_t(CLIENT_SIDE_DECORATION_BORDER)
})
.when(!tiling.bottom, |div| {
div.border_b(CLIENT_SIDE_DECORATION_BORDER)
})
.when(!tiling.left, |div| {
div.border_l(CLIENT_SIDE_DECORATION_BORDER)
})
.when(!tiling.right, |div| {
div.border_r(CLIENT_SIDE_DECORATION_BORDER)
})
.when(!tiling.is_tiled(), |div| {
div.shadow(vec![gpui::BoxShadow {
color: Hsla {
h: 0.,
s: 0.,
l: 0.,
a: 0.4,
},
blur_radius: CLIENT_SIDE_DECORATION_SHADOW / 2.,
spread_radius: px(0.),
offset: point(px(0.0), px(0.0)),
}])
}),
})
.on_mouse_move(|_e, _, cx| {
cx.stop_propagation();
})
.size_full()
.font_family(font_family)
.bg(cx.theme().background)
.text_color(cx.theme().text)
.child(self.view.clone()),
)
}
}
/// Get the window paddings.
pub(crate) fn window_paddings(window: &Window, _cx: &App) -> Edges<Pixels> {
match window.window_decorations() {
Decorations::Server => Edges::all(px(0.0)),
Decorations::Client { tiling } => {
let mut paddings = Edges::all(CLIENT_SIDE_DECORATION_SHADOW);
if tiling.top {
paddings.top = px(0.0);
}
if tiling.bottom {
paddings.bottom = px(0.0);
}
if tiling.left {
paddings.left = px(0.0);
}
if tiling.right {
paddings.right = px(0.0);
}
paddings
}
}
}
/// Get the window resize edge.
fn resize_edge(pos: Point<Pixels>, shadow_size: Pixels, size: Size<Pixels>) -> Option<ResizeEdge> {
let edge = if pos.y < shadow_size && pos.x < shadow_size {
ResizeEdge::TopLeft
} else if pos.y < shadow_size && pos.x > size.width - shadow_size {
ResizeEdge::TopRight
} else if pos.y < shadow_size {
ResizeEdge::Top
} else if pos.y > size.height - shadow_size && pos.x < shadow_size {
ResizeEdge::BottomLeft
} else if pos.y > size.height - shadow_size && pos.x > size.width - shadow_size {
ResizeEdge::BottomRight
} else if pos.y > size.height - shadow_size {
ResizeEdge::Bottom
} else if pos.x < shadow_size {
ResizeEdge::Left
} else if pos.x > size.width - shadow_size {
ResizeEdge::Right
} else {
return None;
};
Some(edge)
}