use super::form::{inset_outline, rem};
use super::overlay::Callback;
use super::typography::Inline;
use crate::{
icons::{CarbonIcon, Icon, IconSize},
motion::{self, Curve, Motion, Speed},
theme::color,
tokens::{ColorRole, FontFamilyKey, TypeStyle},
typography::{TypeStyled as _, font, inline_code_font},
};
use gpui_kit::base::SelectableText;
use gpui_kit::{
AnyElement, App, ClipboardItem, CursorStyle, ElementId, Hsla, InteractiveElement as _,
InteractiveText, IntoElement, MouseButton, ParentElement, RenderOnce, SharedString,
StatefulInteractiveElement as _, Styled, StyledText, TextRun, UnderlineStyle, Window, div,
prelude::FluentBuilder as _, px,
};
use std::rc::Rc;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum NotificationKind {
Error,
Success,
Warning,
#[default]
Info,
}
impl NotificationKind {
pub const ALL: [NotificationKind; 4] = [Self::Error, Self::Success, Self::Warning, Self::Info];
pub const fn name(self) -> &'static str {
match self {
Self::Error => "error",
Self::Success => "success",
Self::Warning => "warning",
Self::Info => "info",
}
}
pub const fn icon(self) -> CarbonIcon {
match self {
Self::Error => CarbonIcon::ErrorFilled,
Self::Success => CarbonIcon::CheckmarkFilled,
Self::Warning => CarbonIcon::WarningFilled,
Self::Info => CarbonIcon::InformationFilled,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AlertVariant {
#[default]
Default,
Destructive,
Success,
Warning,
Info,
Error,
}
impl AlertVariant {
pub const ALL: [AlertVariant; 6] = [
Self::Default,
Self::Destructive,
Self::Success,
Self::Warning,
Self::Info,
Self::Error,
];
pub const fn name(self) -> &'static str {
match self {
Self::Default => "default",
Self::Destructive => "destructive",
Self::Success => "success",
Self::Warning => "warning",
Self::Info => "info",
Self::Error => "error",
}
}
pub const fn kind(self) -> NotificationKind {
match self {
Self::Default | Self::Info => NotificationKind::Info,
Self::Destructive | Self::Error => NotificationKind::Error,
Self::Success => NotificationKind::Success,
Self::Warning => NotificationKind::Warning,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NotificationLook {
pub background: Hsla,
pub accent: Hsla,
pub outline: Option<Hsla>,
pub text: Hsla,
pub close_icon: Hsla,
pub focus: Hsla,
}
impl NotificationLook {
pub fn of(kind: NotificationKind, low_contrast: bool) -> Self {
use NotificationKind::*;
if low_contrast {
let (bg, accent) = match kind {
Error => (
ColorRole::NotificationBackgroundError,
ColorRole::SupportError,
),
Success => (
ColorRole::NotificationBackgroundSuccess,
ColorRole::SupportSuccess,
),
Warning => (
ColorRole::NotificationBackgroundWarning,
ColorRole::SupportWarning,
),
Info => (
ColorRole::NotificationBackgroundInfo,
ColorRole::SupportInfo,
),
};
Self {
background: color(bg),
accent: color(accent),
outline: Some(color(accent).opacity(0.4)),
text: color(ColorRole::TextPrimary),
close_icon: color(ColorRole::IconPrimary),
focus: color(ColorRole::Focus),
}
} else {
let accent = match kind {
Error => ColorRole::SupportErrorInverse,
Success => ColorRole::SupportSuccessInverse,
Warning => ColorRole::SupportWarningInverse,
Info => ColorRole::SupportInfoInverse,
};
Self {
background: color(ColorRole::BackgroundInverse),
accent: color(accent),
outline: None,
text: color(ColorRole::TextInverse),
close_icon: color(ColorRole::IconInverse),
focus: color(ColorRole::FocusInverse),
}
}
}
}
pub const ACCENT_WIDTH: f32 = 3.;
pub const ROW_HEIGHT: f32 = 48.;
pub const DETAILS_MARGIN: f32 = 13.;
pub fn max_width(width_rem: f32) -> f32 {
if width_rem >= 99. {
52. * 16.
} else if width_rem >= 66. {
46. * 16.
} else if width_rem >= 42. {
38. * 16.
} else {
18. * 16.
}
}
pub fn is_wide(width_rem: f32) -> bool {
width_rem >= 42.
}
pub(crate) fn viewport_rem(window: &Window) -> f32 {
f32::from(window.viewport_size().width) / f32::from(window.rem_size())
}
pub(crate) fn status_icon(kind: NotificationKind, accent: Hsla) -> AnyElement {
let icon = Icon::carbon(kind.icon()).size(IconSize::S20).color(accent);
if kind != NotificationKind::Warning {
return icon.into_any_element();
}
div()
.relative()
.size(rem(20.))
.flex_none()
.child(
div()
.absolute()
.left(rem(8.5))
.top(rem(5.))
.w(rem(3.))
.h(rem(10.5))
.bg(gpui_kit::black()),
)
.child(icon.absolute().top_0().left_0())
.into_any_element()
}
pub const CLOSE_MOTION: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast02);
pub(crate) fn close_button(
id: ElementId,
look: NotificationLook,
label: SharedString,
on_click: Callback,
window: &mut Window,
cx: &mut App,
) -> gpui_kit::base::Button {
let focus = window
.use_keyed_state((id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
.read(cx)
.clone();
square_button(
id,
CarbonIcon::Close,
look,
label,
Rc::new(move |window, cx| {
crate::u0::primitives::parts::vacate_focus(&focus, window, cx);
on_click(window, cx)
}),
window,
cx,
)
}
pub const COPIED_MS: u64 = 2000;
pub const FOLD_LINES: usize = 6;
pub const FOLD_CHARS: usize = 480;
pub fn fold_at(words: &str) -> Option<usize> {
let by_lines = words
.match_indices('\n')
.nth(FOLD_LINES - 1)
.map(|(i, _)| i);
let by_chars = words.char_indices().nth(FOLD_CHARS).map(|(i, _)| i);
let at = match (by_lines, by_chars) {
(Some(a), Some(b)) => a.min(b),
(a, b) => a.or(b)?,
};
(!words[at..].trim().is_empty()).then_some(at)
}
pub fn copied_text(title: Option<&str>, words: Option<&str>) -> String {
match (title, words) {
(Some(t), Some(w)) => format!("{t}\n{w}"),
(t, w) => t.or(w).unwrap_or_default().to_owned(),
}
}
fn square_button(
id: ElementId,
icon: CarbonIcon,
look: NotificationLook,
label: SharedString,
on_click: Callback,
window: &mut Window,
cx: &mut App,
) -> gpui_kit::base::Button {
let focus = window
.use_keyed_state((id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
.read(cx)
.clone();
let outline = motion::animate_color(
(id.clone(), "outline"),
if focus.is_focused(window) {
look.focus
} else {
look.focus.opacity(0.)
},
CLOSE_MOTION,
window,
cx,
);
gpui_kit::base::Button::new(id)
.track_focus(&focus)
.accessibility_label(label)
.relative()
.flex_none()
.size(rem(ROW_HEIGHT))
.flex()
.items_center()
.justify_center()
.cursor(CursorStyle::PointingHand)
.child(
Icon::carbon(icon)
.size(IconSize::S20)
.color(look.close_icon),
)
.child(inset_outline(2., outline))
.on_click(move |_, window, cx| on_click(window, cx))
}
pub struct AlertTitle(pub SharedString);
impl AlertTitle {
pub fn new(text: impl Into<SharedString>) -> Self {
Self(text.into())
}
}
pub struct AlertDescription(pub AnyElement);
impl AlertDescription {
pub fn new(content: impl IntoElement) -> Self {
Self(content.into_any_element())
}
}
pub struct AlertAction {
label: SharedString,
on_click: Option<Callback>,
}
impl AlertAction {
pub fn new(label: impl Into<SharedString>) -> Self {
Self {
label: label.into(),
on_click: None,
}
}
pub fn on_click(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_click = Some(Rc::new(f));
self
}
}
enum Description {
Element(AnyElement),
Inlines(Vec<Inline>),
}
pub type DescriptionRuns = (
String,
Vec<TextRun>,
Vec<(std::ops::Range<usize>, SharedString)>,
);
pub fn description_runs(inlines: &[Inline], ink: Hsla) -> DescriptionRuns {
let mut text = String::new();
let mut runs = Vec::new();
let mut links = Vec::new();
for inline in inlines {
let (s, run_font, run_color, underline) = match inline {
Inline::Text(s) => (s, font(FontFamilyKey::Sans, 400), ink, None),
Inline::Code(s) => (s, inline_code_font(), ink, None),
Inline::Link(s, _) => {
let link = color(ColorRole::LinkPrimary);
(
s,
font(FontFamilyKey::Sans, 400),
link,
Some(UnderlineStyle {
thickness: px(1.),
color: Some(link),
wavy: false,
}),
)
}
};
let start = text.len();
text.push_str(s);
if let Inline::Link(_, href) = inline {
links.push((start..text.len(), href.clone()));
}
runs.push(TextRun {
len: s.len(),
font: run_font,
color: run_color,
background_color: None,
underline,
strikethrough: None,
});
}
(text, runs, links)
}
#[derive(IntoElement)]
pub struct Alert {
id: ElementId,
variant: AlertVariant,
title: Option<SharedString>,
description: Vec<Description>,
action: Option<AlertAction>,
full_width: bool,
on_close: Option<Callback>,
close_label: SharedString,
low_contrast: bool,
words: Option<SharedString>,
copy: Option<(SharedString, SharedString)>,
fold: Option<(SharedString, SharedString)>,
}
impl Alert {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
variant: AlertVariant::Default,
title: None,
description: Vec::new(),
action: None,
full_width: false,
on_close: None,
close_label: "Close notification".into(),
low_contrast: true,
words: None,
copy: None,
fold: None,
}
}
pub fn variant(mut self, variant: AlertVariant) -> Self {
self.variant = variant;
self
}
pub fn title(mut self, title: impl Into<SharedString>) -> Self {
self.title = Some(title.into());
self
}
pub fn description(mut self, content: impl IntoElement) -> Self {
self.description
.push(Description::Element(content.into_any_element()));
self
}
pub fn description_inlines(mut self, inlines: impl IntoIterator<Item = Inline>) -> Self {
self.description
.push(Description::Inlines(inlines.into_iter().collect()));
self
}
pub fn words(mut self, words: impl Into<SharedString>) -> Self {
self.words = Some(words.into());
self
}
pub fn copy(mut self, label: impl Into<SharedString>, copied: impl Into<SharedString>) -> Self {
self.copy = Some((label.into(), copied.into()));
self
}
pub fn fold(
mut self,
show_all: impl Into<SharedString>,
show_less: impl Into<SharedString>,
) -> Self {
self.fold = Some((show_all.into(), show_less.into()));
self
}
pub fn alert_title(mut self, title: AlertTitle) -> Self {
self.title = Some(title.0);
self
}
pub fn alert_description(mut self, description: AlertDescription) -> Self {
self.description.push(Description::Element(description.0));
self
}
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
self
}
pub fn action(mut self, action: AlertAction) -> Self {
self.action = Some(action);
self
}
pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_close = Some(Rc::new(f));
self
}
pub fn close_label(mut self, label: impl Into<SharedString>) -> Self {
self.close_label = label.into();
self
}
pub fn low_contrast(mut self, low: bool) -> Self {
self.low_contrast = low;
self
}
}
fn action_button(
id: ElementId,
action: AlertAction,
low_contrast: bool,
look: NotificationLook,
window: &mut Window,
cx: &mut App,
) -> impl IntoElement {
let pointer = window.use_keyed_state((id.clone(), "pointer"), cx, |_, _| (false, false));
let focus = window
.use_keyed_state((id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
.read(cx)
.clone();
let (hovered, pressed) = *pointer.read(cx);
let hover_bg = color(if low_contrast {
ColorRole::NotificationActionHover
} else {
ColorRole::BackgroundInverseHover
});
let bg = motion::animate_color(
(id.clone(), "bg"),
if hovered || pressed {
hover_bg
} else {
hover_bg.opacity(0.)
},
Motion::HOVER,
window,
cx,
);
let text = color(if low_contrast {
ColorRole::LinkPrimary
} else {
ColorRole::LinkInverse
});
let on_click = action.on_click.clone();
gpui_kit::base::Button::new(id)
.track_focus(&focus)
.accessibility_label(action.label.clone())
.relative()
.flex_none()
.h(rem(32.))
.px(rem(12.))
.pt(px(1.))
.flex()
.items_start()
.whitespace_nowrap()
.type_style(TypeStyle::BodyCompact01)
.text_color(text)
.bg(bg)
.cursor(CursorStyle::PointingHand)
.on_hover({
let pointer = pointer.clone();
move |h, _, cx| {
pointer.update(cx, |p, cx| {
p.0 = *h;
if !h {
p.1 = false;
}
cx.notify();
})
}
})
.on_mouse_down(MouseButton::Left, {
let pointer = pointer.clone();
move |_, _, cx| {
pointer.update(cx, |p, cx| {
p.1 = true;
cx.notify();
})
}
})
.on_mouse_up(MouseButton::Left, move |_, _, cx| {
pointer.update(cx, |p, cx| {
p.1 = false;
cx.notify();
})
})
.when_some(on_click, |d, f| {
let focus = focus.clone();
d.on_click(move |_, window, cx| {
crate::u0::primitives::parts::vacate_focus(&focus, window, cx);
f(window, cx)
})
})
.child(action.label)
.when(focus.is_focused(window), |d| {
d.child(inset_outline(2., look.focus))
})
}
impl RenderOnce for Alert {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let open = window.use_keyed_state((id.clone(), "open"), cx, |_, _| true);
if !*open.read(cx) {
return div().into_any_element();
}
let kind = self.variant.kind();
let look = NotificationLook::of(kind, self.low_contrast);
let vw = viewport_rem(window);
let wide = is_wide(vw);
let closable = self.on_close.is_some();
let corner = usize::from(closable) + usize::from(self.copy.is_some());
let unfolded = window.use_keyed_state((id.clone(), "unfolded"), cx, |_, _| false);
let words = self.words.clone().map(|words| {
let cut = self.fold.as_ref().and_then(|_| fold_at(&words));
let all = *unfolded.read(cx);
let shown: SharedString = match cut {
Some(at) if !all => words[..at].trim_end().to_owned().into(),
_ => words.clone(),
};
let link = cut.and(self.fold.clone()).map(|(more, less)| {
let unfolded = unfolded.clone();
let focus = window
.use_keyed_state((id.clone(), "fold-focus"), cx, |_, cx| cx.focus_handle())
.read(cx)
.clone();
gpui_kit::base::Button::new((id.clone(), "fold"))
.track_focus(&focus)
.relative()
.self_start()
.mt(rem(4.))
.cursor(CursorStyle::PointingHand)
.text_color(color(ColorRole::LinkPrimary))
.hover(|s| s.text_color(color(ColorRole::LinkPrimaryHover)))
.child(if all { less } else { more })
.when(focus.is_focused(window), |d| {
d.child(inset_outline(1., look.focus))
})
.on_click(move |_, _, cx| {
unfolded.update(cx, |u, cx| {
*u = !*u;
cx.notify();
})
})
});
div()
.flex()
.flex_col()
.flex_shrink_1()
.min_w_0()
.type_style(TypeStyle::BodyCompact01)
.child(SelectableText::new((id.clone(), "words"), shown))
.children(link)
});
let text = div()
.flex()
.flex_row()
.flex_wrap()
.flex_1()
.min_w_0()
.py(rem(15.))
.text_color(look.text)
.when_some(self.title.clone(), |d, t| {
d.child(
div()
.flex_shrink_1()
.min_w_0()
.type_style(TypeStyle::HeadingCompact01)
.mr(rem(4.))
.child(SelectableText::new((id.clone(), "title"), t)),
)
})
.children(self.description.into_iter().enumerate().map(|(i, c)| {
let c = match c {
Description::Element(e) => e,
Description::Inlines(inlines) => {
let (text, runs, links) = description_runs(&inlines, look.text);
let styled = StyledText::new(text).with_runs(runs);
if links.is_empty() {
styled.into_any_element()
} else {
let (ranges, targets): (Vec<_>, Vec<_>) = links.into_iter().unzip();
InteractiveText::new(
(id.clone(), SharedString::from(format!("description-{i}"))),
styled,
)
.on_click(ranges, move |ix, _, cx| cx.open_url(&targets[ix]))
.into_any_element()
}
}
};
div()
.flex_shrink_1()
.min_w_0()
.type_style(TypeStyle::BodyCompact01)
.child(c)
}))
.children(words);
let details = div()
.flex()
.flex_row()
.flex_1()
.min_w_0()
.ml(rem(DETAILS_MARGIN))
.mr(rem(if wide || corner == 0 {
DETAILS_MARGIN
} else {
ROW_HEIGHT * corner as f32
}))
.when(!wide, |d| d.w_full())
.child(
div()
.flex_none()
.mt(rem(14.))
.mr(rem(16.))
.child(status_icon(kind, look.accent)),
)
.child(text);
let actionable = self.action.is_some();
let action = self.action.map(|a| {
div()
.flex()
.flex_none()
.map(|d| {
if wide {
d.my(rem(8.))
} else {
d.ml(rem(40.)).mb(rem(8.))
}
})
.when(!closable, |d| d.mr(rem(8.)))
.child(action_button(
(id.clone(), "action").into(),
a,
self.low_contrast,
look,
window,
cx,
))
});
let close = self.on_close.clone().map(|f| {
let open = open.clone();
let button = close_button(
(id.clone(), "close").into(),
look,
self.close_label.clone(),
Rc::new(move |window, cx| {
f(window, cx);
open.update(cx, |o, cx| {
*o = false;
cx.notify();
});
}),
window,
cx,
);
if wide {
button
} else {
button.absolute().top_0().right_0()
}
});
let copy = self.copy.clone().map(|(label, copied)| {
let flash =
crate::u0::primitives::parts::flash_state((id.clone(), "copied"), window, cx);
let done = crate::u0::primitives::parts::flash_on(&flash, COPIED_MS, cx);
let text = copied_text(self.title.as_deref(), self.words.as_deref());
let button = square_button(
(id.clone(), "copy").into(),
if done {
CarbonIcon::Checkmark
} else {
CarbonIcon::Copy
},
look,
if done { copied } else { label },
Rc::new(move |_, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(text.clone()));
crate::u0::primitives::parts::flash(&flash, COPIED_MS, cx);
}),
window,
cx,
);
if wide {
button
} else {
button
.absolute()
.top_0()
.right(rem(if closable { ROW_HEIGHT } else { 0. }))
}
});
div()
.id(id)
.relative()
.flex()
.flex_row()
.when(!wide, |d| d.flex_wrap())
.w_full()
.when(self.full_width, |d| d.min_w_0())
.when(!self.full_width, |d| {
d.min_w(rem(288.)).max_w(rem(max_width(vw)))
})
.min_h(rem(ROW_HEIGHT))
.bg(look.background)
.border_l(rem(ACCENT_WIDTH))
.border_color(look.accent)
.when_some(look.outline, |d, outline| {
d.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.border_t(px(1.))
.border_r(px(1.))
.border_b(px(1.))
.border_color(outline),
)
})
.child(details)
.map(|d| {
if actionable && wide {
d.items_start().child(
div()
.flex()
.flex_row()
.flex_none()
.mt(rem(10.))
.mx(rem(16.))
.mb(rem(16.))
.children(action)
.children(copy)
.children(close),
)
} else {
d.children(action).children(copy).children(close)
}
})
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tokens::CarbonTheme;
#[test]
fn variants_map_like_kindof() {
assert_eq!(AlertVariant::Default.kind(), NotificationKind::Info);
assert_eq!(AlertVariant::Destructive.kind(), NotificationKind::Error);
assert_eq!(AlertVariant::Warning.kind(), NotificationKind::Warning);
assert_eq!(
NotificationKind::Success.icon(),
CarbonIcon::CheckmarkFilled
);
}
#[test]
fn looks_match_bundle() {
crate::theme::tests_set(CarbonTheme::White);
let low = NotificationLook::of(NotificationKind::Error, true);
assert_eq!(
low.background,
color(ColorRole::NotificationBackgroundError)
);
assert_eq!(low.accent, color(ColorRole::SupportError));
assert_eq!(
low.outline,
Some(color(ColorRole::SupportError).opacity(0.4))
);
assert_eq!(low.text, color(ColorRole::TextPrimary));
assert_eq!(low.close_icon, color(ColorRole::IconPrimary));
let high = NotificationLook::of(NotificationKind::Success, false);
assert_eq!(high.background, color(ColorRole::BackgroundInverse));
assert_eq!(high.accent, color(ColorRole::SupportSuccessInverse));
assert_eq!(high.outline, None);
assert_eq!(high.text, color(ColorRole::TextInverse));
assert_eq!(high.focus, color(ColorRole::FocusInverse));
assert_eq!(
NotificationLook::of(NotificationKind::Warning, true).accent,
color(ColorRole::SupportWarning)
);
}
#[test]
fn long_words_fold_after_six_lines_or_480_characters() {
let trace: String = (1..=20).map(|i| format!(" at line {i}\n")).collect();
let at = fold_at(&trace).unwrap();
assert_eq!(trace[..at].lines().count(), FOLD_LINES);
assert!(trace[..at].ends_with("line 6"));
assert_eq!(fold_at("one line"), None);
assert_eq!(fold_at("a\nb\nc\nd\ne\nf\n"), None);
let long = "語".repeat(500);
let at = fold_at(&long).unwrap();
assert_eq!(long[..at].chars().count(), FOLD_CHARS);
}
#[test]
fn copy_takes_the_title_and_all_the_words() {
assert_eq!(
copied_text(Some("Stopped"), Some("at a\nat b")),
"Stopped\nat a\nat b"
);
assert_eq!(copied_text(None, Some("why")), "why");
assert_eq!(copied_text(Some("Stopped"), None), "Stopped");
assert_eq!(copied_text(None, None), "");
}
#[test]
fn a_rich_description_sets_its_command_in_mono() {
crate::theme::tests_set(CarbonTheme::White);
let ink = color(ColorRole::TextPrimary);
let (text, runs, links) = description_runs(
&[
Inline::Text("Install it with ".into()),
Inline::Code("brew install gh".into()),
Inline::Text(".".into()),
],
ink,
);
assert_eq!(text, "Install it with brew install gh.");
assert_eq!(runs.iter().map(|r| r.len).collect::<Vec<_>>(), [16, 15, 1]);
assert_eq!(runs[1].font.family, inline_code_font().family);
assert_eq!(runs[0].font.family, font(FontFamilyKey::Sans, 400).family);
assert!(
runs.iter()
.all(|r| r.background_color.is_none() && r.color == ink)
);
assert!(links.is_empty());
}
#[test]
fn widths_follow_media_queries() {
assert_eq!(max_width(30.), 288.);
assert_eq!(max_width(42.), 608.);
assert_eq!(max_width(70.), 736.);
assert_eq!(max_width(100.), 832.);
assert!(!is_wide(41.9) && is_wide(42.));
assert_eq!(ROW_HEIGHT, 48.);
assert_eq!(ACCENT_WIDTH, 3.);
}
}