use std::{cell::RefCell, rc::Rc};
use arc_motion::{
ArcPresence, ArcPresenceConfig, arc_spring, arc_spring_with_options, is_reduced_motion,
motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, Point,
RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, base::StyledExt as _,
canvas, deferred, div, point, prelude::*, px,
};
use crate::overlay::dialog::swap_text_sample;
pub const DRAWER_WIDTH: f32 = 480.0;
pub const DRAWER_CONTAINED_WIDTH: f32 = 352.0;
pub const DRAWER_MAX_VERTICAL_SIZE: f32 = 512.0;
pub const DRAWER_INNER_RADIUS: f32 = 12.0;
pub const DRAWER_FLING_VELOCITY: f32 = 500.0;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum DrawerSide {
#[default]
Right,
Left,
Top,
Bottom,
}
impl DrawerSide {
pub const ALL: [DrawerSide; 4] = [Self::Right, Self::Left, Self::Top, Self::Bottom];
pub const fn edge_sign(self) -> f32 {
match self {
Self::Right | Self::Bottom => 1.0,
Self::Left | Self::Top => -1.0,
}
}
pub const fn is_horizontal(self) -> bool {
matches!(self, Self::Left | Self::Right)
}
pub const fn label(self) -> &'static str {
match self {
Self::Right => "Right",
Self::Left => "Left",
Self::Top => "Top",
Self::Bottom => "Bottom",
}
}
}
pub fn drawer_pan_offset(side: DrawerSide, raw_delta_px: f32) -> f32 {
let sign = side.edge_sign();
let toward = raw_delta_px * sign;
let clamped = if toward >= 0.0 {
toward
} else {
-(-toward).sqrt()
};
sign * clamped
}
pub fn drawer_should_dismiss(
side: DrawerSide,
offset_px: f32,
velocity_px_per_sec: f32,
panel_extent_px: f32,
) -> bool {
let sign = side.edge_sign();
let toward = offset_px * sign;
let vel_toward = velocity_px_per_sec * sign;
let threshold = (panel_extent_px / 3.0).max(40.0);
toward > threshold || (toward > 0.0 && vel_toward > DRAWER_FLING_VELOCITY)
}
pub fn drawer_exit_opacity(is_open: bool, presence_progress: f32, reduced: bool) -> f32 {
let p = presence_progress.clamp(0.0, 1.0);
if reduced || is_open {
return p;
}
let exit_elapsed_fraction = 1.0 - p;
if exit_elapsed_fraction <= 0.65 {
1.0
} else {
((1.0 - exit_elapsed_fraction) / 0.35).clamp(0.0, 1.0)
}
}
type OpenCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
fn paint_close_x(cx: f32, cy: f32, scale: f32, color: Hsla, window: &mut Window) {
let r = 4.2 * scale;
for (x1, y1, x2, y2) in [
(cx - r, cy - r, cx + r, cy + r),
(cx + r, cy - r, cx - r, cy + r),
] {
let mut b = PathBuilder::stroke(px(1.75));
b.move_to(point(px(x1), px(y1)));
b.line_to(point(px(x2), px(y2)));
if let Ok(path) = b.build() {
window.paint_path(path, color);
}
}
}
#[derive(Clone)]
struct DrawerInternal {
open: bool,
was_open: bool,
last_side: DrawerSide,
slide_epoch: u64,
opened_at_secs: f64,
close_hovered: bool,
close_pressed: bool,
dragging: bool,
drag_start_pt: Point<Pixels>,
drag_last_pt: Point<Pixels>,
drag_last_at: f64,
drag_velocity: f32,
drag_offset: f32,
prev_title: Option<SharedString>,
last_title: SharedString,
title_changed_at: f64,
prev_desc: Option<SharedString>,
last_desc: SharedString,
desc_changed_at: f64,
trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
focus_handle: FocusHandle,
}
impl DrawerInternal {
fn new(
default_open: bool,
side: DrawerSide,
title: SharedString,
desc: SharedString,
now: f64,
focus_handle: FocusHandle,
) -> Self {
Self {
open: default_open,
was_open: default_open,
last_side: side,
slide_epoch: 0,
opened_at_secs: now - 10.0,
close_hovered: false,
close_pressed: false,
dragging: false,
drag_start_pt: point(px(0.0), px(0.0)),
drag_last_pt: point(px(0.0), px(0.0)),
drag_last_at: now,
drag_velocity: 0.0,
drag_offset: 0.0,
prev_title: None,
last_title: title,
title_changed_at: now - 10.0,
prev_desc: None,
last_desc: desc,
desc_changed_at: now - 10.0,
trigger_bounds: Rc::new(RefCell::new(None)),
panel_bounds: Rc::new(RefCell::new(None)),
focus_handle,
}
}
}
#[derive(IntoElement)]
pub struct Drawer {
id: ElementId,
title: SharedString,
description: Option<SharedString>,
side: DrawerSide,
contained: bool,
trigger: Option<AnyElement>,
body: Option<AnyElement>,
open: Option<bool>,
default_open: bool,
on_open_change: Option<OpenCallback>,
}
impl Drawer {
pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
title: title.into(),
description: None,
side: DrawerSide::Right,
contained: false,
trigger: None,
body: None,
open: None,
default_open: false,
on_open_change: None,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn side(mut self, side: DrawerSide) -> Self {
self.side = side;
self
}
pub fn contained(mut self, contained: bool) -> Self {
self.contained = contained;
self
}
pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
self.trigger = Some(trigger.into_any_element());
self
}
pub fn content(mut self, body: impl IntoElement) -> Self {
self.body = Some(body.into_any_element());
self
}
pub fn open(mut self, open: bool) -> Self {
self.open = Some(open);
self
}
pub fn default_open(mut self, default_open: bool) -> Self {
self.default_open = default_open;
self
}
pub fn on_open_change(
mut self,
handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_open_change = Some(Rc::new(handler));
self
}
}
#[allow(clippy::too_many_arguments)]
fn render_swap_slot(
old_text: Option<SharedString>,
new_text: SharedString,
elapsed: f64,
reduced: bool,
line_height_px: f32,
text_size: Pixels,
font_medium: bool,
color: Hsla,
) -> AnyElement {
let (old_alpha, old_y, new_alpha, new_y) = swap_text_sample(elapsed, reduced);
let swapping = old_text.is_some() && old_alpha > 0.01;
if !swapping {
return div()
.line_height(px(line_height_px))
.text_size(text_size)
.when(font_medium, |d| d.font_medium())
.text_color(color)
.child(new_text)
.into_any_element();
}
div()
.relative()
.min_h(px(line_height_px))
.child(
div()
.line_height(px(line_height_px))
.text_size(text_size)
.when(font_medium, |d| d.font_medium())
.text_color(color)
.opacity(new_alpha)
.mt(px(new_y))
.child(new_text),
)
.when_some(old_text, |d, old| {
d.child(
div()
.absolute()
.top(px(old_y))
.left_0()
.right_0()
.line_height(px(line_height_px))
.text_size(text_size)
.when(font_medium, |d| d.font_medium())
.text_color(color)
.opacity(old_alpha)
.child(old),
)
})
.into_any_element()
}
impl RenderOnce for Drawer {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let desc_str = self.description.clone().unwrap_or_default();
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-drawer-state".into());
let title_init = self.title.clone();
let desc_init = desc_str.clone();
let side = self.side;
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
DrawerInternal::new(
self.default_open,
side,
title_init,
desc_init,
now,
cx.focus_handle(),
)
});
{
let snap = internal.read(cx).clone();
let is_open_now = self.open.unwrap_or(snap.open);
if snap.last_side != side || snap.was_open != is_open_now {
internal.update(cx, |s, _| {
if s.last_side != side || (!s.was_open && is_open_now) {
s.slide_epoch = s.slide_epoch.wrapping_add(1);
}
s.last_side = side;
s.was_open = is_open_now;
});
}
if snap.last_title != self.title {
let prev = snap.last_title.clone();
let next = self.title.clone();
internal.update(cx, |s, _| {
if is_open_now {
s.prev_title = Some(prev);
s.title_changed_at = now;
}
s.last_title = next;
});
}
if snap.last_desc != desc_str {
let prev = snap.last_desc.clone();
let next = desc_str.clone();
internal.update(cx, |s, _| {
if is_open_now && !prev.is_empty() {
s.prev_desc = Some(prev);
s.desc_changed_at = now;
}
s.last_desc = next;
});
}
}
let snap = internal.read(cx).clone();
let is_open = self.open.unwrap_or(snap.open);
let overlay_presence = ArcPresence::new((self.id.clone(), "drawer-overlay"), is_open)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: motion.duration.standard,
exit_duration: motion.duration.fast,
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let panel_presence = ArcPresence::new((self.id.clone(), "drawer-panel"), is_open)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: motion.duration.standard,
exit_duration: motion.duration.standard,
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let viewport = window.viewport_size();
let base_extent = if side.is_horizontal() {
let max_w = if self.contained {
DRAWER_CONTAINED_WIDTH
} else {
DRAWER_WIDTH
};
(f32::from(viewport.width) - 16.0).clamp(220.0_f32.min(max_w), max_w)
} else {
(f32::from(viewport.height) - 32.0).clamp(
200.0_f32.min(DRAWER_MAX_VERTICAL_SIZE),
DRAWER_MAX_VERTICAL_SIZE,
)
};
let side_key = side.label();
let slide_epoch = snap.slide_epoch;
let closed_slide = side.edge_sign() * base_extent;
let target_slide = if is_open { 0.0 } else { closed_slide };
let slide_spring = if reduced {
0.0
} else {
arc_spring_with_options(
(
self.id.clone(),
format!("drawer-slide-{side_key}-{slide_epoch}"),
),
target_slide,
SpringOptions::new(motion.spring.smooth).with_initial_value(closed_slide),
window,
cx,
)
.value
};
let drag_offset = if reduced {
0.0
} else if snap.dragging {
let _ = arc_spring_with_options(
(self.id.clone(), format!("drawer-drag-{side_key}")),
snap.drag_offset,
SpringOptions::new(motion.spring.snappy),
window,
cx,
);
snap.drag_offset
} else {
arc_spring(
(self.id.clone(), format!("drawer-drag-{side_key}")),
0.0,
motion.spring.snappy,
window,
cx,
)
};
let total_shift = slide_spring + drag_offset;
let panel_alpha = drawer_exit_opacity(is_open, panel_presence.progress, reduced);
let title_elapsed = (now - snap.title_changed_at).max(0.0);
let desc_elapsed = (now - snap.desc_changed_at).max(0.0);
if is_open && !reduced && (title_elapsed < 0.23 || desc_elapsed < 0.23) {
window.request_animation_frame();
}
let trigger_bounds_ref = snap.trigger_bounds.clone();
let trigger_probe = canvas(
move |rect, _, _| {
*trigger_bounds_ref.borrow_mut() = Some(rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let internal_trig = internal.clone();
let on_open_trig = self.on_open_change.clone();
let focus_trig = snap.focus_handle.clone();
let mut root = div()
.id(self.id.clone())
.test_support()
.relative()
.flex()
.child(trigger_probe);
if let Some(trig) = self.trigger {
root = root.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"trigger".into(),
))
.test_support()
.role(Role::Button)
.aria_label("Open drawer")
.relative()
.flex()
.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let t = motion_now(cx);
internal_trig.update(cx, |s, _| {
s.open = true;
s.opened_at_secs = t;
s.dragging = false;
s.drag_offset = 0.0;
});
focus_trig.focus(window, cx);
if let Some(h) = &on_open_trig {
h(&true, window, cx);
}
window.refresh();
})
.child(trig),
);
}
if !overlay_presence.should_render() && !panel_presence.should_render() {
return root;
}
if is_open && !snap.focus_handle.is_focused(window) {
snap.focus_handle.focus(window, cx);
}
let panel_bounds_ref = snap.panel_bounds.clone();
let panel_bounds_out = snap.panel_bounds.clone();
let trig_bounds_out = snap.trigger_bounds.clone();
let internal_events = internal.clone();
let on_open_events = self.on_open_change.clone();
let opened_at = snap.opened_at_secs;
let is_dragging = snap.dragging;
let panel_probe = canvas(
move |rect, _, _| {
*panel_bounds_ref.borrow_mut() = Some(rect);
},
move |_, _, window, _| {
if is_open {
let p_ref = panel_bounds_out.clone();
let t_ref = trig_bounds_out.clone();
let st = internal_events.clone();
let cb = on_open_events.clone();
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let t_now = motion_now(cx);
if (t_now - opened_at).abs() < 0.001 {
return;
}
let in_panel = p_ref.borrow().is_some_and(|b| b.contains(&event.position));
let in_trig = t_ref.borrow().is_some_and(|b| b.contains(&event.position));
if !in_panel && !in_trig {
st.update(cx, |s, _| {
s.open = false;
s.dragging = false;
s.drag_offset = 0.0;
});
if let Some(h) = &cb {
h(&false, window, cx);
}
window.refresh();
}
});
}
if is_dragging {
let st_move = internal_events.clone();
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let t_now = motion_now(cx);
st_move.update(cx, |s, _| {
if !s.dragging {
return;
}
let raw_delta = if side.is_horizontal() {
f32::from(event.position.x - s.drag_start_pt.x)
} else {
f32::from(event.position.y - s.drag_start_pt.y)
};
let step_delta = if side.is_horizontal() {
f32::from(event.position.x - s.drag_last_pt.x)
} else {
f32::from(event.position.y - s.drag_last_pt.y)
};
let dt = (t_now - s.drag_last_at).max(0.004) as f32;
s.drag_velocity = step_delta / dt;
s.drag_last_pt = event.position;
s.drag_last_at = t_now;
s.drag_offset = drawer_pan_offset(side, raw_delta);
});
window.refresh();
});
let st_up = internal_events.clone();
let cb_up = on_open_events.clone();
let p_ref_up = panel_bounds_out.clone();
window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let extent = p_ref_up
.borrow()
.map(|b| {
if side.is_horizontal() {
f32::from(b.size.width)
} else {
f32::from(b.size.height)
}
})
.unwrap_or(base_extent);
let (offset, vel) = {
let r = st_up.read(cx);
(r.drag_offset, r.drag_velocity)
};
let dismiss = drawer_should_dismiss(side, offset, vel, extent);
st_up.update(cx, |s, _| {
s.dragging = false;
s.drag_offset = 0.0;
s.drag_velocity = 0.0;
if dismiss {
s.open = false;
}
});
if dismiss && let Some(h) = &cb_up {
h(&false, window, cx);
}
window.refresh();
});
}
},
)
.absolute()
.inset_0();
let close_bg = if snap.close_hovered || snap.close_pressed {
colors.surface_muted
} else {
oklab_mix(colors.surface_muted, Hsla::transparent_black(), 0.65)
};
let close_fg = if snap.close_hovered || snap.close_pressed {
colors.foreground
} else {
colors.text_secondary
};
let close_scale = if snap.close_pressed && !reduced {
0.92
} else {
1.0
};
let int_close_hover = internal.clone();
let int_close_down = internal.clone();
let int_close_up = internal.clone();
let on_open_close = self.on_open_change.clone();
let close_btn = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"close".into(),
))
.test_support()
.role(Role::Button)
.aria_label("Close drawer")
.flex_none()
.w(Spacing::S8)
.h(Spacing::S8)
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(close_bg)
.cursor_pointer()
.on_hover(move |hovered, window, cx| {
int_close_hover.update(cx, |s, _| {
s.close_hovered = *hovered;
if !*hovered {
s.close_pressed = false;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
int_close_down.update(cx, |s, _| {
s.close_pressed = true;
});
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
int_close_up.update(cx, |s, _| {
s.close_pressed = false;
s.open = false;
s.dragging = false;
s.drag_offset = 0.0;
});
if let Some(h) = &on_open_close {
h(&false, window, cx);
}
window.refresh();
})
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx = f32::from(rect.origin.x) + f32::from(rect.size.width) * 0.5;
let cy = f32::from(rect.origin.y) + f32::from(rect.size.height) * 0.5;
paint_close_x(cx, cy, close_scale, close_fg, window);
},
)
.size_full(),
);
let title_slot = render_swap_slot(
snap.prev_title.clone(),
self.title.clone(),
title_elapsed,
reduced,
24.0,
Typography::TEXT_LG,
true,
colors.foreground,
);
let desc_slot = self.description.as_ref().map(|d| {
render_swap_slot(
snap.prev_desc.clone(),
d.clone(),
desc_elapsed,
reduced,
21.0,
Typography::TEXT_SM,
false,
colors.text_secondary,
)
});
let int_pan_start = internal.clone();
let header = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"header".into(),
))
.test_support()
.w_full()
.flex_none()
.flex()
.items_start()
.justify_between()
.gap(Spacing::S5)
.p(Spacing::S6)
.border_b_1()
.border_color(colors.border)
.on_mouse_down(
MouseButton::Left,
move |event: &MouseDownEvent, window, cx| {
if reduced {
return;
}
let t = motion_now(cx);
int_pan_start.update(cx, |s, _| {
s.dragging = true;
s.drag_start_pt = event.position;
s.drag_last_pt = event.position;
s.drag_last_at = t;
s.drag_velocity = 0.0;
s.drag_offset = 0.0;
});
window.refresh();
},
)
.child(
div()
.flex_1()
.flex()
.flex_col()
.gap(Spacing::S2)
.child(title_slot)
.when_some(desc_slot, |d, desc| d.child(desc)),
)
.child(close_btn);
let body = div()
.id(ElementId::NamedChild(self.id.clone().into(), "body".into()))
.w_full()
.flex_1()
.min_h_0()
.overflow_y_scroll()
.p(Spacing::S6)
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.when_some(self.body, |d, b| d.child(b));
let int_key = internal.clone();
let on_open_key = self.on_open_change.clone();
let rad = px(DRAWER_INNER_RADIUS);
let mut panel = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"content".into(),
))
.role(Role::Dialog)
.aria_label(self.title.clone())
.test_support()
.track_focus(&snap.focus_handle)
.absolute()
.flex()
.flex_col()
.overflow_hidden()
.border_color(colors.border)
.bg(colors.surface_raised)
.text_color(colors.foreground)
.when(!self.contained, |d| d.shadow(Shadows::floating(theme.mode)))
.opacity(panel_alpha)
.on_mouse_down(MouseButton::Left, |_, _, cx| {
cx.stop_propagation();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key.as_str() == "escape" {
cx.stop_propagation();
int_key.update(cx, |s, _| {
s.open = false;
s.dragging = false;
s.drag_offset = 0.0;
});
if let Some(h) = &on_open_key {
h(&false, window, cx);
}
window.refresh();
}
})
.child(panel_probe);
panel = match side {
DrawerSide::Right => panel
.top_0()
.bottom_0()
.right(px(-total_shift))
.w(px(base_extent))
.border_l_1()
.when(!self.contained, |d| d.border_t_1().border_b_1())
.rounded_tl(rad)
.rounded_bl(rad),
DrawerSide::Left => panel
.top_0()
.bottom_0()
.left(px(total_shift))
.w(px(base_extent))
.border_r_1()
.when(!self.contained, |d| d.border_t_1().border_b_1())
.rounded_tr(rad)
.rounded_br(rad),
DrawerSide::Top => panel
.left_0()
.right_0()
.top(px(total_shift))
.max_h(px(base_extent))
.border_b_1()
.rounded_bl(rad)
.rounded_br(rad),
DrawerSide::Bottom => panel
.left_0()
.right_0()
.bottom(px(-total_shift))
.max_h(px(base_extent))
.border_t_1()
.rounded_tl(rad)
.rounded_tr(rad)
.child(
div().w_full().pt(px(9.0)).flex().justify_center().child(
div()
.w(px(36.0))
.h(px(4.0))
.rounded(Radii::PILL)
.bg(colors.border_strong)
.opacity(0.75),
),
),
};
panel = panel.child(header).child(body);
let base_alpha = if self.contained { 0.16 } else { 0.38 };
let mut backdrop_color = gpui_kit::hsla(0.0, 0.0, 0.04, base_alpha);
backdrop_color.a *= overlay_presence.progress.clamp(0.0, 1.0);
let (rel_left, rel_top) = if self.contained {
(0.0, 0.0)
} else {
snap.trigger_bounds
.borrow()
.map(|b| (-f32::from(b.origin.x), -f32::from(b.origin.y)))
.unwrap_or((0.0, 0.0))
};
let layer = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"backdrop".into(),
))
.test_support()
.absolute()
.left(px(rel_left))
.top(px(rel_top))
.when(self.contained, |d| d.right_0().bottom_0())
.when(!self.contained, |d| d.w(viewport.width).h(viewport.height))
.bg(backdrop_color)
.overflow_hidden()
.child(panel);
if self.contained {
root.child(layer)
} else {
root.child(deferred(layer).with_priority(30))
}
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, IntoElement, MouseButton, ParentElement, Render, Role, Styled, TestAppContext,
Window, div, px,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
#[test]
fn drawer_pan_rubber_band_dismiss_and_late_shadow_fade_match_spec() {
assert!((drawer_pan_offset(DrawerSide::Right, 60.0) - 60.0).abs() < 1e-4);
assert!((drawer_pan_offset(DrawerSide::Right, -25.0) - -5.0).abs() < 1e-4);
assert!((drawer_pan_offset(DrawerSide::Left, -60.0) - -60.0).abs() < 1e-4);
assert!((drawer_pan_offset(DrawerSide::Left, 36.0) - 6.0).abs() < 1e-4);
assert!(!drawer_should_dismiss(
DrawerSide::Right,
120.0,
100.0,
480.0
));
assert!(drawer_should_dismiss(DrawerSide::Right, 170.0, 50.0, 480.0));
assert!(drawer_should_dismiss(DrawerSide::Right, 20.0, 620.0, 480.0));
assert_eq!(drawer_exit_opacity(false, 0.80, false), 1.0);
assert_eq!(drawer_exit_opacity(false, 0.35, false), 1.0);
assert!((drawer_exit_opacity(false, 0.175, false) - 0.5).abs() < 1e-3);
assert_eq!(drawer_exit_opacity(false, 0.0, false), 0.0);
}
struct DrawerHost {
open: bool,
closed_count: Rc<Cell<usize>>,
}
impl Render for DrawerHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let count = self.closed_count.clone();
div().size_full().p(px(24.0)).child(
Drawer::new("test-drawer", "Inspector drawer")
.description("Edge panel details")
.side(DrawerSide::Right)
.open(self.open)
.on_open_change(cx.listener(move |this, next: &bool, _, cx| {
this.open = *next;
if !*next {
count.set(count.get() + 1);
}
cx.notify();
}))
.trigger(div().w(px(110.0)).h(px(36.0)).child("Open drawer"))
.content(div().child("Drawer details body")),
)
}
}
#[gpui_kit::test]
fn drawer_opens_on_trigger_and_closes_on_close_button(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
});
let closed_count = Rc::new(Cell::new(0));
let (_view, cx) = cx.add_window_view(|_, _| DrawerHost {
open: false,
closed_count: closed_count.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let trig = window.find_by_label("Open drawer");
let tpos = trig.bounds().center();
window.pointer_down(tpos, MouseButton::Left, cx);
window.pointer_up(tpos, MouseButton::Left, cx);
window.render_frame(cx);
let panel = window.find_by_label("Inspector drawer");
assert_eq!(panel.role(), Some(Role::Dialog));
let close_btn = window.find_by_label("Close drawer");
let cpos = close_btn.bounds().center();
window.pointer_down(cpos, MouseButton::Left, cx);
window.pointer_up(cpos, MouseButton::Left, cx);
window.render_frame(cx);
assert_eq!(closed_count.get(), 1);
});
}
struct SideSwitchHost {
open: bool,
side: DrawerSide,
}
impl Render for SideSwitchHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(
Drawer::new("switch-drawer", "Side switch drawer")
.side(self.side)
.open(self.open)
.content(div().child("Body")),
)
}
}
#[gpui_kit::test]
fn drawer_switching_sides_always_slides_from_anchored_edge(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx);
});
let (view, cx) = cx.add_window_view(|_, _| SideSwitchHost {
open: false,
side: DrawerSide::Right,
});
cx.update(|window, cx| {
window.render_frame(cx);
let vw = f32::from(window.viewport_size().width);
view.update(cx, |this, cx| {
this.side = DrawerSide::Left;
this.open = true;
cx.notify();
});
window.render_frame(cx);
let left_bounds = window.find_by_label("Side switch drawer").bounds();
assert!(
f32::from(left_bounds.origin.x) < 0.0,
"Left drawer should start sliding from left edge (< 0), got {:?}",
left_bounds
);
view.update(cx, |this, cx| {
this.open = false;
cx.notify();
});
window.render_frame(cx);
view.update(cx, |this, cx| {
this.side = DrawerSide::Right;
this.open = true;
cx.notify();
});
window.render_frame(cx);
let right_bounds = window.find_by_label("Side switch drawer").bounds();
assert!(
f32::from(right_bounds.origin.x) > vw - DRAWER_WIDTH,
"Right drawer should start sliding from right edge (> {}), got {:?}",
vw - DRAWER_WIDTH,
right_bounds
);
});
}
}