use std::{cell::RefCell, rc::Rc};
use arc_motion::{
ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, is_reduced_motion,
motion_now,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
TestSupportExt as _, Window, base::StyledExt as _, canvas, deferred, div, point, prelude::*,
px,
};
pub const DIALOG_MAX_WIDTH: f32 = 440.0;
pub const DIALOG_VIEWPORT_MARGIN: f32 = 32.0;
type OpenCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
pub fn dialog_card_y_offset(is_open: bool, spring_y: f32, presence_t: f32, reduced: bool) -> f32 {
if reduced {
return 0.0;
}
if is_open {
spring_y
} else {
let exit_progress = (1.0 - presence_t).clamp(0.0, 1.0);
spring_y + (4.0 - spring_y) * exit_progress
}
}
pub fn swap_text_sample(elapsed_secs: f64, reduced: bool) -> (f32, f32, f32, f32) {
if reduced || elapsed_secs >= 0.22 {
return (0.0, -5.0, 1.0, 0.0);
}
let out_t = (elapsed_secs / 0.16).clamp(0.0, 1.0) as f32;
let out_eased = CubicBezier::new(0.2, 0.0, 0.0, 1.0).sample(out_t);
let in_t = (elapsed_secs / 0.22).clamp(0.0, 1.0) as f32;
let in_eased = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(in_t);
let old_blur = BlurFallback::evaluate(px(out_eased * 4.0), reduced);
let new_blur = BlurFallback::evaluate(px((1.0 - in_eased) * 8.0), reduced);
let old_alpha = ((1.0 - out_eased) * old_blur.opacity_multiplier).clamp(0.0, 1.0);
let old_y = -5.0 * out_eased;
let new_alpha = (in_eased * new_blur.opacity_multiplier).clamp(0.0, 1.0);
let new_y = 5.0 * (1.0 - in_eased);
(old_alpha, old_y, new_alpha, new_y)
}
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 DialogInternal {
open: bool,
last_open_changed_at: f64,
close_hovered: bool,
close_pressed: bool,
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>>>>,
card_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
focus_handle: FocusHandle,
}
impl DialogInternal {
fn new(
default_open: bool,
title: SharedString,
desc: SharedString,
now: f64,
focus_handle: FocusHandle,
) -> Self {
Self {
open: default_open,
last_open_changed_at: now - 10.0,
close_hovered: false,
close_pressed: false,
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)),
card_bounds: Rc::new(RefCell::new(None)),
focus_handle,
}
}
}
#[derive(IntoElement)]
pub struct ArcDialog {
id: ElementId,
title: SharedString,
description: Option<SharedString>,
trigger: Option<AnyElement>,
body: Option<AnyElement>,
open: Option<bool>,
default_open: bool,
content_only: bool,
max_width: Pixels,
on_open_change: Option<OpenCallback>,
}
impl ArcDialog {
pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
title: title.into(),
description: None,
trigger: None,
body: None,
open: None,
default_open: false,
content_only: false,
max_width: px(DIALOG_MAX_WIDTH),
on_open_change: None,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
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 content_only(mut self, content_only: bool) -> Self {
self.content_only = content_only;
self
}
pub fn max_width(mut self, max_width: Pixels) -> Self {
if f32::from(max_width).is_finite() && max_width > px(0.0) {
self.max_width = max_width;
}
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 ArcDialog {
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-dialog-state".into());
let title_init = self.title.clone();
let desc_init = desc_str.clone();
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
DialogInternal::new(
self.default_open,
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_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(), "dialog-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 card_presence = ArcPresence::new((self.id.clone(), "dialog-card"), is_open)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: motion.duration.fast,
exit_duration: motion.duration.fast,
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let spring_y = if reduced {
0.0
} else {
arc_spring(
(self.id.clone(), "dialog-y"),
if is_open { 0.0 } else { 8.0 },
motion.spring.smooth,
window,
cx,
)
};
let y_offset = dialog_card_y_offset(is_open, spring_y, card_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 dialog")
.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.last_open_changed_at = t;
});
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() && !card_presence.should_render() {
return root;
}
if is_open && !snap.focus_handle.contains_focused(window, cx) {
snap.focus_handle.focus(window, cx);
}
let card_bounds_ref = snap.card_bounds.clone();
let card_bounds_out = snap.card_bounds.clone();
let trig_bounds_out = snap.trigger_bounds.clone();
let internal_out = internal.clone();
let on_open_out = self.on_open_change.clone();
let opened_at = snap.last_open_changed_at;
let card_probe = canvas(
move |rect, _, _| {
*card_bounds_ref.borrow_mut() = Some(rect);
},
move |_, _, window, _| {
if is_open {
let c_ref = card_bounds_out.clone();
let t_ref = trig_bounds_out.clone();
let st = internal_out.clone();
let cb = on_open_out.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_card = c_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_card && !in_trig {
st.update(cx, |s, _| {
s.open = false;
s.last_open_changed_at = t_now;
});
if let Some(h) = &cb {
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.5)
};
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 internal_close_hover = internal.clone();
let internal_close_press = internal.clone();
let internal_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 dialog")
.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| {
internal_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();
internal_close_press.update(cx, |s, _| {
s.close_pressed = true;
});
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
let t = motion_now(cx);
internal_close_up.update(cx, |s, _| {
s.close_pressed = false;
s.open = false;
s.last_open_changed_at = t;
});
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 header = div()
.w_full()
.flex()
.items_start()
.justify_between()
.gap(Spacing::S5)
.p(Spacing::S6)
.border_b_1()
.border_color(colors.border)
.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()
.w_full()
.when(!self.content_only, |d| d.p(Spacing::S6))
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.when_some(self.body, |d, b| d.child(b));
let viewport = window.viewport_size();
let avail_w = (f32::from(viewport.width) - DIALOG_VIEWPORT_MARGIN).max(0.0);
let card_w = avail_w.min(f32::from(self.max_width));
let internal_key = internal.clone();
let on_open_key = self.on_open_change.clone();
let card = 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)
.relative()
.w(px(card_w))
.mt(px(y_offset))
.when(!self.content_only, |d| {
d.rounded(Radii::SURFACE)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.shadow(Shadows::floating(theme.mode))
})
.text_color(colors.foreground)
.opacity(card_presence.progress.clamp(0.0, 1.0))
.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();
let t = motion_now(cx);
internal_key.update(cx, |s, _| {
s.open = false;
s.last_open_changed_at = t;
});
if let Some(h) = &on_open_key {
h(&false, window, cx);
}
window.refresh();
}
})
.child(card_probe)
.when(!self.content_only, |d| d.child(header))
.child(body);
let mut backdrop_color = gpui_kit::hsla(0.0, 0.0, 0.04, 0.46);
backdrop_color.a *= overlay_presence.progress.clamp(0.0, 1.0);
let (rel_left, rel_top) = snap
.trigger_bounds
.borrow()
.map(|b| (-f32::from(b.origin.x), -f32::from(b.origin.y)))
.unwrap_or((0.0, 0.0));
let modal_layer = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"backdrop".into(),
))
.test_support()
.absolute()
.left(px(rel_left))
.top(px(rel_top))
.w(viewport.width)
.h(viewport.height)
.bg(backdrop_color)
.flex()
.items_center()
.justify_center()
.p(Spacing::S4)
.when(is_open, |layer| {
layer.on_scroll(|_, _, cx| cx.stop_propagation())
})
.child(card);
root.child(deferred(modal_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, SharedString, Styled,
TestAppContext, Window, div, px,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct DialogHarness {
open: bool,
title: SharedString,
close_count: Rc<Cell<usize>>,
}
impl Render for DialogHarness {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let count = self.close_count.clone();
div().size_full().p(px(24.0)).child(
ArcDialog::new("test-dialog", self.title.clone())
.description("Confirm workspace archive")
.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(100.0)).h(px(36.0)).child("Open dialog"))
.content(div().child("Dialog body content")),
)
}
}
#[gpui_kit::test]
fn modal_consumes_wheel_after_inner_list_and_unlocks_after_close(cx: &mut TestAppContext) {
use gpui_kit::{
InputEvent as _, ScrollDelta, ScrollEvent, ScrollHandle, TouchPhase, point, size,
};
struct ScrollDialog {
open: bool,
document: ScrollHandle,
list: ScrollHandle,
}
impl Render for ScrollDialog {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.id("modal-scroll-document")
.size_full()
.overflow_y_scroll()
.track_scroll(&self.document)
.child(
ArcDialog::new("scroll-dialog", "Scroll dialog")
.open(self.open)
.trigger(div().w(px(120.0)).h(px(36.0)).child("Open"))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.content(
div()
.id("modal-scroll-list")
.test_support()
.h(px(120.0))
.overflow_y_scroll()
.track_scroll(&self.list)
.child(div().h(px(900.0)).flex_none()),
),
)
.child(div().h(px(1800.0)).flex_none())
}
}
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 document = ScrollHandle::new();
let list = ScrollHandle::new();
let (_, cx) = cx.add_window_view(|_, _| ScrollDialog {
open: false,
document: document.clone(),
list: list.clone(),
});
cx.simulate_resize(size(px(800.0), px(700.0)));
cx.update(|w, cx| {
w.render_frame(cx);
w.click(
ElementId::NamedChild(ElementId::from("scroll-dialog").into(), "trigger".into()),
cx,
);
w.render_frame(cx);
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(400));
cx.update(|w, cx| {
w.render_frame(cx);
for (index, delta) in [-60.0, -2000.0, -60.0, 60.0, 2000.0, 60.0]
.into_iter()
.enumerate()
{
let position = w.find("modal-scroll-list").bounds().center();
w.pointer_move(position, None, cx);
w.dispatch_event(
ScrollEvent {
position,
delta: ScrollDelta::Pixels(point(px(0.0), px(delta))),
modifiers: Default::default(),
touch_phase: TouchPhase::Moved,
source: Default::default(),
}
.to_platform_input(),
cx,
);
w.render_frame(cx);
assert_eq!(document.offset().y, px(0.0));
if index == 0 {
assert!(list.offset().y < px(0.0), "内层列表必须仍能滚动");
}
if index >= 4 {
assert_eq!(list.offset().y, px(0.0));
}
}
w.press("escape", cx);
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(400));
cx.update(|w, cx| {
w.render_frame(cx);
let position = point(px(400.0), px(300.0));
w.pointer_move(position, None, cx);
w.dispatch_event(
ScrollEvent {
position,
delta: ScrollDelta::Pixels(point(px(0.0), px(-60.0))),
modifiers: Default::default(),
touch_phase: TouchPhase::Moved,
source: Default::default(),
}
.to_platform_input(),
cx,
);
w.render_frame(cx);
assert!(document.offset().y < px(0.0));
});
}
#[test]
fn card_offset_and_swap_text_curves_follow_spec() {
assert!((dialog_card_y_offset(true, 8.0, 0.0, false) - 8.0).abs() < 1e-4);
assert!((dialog_card_y_offset(true, 0.0, 1.0, false) - 0.0).abs() < 1e-4);
assert!((dialog_card_y_offset(false, 0.0, 0.0, false) - 4.0).abs() < 1e-4);
assert_eq!(dialog_card_y_offset(true, 6.0, 0.5, true), 0.0);
let (old_a0, _, new_a0, new_y0) = swap_text_sample(0.0, false);
assert!(old_a0 > 0.95);
assert!(new_a0 < 0.05);
assert!(new_y0 > 4.0);
let (old_a1, _, new_a1, new_y1) = swap_text_sample(0.25, false);
assert_eq!(old_a1, 0.0);
assert_eq!(new_a1, 1.0);
assert_eq!(new_y1, 0.0);
}
#[gpui_kit::test]
fn dialog_opens_on_trigger_and_closes_on_close_button_or_outside_click(
cx: &mut TestAppContext,
) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let close_count = Rc::new(Cell::new(0));
let (_view, cx) = cx.add_window_view(|_, _| DialogHarness {
open: false,
title: "Archive project".into(),
close_count: close_count.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let trig = window.find_by_label("Open dialog");
assert_eq!(trig.role(), Some(Role::Button));
let tpos = trig.bounds().center();
window.pointer_down(tpos, MouseButton::Left, cx);
window.pointer_up(tpos, MouseButton::Left, cx);
window.render_frame(cx);
let modal = window.find_by_label("Archive project");
assert_eq!(modal.role(), Some(Role::Dialog));
let close_btn = window.find_by_label("Close dialog");
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!(close_count.get(), 1);
});
}
}