use super::button::{Button, ButtonSize, ButtonVariant};
use super::button_group::{ButtonGroupOrientation, separator_color};
use super::overlay::{self, OpenChange, Translate, rem};
use crate::{
density::{self, Density},
icons::{CarbonIcon, Icon, IconSize},
motion::{self, Curve, Motion, Speed},
theme::color,
tokens::{ColorRole, TypeStyle},
typography::TypeStyled as _,
};
use gpui_kit::{
AnyElement, App, CursorStyle, ElementId, FocusHandle, Hsla, InteractiveElement, IntoElement,
ParentElement, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled, Window, div,
prelude::FluentBuilder as _, px,
};
use std::rc::Rc;
pub const MODAL_ENTER: Motion = Motion::new(Curve::ExpressiveEntrance, Speed::Moderate02);
pub const MODAL_EXIT: Motion = Motion::new(Curve::ExpressiveExit, Speed::Moderate02);
pub const MODAL_TRAVEL: f32 = -24.;
const CLOSE_HOVER: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast02);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum DialogSize {
Xs,
#[default]
Sm,
Md,
Lg,
}
impl DialogSize {
pub const ALL: [DialogSize; 4] = [Self::Xs, Self::Sm, Self::Md, Self::Lg];
pub const fn name(self) -> &'static str {
match self {
Self::Xs => "xs",
Self::Sm => "sm",
Self::Md => "md",
Self::Lg => "lg",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ModalGeometry {
pub width: f32,
pub max_height: f32,
pub centered: bool,
pub text_inset: f32,
pub text_inset_px: f32,
}
impl ModalGeometry {
pub fn of(size: DialogSize, viewport_rem: f32) -> Self {
let (widths, max_lg) = match size {
DialogSize::Xs => ([1., 0.48, 0.32, 0.24], 0.48),
DialogSize::Sm => ([1., 0.60, 0.42, 0.36], 0.72),
DialogSize::Md => ([1., 0.84, 0.60, 0.48], 0.84),
DialogSize::Lg => ([1., 0.96, 0.84, 0.72], 0.96),
};
let column = if viewport_rem >= 82. {
3
} else if viewport_rem >= 66. {
2
} else if viewport_rem >= 42. {
1
} else {
0
};
let max_height = match column {
0 => 1.,
1 => 0.90,
_ => max_lg,
};
let (text_inset, text_inset_px) = match (size, column) {
(DialogSize::Xs, _) => (0., 0.),
(DialogSize::Sm, 0 | 1) => (0., 0.),
(DialogSize::Sm, _) => (0.2, 0.),
_ => (0.2, 32.),
};
Self {
width: widths[column],
max_height,
centered: column > 0,
text_inset,
text_inset_px,
}
}
pub fn text_padding(&self, width: f32) -> f32 {
(width * self.text_inset - self.text_inset_px).max(0.)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ModalLook {
pub scrim: Hsla,
pub container: Hsla,
pub border: Hsla,
pub label: Hsla,
pub text: Hsla,
pub close_icon: Hsla,
pub close_hover: Hsla,
}
impl ModalLook {
pub fn current() -> Self {
use ColorRole::*;
Self {
scrim: color(Overlay),
container: color(Layer01),
border: color(BorderSubtle01),
label: color(TextSecondary),
text: color(TextPrimary),
close_icon: color(IconPrimary),
close_hover: color(LayerHover01),
}
}
}
type Action = Rc<dyn Fn(&mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct Dialog {
id: ElementId,
open: Option<bool>,
default_open: bool,
on_open_change: Option<OpenChange>,
trigger: Option<AnyElement>,
title: Option<SharedString>,
label: Option<SharedString>,
description: Option<SharedString>,
children: Vec<AnyElement>,
primary_text: Option<SharedString>,
secondary_text: Option<SharedString>,
on_primary: Option<Action>,
on_secondary: Option<Action>,
danger: bool,
passive: bool,
size: DialogSize,
primary_disabled: bool,
alert: bool,
close_on_backdrop: bool,
close_label: SharedString,
initial_focus: Option<FocusHandle>,
}
impl Dialog {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
open: None,
default_open: false,
on_open_change: None,
trigger: None,
title: None,
label: None,
description: None,
children: Vec::new(),
primary_text: None,
secondary_text: None,
on_primary: None,
on_secondary: None,
danger: false,
passive: false,
size: DialogSize::Sm,
primary_disabled: false,
alert: false,
close_on_backdrop: true,
close_label: "Close".into(),
initial_focus: None,
}
}
pub fn open(mut self, open: bool) -> Self {
self.open = Some(open);
self
}
pub fn default_open(mut self, open: bool) -> Self {
self.default_open = open;
self
}
pub fn on_open_change(mut self, f: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
self.on_open_change = Some(Rc::new(f));
self
}
pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
self.trigger = Some(trigger.into_any_element());
self
}
pub fn title(mut self, title: impl Into<SharedString>) -> Self {
self.title = Some(title.into());
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn primary_text(mut self, text: impl Into<SharedString>) -> Self {
self.primary_text = Some(text.into());
self
}
pub fn secondary_text(mut self, text: impl Into<SharedString>) -> Self {
self.secondary_text = Some(text.into());
self
}
pub fn on_primary(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_primary = Some(Rc::new(f));
self
}
pub fn on_secondary(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_secondary = Some(Rc::new(f));
self
}
pub fn danger(mut self, danger: bool) -> Self {
self.danger = danger;
self
}
pub fn passive(mut self, passive: bool) -> Self {
self.passive = passive;
self
}
pub fn size(mut self, size: DialogSize) -> Self {
self.size = size;
self
}
pub fn primary_disabled(mut self, disabled: bool) -> Self {
self.primary_disabled = disabled;
self
}
pub fn alert(mut self, alert: bool) -> Self {
self.alert = alert;
self
}
pub fn close_on_backdrop(mut self, close: bool) -> Self {
self.close_on_backdrop = close;
self
}
pub fn close_label(mut self, label: impl Into<SharedString>) -> Self {
self.close_label = label.into();
self
}
pub fn initial_focus(mut self, handle: &FocusHandle) -> Self {
self.initial_focus = Some(handle.clone());
self
}
fn is_passive(&self) -> bool {
self.passive || self.primary_text.is_none()
}
#[cfg(test)]
pub(crate) fn is_danger(&self) -> bool {
self.danger
}
#[cfg(test)]
pub(crate) fn is_alert(&self) -> bool {
self.alert
}
#[cfg(test)]
pub(crate) fn closes_on_backdrop(&self) -> bool {
self.close_on_backdrop
}
}
impl ParentElement for Dialog {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
struct Handles {
primary: FocusHandle,
secondary: FocusHandle,
close: FocusHandle,
}
pub fn footer_separator(
has_secondary: bool,
primary_disabled: bool,
primary_focused: bool,
secondary_focused: bool,
) -> Option<Hsla> {
separator_color(
ButtonGroupOrientation::Horizontal,
!has_secondary,
primary_disabled,
primary_focused,
secondary_focused,
)
}
pub fn footer_button_size(density: Density) -> ButtonSize {
match density {
Density::Compact => ButtonSize::Lg,
Density::Comfortable => ButtonSize::Xl,
}
}
impl RenderOnce for Dialog {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let openness = overlay::openness(
&id,
self.open,
self.default_open,
self.on_open_change.clone(),
window,
cx,
);
let open = openness.open;
let progress = overlay::presence(id.clone(), open, MODAL_ENTER, MODAL_EXIT, window, cx);
let set_open = openness.setter();
let handles = window
.use_keyed_state((id.clone(), "handles"), cx, |_, cx| Handles {
primary: cx.focus_handle(),
secondary: cx.focus_handle(),
close: cx.focus_handle(),
})
.read(cx);
let (primary_focus, secondary_focus, close_focus) = (
handles.primary.clone(),
handles.secondary.clone(),
handles.close.clone(),
);
let passive = self.is_passive();
let initial = self.initial_focus.clone().or_else(|| {
if passive {
Some(close_focus.clone())
} else if self.danger && self.secondary_text.is_some() {
Some(secondary_focus.clone())
} else if self.primary_disabled {
Some(close_focus.clone())
} else {
Some(primary_focus.clone())
}
});
let focus = overlay::surface_focus(&id, open, initial, window, cx);
let trigger = self.trigger.map(|trigger| {
let set_open = set_open.clone();
overlay::trigger_wrapper(
(id.clone(), "trigger"),
trigger,
Rc::new(move |window, cx| set_open(true, window, cx)),
)
});
let root = div().flex().flex_shrink_0().children(trigger);
if !open && progress <= 0. {
return root.into_any_element();
}
let look = ModalLook::current();
let viewport = window.viewport_size();
let rem_size = f32::from(window.rem_size());
let viewport_rem = f32::from(viewport.width) / rem_size;
let geometry = ModalGeometry::of(self.size, viewport_rem);
let scale = rem_size / crate::tokens::REM_PX;
let width_px = f32::from(viewport.width) * geometry.width / scale;
let max_height_px = f32::from(viewport.height) * geometry.max_height / scale;
let reduced = motion::reduced_motion(cx);
let travel = if reduced {
0.
} else {
MODAL_TRAVEL * (1. - progress)
};
let close_hover = window.use_keyed_state((id.clone(), "close-hover"), cx, |_, _| false);
let close_bg = motion::animate_color(
(id.clone(), "close-bg"),
if *close_hover.read(cx) {
look.close_hover
} else {
Hsla::transparent_black()
},
CLOSE_HOVER,
window,
cx,
);
let close = {
let set_open = set_open.clone();
gpui_kit::base::Button::new((id.clone(), "close"))
.track_focus(&close_focus)
.accessibility_label(self.close_label.clone())
.absolute()
.top_0()
.right_0()
.size(rem(48.))
.flex()
.items_center()
.justify_center()
.bg(close_bg)
.border_2()
.border_color(if close_focus.is_focused(window) {
color(ColorRole::Focus)
} else {
Hsla::transparent_black()
})
.cursor(CursorStyle::PointingHand)
.on_hover(move |hovered, _, cx| {
close_hover.update(cx, |h, cx| {
*h = *hovered;
cx.notify();
})
})
.on_click(move |_, window, cx| set_open(false, window, cx))
.child(
Icon::carbon(CarbonIcon::Close)
.size(IconSize::S20)
.color(look.close_icon),
)
};
let header = div()
.flex()
.flex_col()
.flex_shrink_0()
.pt(rem(16.))
.pl(rem(16.))
.pr(rem(48.))
.mb(rem(8.))
.when_some(self.label.clone(), |this, label| {
this.child(
div()
.type_style(TypeStyle::Label01)
.text_color(look.label)
.mb(rem(4.))
.child(label),
)
})
.when_some(self.title.clone(), |this, title| {
this.child(
div()
.type_style(TypeStyle::Heading03)
.text_color(look.text)
.pr(rem((width_px * 0.2 - 48.).max(0.)))
.child(title),
)
});
let text_padding = geometry.text_padding(width_px - 32.);
let body = div()
.id((id.clone(), "body"))
.flex_1()
.min_h_0()
.overflow_y_scroll()
.pt(rem(8.))
.pb(rem(48.))
.px(rem(16.))
.type_style(TypeStyle::Body01)
.text_color(look.text)
.flex()
.flex_col()
.when_some(self.description.clone(), |this, description| {
this.child(div().mb(rem(16.)).pr(rem(text_padding)).child(description))
})
.children(self.children);
let footer_button = footer_button_size(density::current());
let footer = (!passive).then(|| {
let secondary = self.secondary_text.clone().map(|text| {
let on_secondary = self.on_secondary.clone();
let set_open = set_open.clone();
div().w_1_2().child(
Button::new((id.clone(), "secondary"), text)
.variant(ButtonVariant::Secondary)
.size(footer_button)
.full_width(true)
.track_focus(&secondary_focus)
.on_click(move |_, window, cx| match &on_secondary {
Some(f) => f(window, cx),
None => set_open(false, window, cx),
}),
)
});
let separator = footer_separator(
secondary.is_some(),
self.primary_disabled,
primary_focus.is_focused(window),
secondary_focus.is_focused(window),
);
let primary = self.primary_text.clone().map(|text| {
let on_primary = self.on_primary.clone();
div()
.relative()
.w_1_2()
.child(
Button::new((id.clone(), "primary"), text)
.variant(if self.danger {
ButtonVariant::Danger
} else {
ButtonVariant::Primary
})
.size(footer_button)
.full_width(true)
.disabled(self.primary_disabled)
.track_focus(&primary_focus)
.on_click(move |_, window, cx| {
if let Some(f) = &on_primary {
f(window, cx)
}
}),
)
.when_some(separator, |this, line| {
this.child(
div()
.absolute()
.top_0()
.bottom_0()
.left(px(-1.))
.w(px(1.))
.bg(line),
)
})
});
div()
.flex()
.flex_row()
.flex_shrink_0()
.justify_end()
.items_start()
.h(rem(64.))
.children(secondary)
.children(primary)
});
let container = div()
.id((id.clone(), "container"))
.relative()
.flex()
.flex_col()
.w(rem(width_px))
.max_h(rem(max_height_px))
.bg(look.container)
.border_1()
.border_color(look.border)
.occlude()
.child(header)
.child(body)
.children(footer)
.child(close);
let surface = div()
.opacity(progress)
.when(!geometry.centered, |this| this.absolute().top_0().left_0())
.child(Translate::y(container, travel));
let set_cancel = set_open.clone();
let set_scrim = set_open.clone();
let close_on_scrim = self.close_on_backdrop && !self.alert;
let scrim = div()
.id((id.clone(), "scrim"))
.size_full()
.bg(look.scrim)
.opacity(progress)
.occlude()
.on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
if open && close_on_scrim {
set_scrim(false, window, cx);
}
});
macro_rules! host {
($host:expr) => {
$host
.open(true)
.focus_handle(focus)
.on_ok(|_, _, cx| {
cx.propagate();
false
})
.on_cancel(move |_, window, cx| {
if open {
set_cancel(false, window, cx);
}
false
})
.backdrop(scrim)
.popup(surface)
};
}
let host = if self.alert {
host!(gpui_kit::base::AlertDialog::new(cx)).into_any_element()
} else {
host!(
gpui_kit::base::Dialog::new(cx)
.when_some(self.title.clone(), |this, title| {
this.accessibility_label(title)
})
.close_on_backdrop_press(self.close_on_backdrop)
)
.into_any_element()
};
root.child(host).into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tokens::CarbonTheme;
fn hex(c: Hsla) -> String {
let c = c.to_rgb();
let b = |v: f32| (v * 255.).round() as u8;
format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b))
}
#[test]
fn widths_follow_modal_container_media_queries() {
let sm = ModalGeometry::of(DialogSize::Sm, 80.);
assert_eq!((sm.width, sm.max_height, sm.centered), (0.42, 0.72, true));
assert_eq!(ModalGeometry::of(DialogSize::Sm, 90.).width, 0.36);
assert_eq!(ModalGeometry::of(DialogSize::Sm, 50.).width, 0.60);
assert_eq!(ModalGeometry::of(DialogSize::Xs, 70.).max_height, 0.48);
assert_eq!(ModalGeometry::of(DialogSize::Md, 50.).max_height, 0.90);
assert_eq!(ModalGeometry::of(DialogSize::Lg, 85.).width, 0.72);
let narrow = ModalGeometry::of(DialogSize::Md, 40.);
assert_eq!((narrow.width, narrow.centered), (1., false));
}
#[test]
fn footer_buttons_are_32px_in_compact_and_64px_in_comfortable() {
let compact = footer_button_size(Density::Compact);
let comfortable = footer_button_size(Density::Comfortable);
assert_eq!(compact.height(Density::Compact), 32.);
assert_eq!(comfortable.height(Density::Comfortable), 64.);
}
#[test]
fn paragraph_inset_follows_modal_content_p() {
assert_eq!(
ModalGeometry::of(DialogSize::Md, 80.).text_padding(500.),
68.
);
assert_eq!(
ModalGeometry::of(DialogSize::Xs, 80.).text_padding(500.),
0.
);
assert_eq!(
ModalGeometry::of(DialogSize::Sm, 50.).text_padding(500.),
0.
);
assert_eq!(
ModalGeometry::of(DialogSize::Sm, 80.).text_padding(500.),
100.
);
}
#[test]
fn motion_follows_modal_presence_keyframes() {
assert_eq!(MODAL_ENTER.speed.millis(), 240);
assert_eq!(MODAL_ENTER.curve.points(), (0., 0., 0.3, 1.));
assert_eq!(MODAL_EXIT.speed.millis(), 240);
assert_eq!(MODAL_EXIT.curve.points(), (0.4, 0.14, 1., 1.));
assert_eq!(MODAL_TRAVEL, -24.);
assert_eq!(CLOSE_HOVER.speed.millis(), 110);
}
#[test]
fn look_follows_bundle_css() {
crate::theme::tests_set(CarbonTheme::White);
let look = ModalLook::current();
assert_eq!(hex(look.container), "#f4f4f4");
assert_eq!(hex(look.border), "#c6c6c6");
assert_eq!(hex(look.label), "#525252");
assert_eq!(hex(look.close_hover), "#e8e8e8");
assert!((look.scrim.a - 0.6).abs() < 0.01);
crate::theme::tests_set(CarbonTheme::G100);
assert_eq!(hex(ModalLook::current().container), "#262626");
}
#[test]
fn footer_separator_follows_btn_set() {
crate::theme::tests_set(CarbonTheme::White);
let line = footer_separator(true, false, false, false).map(hex);
assert_eq!(line.as_deref(), Some("#e0e0e0"));
assert_eq!(footer_separator(true, false, true, false), None);
assert_eq!(footer_separator(true, false, false, true), None);
assert_eq!(footer_separator(false, false, false, false), None);
crate::theme::tests_set(CarbonTheme::G100);
let line = footer_separator(true, false, false, false).map(hex);
assert_eq!(line.as_deref(), Some("#161616"));
}
#[test]
fn passive_without_primary_text() {
assert!(Dialog::new("d").is_passive());
assert!(!Dialog::new("d").primary_text("Save").is_passive());
assert!(
Dialog::new("d")
.primary_text("Save")
.passive(true)
.is_passive()
);
let plain = Dialog::new("d");
assert!(!plain.is_danger() && !plain.is_alert() && plain.closes_on_backdrop());
}
}