use super::{child_id, text};
use crate::{Avatar, Button, ButtonSize, ButtonVariant};
use arc_motion::{ArcPresence, ArcPresenceConfig, arc_spring};
use arc_tokens::{
ActiveArcTheme as _, BlockTokens, NotificationTokens as N, Radii, Shadows, Spacing, Typography,
};
use gpui_kit::base::{ElementExt as _, StyledExt as _};
use gpui_kit::{
Anchor, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, KeyDownEvent,
MouseDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Size, Styled,
TestSupportExt as _, Transformation, Window, anchored,
assets::IconName,
base::{Button as BaseButton, MotionReveal},
canvas, deferred, div, point,
prelude::*,
px, size, svg,
};
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
rc::Rc,
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NotificationTone {
#[default]
Info,
Success,
Warning,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NotificationActor {
pub name: SharedString,
pub photo: SharedString,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NotificationItem {
pub id: SharedString,
pub title: SharedString,
pub description: Option<SharedString>,
pub time: SharedString,
pub read: bool,
pub tone: NotificationTone,
pub actor: Option<NotificationActor>,
}
impl NotificationItem {
pub fn new(
id: impl Into<SharedString>,
title: impl Into<SharedString>,
time: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
title: title.into(),
time: time.into(),
description: None,
read: false,
tone: NotificationTone::Info,
actor: None,
}
}
pub fn description(mut self, value: impl Into<SharedString>) -> Self {
self.description = Some(value.into());
self
}
pub fn read(mut self, value: bool) -> Self {
self.read = value;
self
}
pub fn tone(mut self, value: NotificationTone) -> Self {
self.tone = value;
self
}
pub fn actor(mut self, name: impl Into<SharedString>, photo: impl Into<SharedString>) -> Self {
self.actor = Some(NotificationActor {
name: name.into(),
photo: photo.into(),
});
self
}
fn preview(&self) -> SharedString {
self.description
.clone()
.unwrap_or_else(|| match &self.actor {
Some(actor) => format!("From {}", actor.name).into(),
None => "View update details".into(),
})
}
fn body(&self) -> SharedString {
self.description
.clone()
.unwrap_or_else(|| match &self.actor {
Some(actor) => format!("{} shared an update with you.", actor.name).into(),
None => "This update is ready to review.".into(),
})
}
}
#[derive(Clone)]
struct State {
items: Vec<NotificationItem>,
unread_only: bool,
expanded: Option<SharedString>,
retained: Vec<NotificationItem>,
focus: HashMap<SharedString, FocusHandle>,
tabs: [FocusHandle; 2],
open: bool,
was_open: bool,
panel_focus: FocusHandle,
trigger_focus: FocusHandle,
trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
}
type ReadHandler = Rc<dyn Fn(&NotificationItem, bool, &mut Window, &mut App)>;
type DismissHandler = Rc<dyn Fn(&NotificationItem, &mut Window, &mut App)>;
type OpenHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
#[derive(Clone)]
struct PanelHandlers {
read: Option<ReadHandler>,
dismiss: Option<DismissHandler>,
close: CloseHandler,
}
#[derive(IntoElement)]
pub struct NotificationCenter {
id: ElementId,
notifications: Vec<NotificationItem>,
label: SharedString,
open: Option<bool>,
on_read_change: Option<ReadHandler>,
on_dismiss: Option<DismissHandler>,
on_open_change: Option<OpenHandler>,
avoid_collisions: bool,
}
impl NotificationCenter {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
notifications: vec![],
label: "Notifications".into(),
open: None,
on_read_change: None,
on_dismiss: None,
on_open_change: None,
avoid_collisions: true,
}
}
pub fn notifications(mut self, items: impl IntoIterator<Item = NotificationItem>) -> Self {
self.notifications = items.into_iter().collect();
self
}
pub fn label(mut self, v: impl Into<SharedString>) -> Self {
self.label = v.into();
self
}
pub fn open(mut self, v: bool) -> Self {
self.open = Some(v);
self
}
pub fn avoid_collisions(mut self, v: bool) -> Self {
self.avoid_collisions = v;
self
}
pub fn on_read_change(
mut self,
f: impl Fn(&NotificationItem, bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_read_change = Some(Rc::new(f));
self
}
pub fn on_dismiss(
mut self,
f: impl Fn(&NotificationItem, &mut Window, &mut App) + 'static,
) -> Self {
self.on_dismiss = Some(Rc::new(f));
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
}
}
fn notification_icon(name: IconName, size: Pixels, color: Hsla) -> gpui_kit::Svg {
svg()
.path(name.path())
.size(size)
.flex_none()
.text_color(color)
}
impl RenderOnce for NotificationCenter {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let initial = self.notifications;
let state = window.use_keyed_state(child_id(&self.id, "state"), cx, |_, cx| State {
retained: initial.clone(),
items: initial,
unread_only: false,
expanded: None,
focus: HashMap::new(),
tabs: [cx.focus_handle(), cx.focus_handle()],
open: false,
was_open: false,
panel_focus: cx.focus_handle(),
trigger_focus: cx.focus_handle(),
trigger_bounds: Rc::new(RefCell::new(None)),
panel_bounds: Rc::new(RefCell::new(None)),
});
let unread = state.read(cx).items.iter().filter(|i| !i.read).count();
let label = self.label.clone();
let id = self.id.clone();
let read = self.on_read_change;
let dismiss = self.on_dismiss;
let open_change = self.on_open_change;
let controlled = self.open;
let is_open = controlled.unwrap_or(state.read(cx).open);
let motion = cx.arc_theme().motion;
let presence = ArcPresence::new((child_id(&self.id, "presence"), "panel"), is_open)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: motion.duration.standard,
exit_duration: motion.duration.instant,
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let close: CloseHandler = {
let st = state.clone();
let cb = open_change.clone();
Rc::new(move |w: &mut Window, cx: &mut App| {
close_panel(&st, cb.as_ref(), w, cx);
})
};
let was_open = state.read(cx).was_open;
if is_open && !was_open {
let handle = state.read(cx).panel_focus.clone();
window.focus(&handle, cx);
state.update(cx, |s, _| s.was_open = true);
} else if !is_open && was_open {
state.update(cx, |s, _| s.was_open = false);
}
let trigger_focus = state.read(cx).trigger_focus.clone();
let panel_focus = state.read(cx).panel_focus.clone();
let trigger_bounds = state.read(cx).trigger_bounds.clone();
let panel_bounds = state.read(cx).panel_bounds.clone();
let toggle_state = state.clone();
let toggle_cb = open_change.clone();
let colors = cx.arc_theme().colors;
let tilt = arc_spring(
(self.id.clone(), "bell-tilt"),
if is_open && !arc_motion::is_reduced_motion(cx) {
N::BELL_TILT_DEG
} else {
0.0
},
motion.spring.snappy,
window,
cx,
);
let badge = ArcPresence::new((self.id.clone(), "badge"), unread > 0)
.animate_initial(false)
.sample(window, cx);
let mut trigger = BaseButton::new(child_id(&self.id, "trigger"))
.relative()
.flex_none()
.size(N::TRIGGER)
.rounded(N::TRIGGER_RADIUS)
.border_1()
.border_color(colors.border)
.bg(if is_open {
colors.surface_muted
} else {
colors.surface
})
.text_color(colors.foreground)
.flex()
.items_center()
.justify_center()
.hover(|s| {
s.bg(colors.surface_muted)
.border_color(colors.border_strong)
})
.child(
notification_icon(IconName::Bell, N::BELL, colors.foreground)
.with_transformation(Transformation::rotate(gpui_kit::Radians(
tilt.to_radians(),
)))
.id(child_id(&self.id, "bell"))
.test_support(),
)
.accessibility_label(if unread == 0 {
label.to_string()
} else {
format!("{label}, {unread} unread")
})
.track_focus(&trigger_focus)
.on_click(move |_, w, cx| {
let next = !is_open;
if controlled.is_none() {
toggle_state.update(cx, |s, _| s.open = next);
}
if let Some(cb) = &toggle_cb {
cb(next, w, cx)
}
w.refresh();
});
if badge.should_render() {
trigger = trigger.child(
div()
.id(child_id(&self.id, "badge"))
.test_support()
.absolute()
.top(N::BADGE_OFFSET)
.right(N::BADGE_OFFSET)
.min_w(N::BADGE)
.h(N::BADGE)
.px(Spacing::S1)
.border_2()
.border_color(colors.surface)
.rounded_full()
.bg(colors.foreground)
.text_color(colors.background)
.text_size(Typography::TEXT_XS)
.font_medium()
.flex()
.items_center()
.justify_center()
.opacity(badge.progress)
.child(rolling_count(
child_id(&self.id, "badge-roll"),
unread,
true,
window,
cx,
)),
);
}
let escape_close = close.clone();
let bounds_state = trigger_bounds.clone();
let mut root = div()
.id(self.id.clone())
.relative()
.flex_none()
.size(N::TRIGGER)
.track_focus(&panel_focus)
.on_prepaint(move |bounds, _, _| {
*bounds_state.borrow_mut() = Some(bounds);
})
.on_key_down(move |event: &KeyDownEvent, w, cx| {
if is_open && event.keystroke.key == "escape" {
escape_close(w, cx);
}
})
.child(
canvas(|_, _, _| {}, {
let trigger_bounds = trigger_bounds.clone();
let panel_bounds = panel_bounds.clone();
let close = close.clone();
move |_, _, window, _| {
if !is_open {
return;
}
let trigger_bounds = trigger_bounds.clone();
let panel_bounds = panel_bounds.clone();
let close = close.clone();
window.on_mouse_event(move |event: &MouseDownEvent, phase, w, cx| {
if !phase.bubble() {
return;
}
let inside_trigger = trigger_bounds
.borrow()
.is_some_and(|b| b.contains(&event.position));
let inside_panel = panel_bounds
.borrow()
.is_some_and(|b| b.contains(&event.position));
if !inside_trigger && !inside_panel {
close(w, cx);
}
});
}
})
.absolute()
.inset_0(),
)
.child(trigger);
if presence.should_render() {
let p = presence.progress.clamp(0.0, 1.0);
let lift = if arc_motion::is_reduced_motion(cx) {
0.0
} else {
-N::PANEL_TRAVEL * (1.0 - p)
};
let panel = render_panel(
&id,
&label,
&state,
PanelHandlers {
read: read.clone(),
dismiss: dismiss.clone(),
close: close.clone(),
},
window,
cx,
);
let viewport = window.viewport_size();
let (place_above, align_left) = {
let trigger_snapshot = trigger_bounds.borrow();
let panel_snapshot = panel_bounds.borrow();
let panel_estimate = panel_snapshot.map(|b| b.size).unwrap_or_else(|| {
size(
BlockTokens::NOTIFICATIONS_WIDTH,
BlockTokens::NOTIFICATIONS_HEIGHT,
)
});
trigger_snapshot
.map(|t| resolve_placement(t, panel_estimate, viewport, self.avoid_collisions))
.unwrap_or((false, false))
};
let trigger_rect = *trigger_bounds.borrow();
let anchor = match (place_above, align_left) {
(true, true) => Anchor::BottomLeft,
(true, false) => Anchor::BottomCenter,
(false, true) => Anchor::TopLeft,
(false, false) => Anchor::TopCenter,
};
let mut layer = anchored().anchor(anchor);
if let Some(t) = trigger_rect {
let x = if align_left {
t.origin.x
} else {
t.origin.x + t.size.width / 2.0
};
let y = if place_above {
t.origin.y - N::PANEL_GAP - px(lift)
} else {
t.origin.y + t.size.height + N::PANEL_GAP + px(lift)
};
layer = layer.position(point(x, y));
}
if self.avoid_collisions {
layer = layer.snap_to_window_with_margin(N::PANEL_GAP);
}
root =
root.child(deferred(layer.child(div().opacity(p).child(panel))).with_priority(1));
}
root
}
}
fn resolve_placement(
trigger: Bounds<Pixels>,
panel: Size<Pixels>,
viewport: Size<Pixels>,
avoid_collisions: bool,
) -> (bool, bool) {
if !avoid_collisions {
return (false, false);
}
let gap = 12.0f32;
let below = f32::from(viewport.height) - f32::from(trigger.origin.y + trigger.size.height);
let above = f32::from(trigger.origin.y);
let place_above = f32::from(panel.height) + gap > below && above > below;
let margin = f32::from(Spacing::S6);
let align_left =
f32::from(trigger.origin.x + trigger.size.width) < f32::from(panel.width) + margin;
(place_above, align_left)
}
fn close_panel(state: &Entity<State>, cb: Option<&OpenHandler>, w: &mut Window, cx: &mut App) {
state.update(cx, |s, _| s.open = false);
if let Some(cb) = cb {
cb(false, w, cx)
}
let handle = state.read(cx).trigger_focus.clone();
w.focus(&handle, cx);
w.refresh();
}
fn rolling_count(
id: ElementId,
value: usize,
capped: bool,
window: &mut Window,
cx: &mut App,
) -> gpui_kit::AnyElement {
let pitch = f32::from(Typography::TEXT_XS) * Typography::LEADING_BODY;
let position = arc_spring(
(id.clone(), "roll"),
value as f32 * pitch,
cx.arc_theme().motion.spring.snappy,
window,
cx,
);
let display = if capped && value > 9 {
"9+".to_owned()
} else {
value.to_string()
};
div()
.relative()
.overflow_hidden()
.h(px(pitch))
.min_w(Spacing::S2)
.child(
div()
.relative()
.top(px((value as f32 * pitch - position).clamp(-pitch, pitch)))
.text_size(Typography::TEXT_XS)
.child(display),
)
.into_any_element()
}
fn visual(item: &NotificationItem, id: &ElementId, cx: &App) -> gpui_kit::AnyElement {
if let Some(actor) = item.actor.as_ref() {
return Avatar::new(child_id(id, "avatar"), actor.name.clone())
.src(actor.photo.clone())
.into_any_element();
}
let colors = cx.arc_theme().colors;
let (glyph, color) = match item.tone {
NotificationTone::Warning => (IconName::TriangleAlert, colors.warning),
NotificationTone::Success => (IconName::CircleCheck, colors.success),
NotificationTone::Info => (IconName::MessageCircle, colors.accent),
};
div()
.flex_none()
.size(N::VISUAL)
.flex()
.items_center()
.justify_center()
.text_color(color)
.child(
notification_icon(glyph, N::EVENT_ICON, color)
.id(child_id(id, "event-icon"))
.test_support(),
)
.into_any_element()
}
fn render_panel(
id: &ElementId,
label: &SharedString,
state: &Entity<State>,
handlers: PanelHandlers,
window: &mut Window,
cx: &mut App,
) -> gpui_kit::AnyElement {
let PanelHandlers {
read,
dismiss,
close,
} = handlers;
let motion = cx.arc_theme().motion;
let colors = cx.arc_theme().colors;
let snap = state.read(cx).clone();
let unread = snap.items.iter().filter(|i| !i.read).count();
let read_count = snap.items.len() - unread;
let visible: Vec<_> = snap
.items
.iter()
.filter(|i| !snap.unread_only || !i.read)
.cloned()
.collect();
let visible_ids: Vec<SharedString> = visible.iter().map(|i| i.id.clone()).collect();
let ids: HashSet<_> = visible_ids.iter().cloned().collect();
let mut focus = snap.focus.clone();
for item in &snap.items {
focus
.entry(item.id.clone())
.or_insert_with(|| cx.focus_handle());
}
if focus.len() != snap.focus.len() {
let next = focus.clone();
state.update(cx, |s, _| s.focus = next);
}
let (all_tab, unread_tab) = (snap.tabs[0].clone(), snap.tabs[1].clone());
let mut retained = snap.retained;
for item in &snap.items {
if let Some(old) = retained.iter_mut().find(|i| i.id == item.id) {
*old = item.clone()
} else {
retained.push(item.clone())
}
}
let close_button = close.clone();
let panel_bounds = state.read(cx).panel_bounds.clone();
let summary = match unread {
0 => "You’re all caught up".to_owned(),
1 => "1 update waiting for you".to_owned(),
n => format!("{n} updates waiting for you"),
};
let narrow = f32::from(window.viewport_size().width) < N::NARROW;
let panel_height = BlockTokens::NOTIFICATIONS_HEIGHT
.min((window.viewport_size().height - N::PANEL_GAP * 2.0).max(px(0.0)));
let reserved_height = N::HEADER_TOP
+ N::HEADER_BOTTOM
+ Typography::TEXT_XL * 1.2
+ Spacing::S1
+ Typography::TEXT_XS * Typography::LEADING_BODY
+ N::TOOLBAR
+ if read_count > 0 { N::FOOTER } else { px(0.0) };
let mut root = div()
.flex()
.flex_col()
.min_w(px(0.0))
.rounded(N::PANEL_RADIUS)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.text_color(colors.foreground)
.text_size(Typography::TEXT_SM)
.shadow(Shadows::floating(cx.arc_theme().mode))
.id(child_id(id, "panel"))
.test_support()
.on_prepaint(move |bounds, _, _| {
*panel_bounds.borrow_mut() = Some(bounds);
})
.role(Role::Dialog)
.aria_label(label.clone())
.w(BlockTokens::NOTIFICATIONS_WIDTH)
.max_w(window.viewport_size().width - Spacing::S6)
.max_h(panel_height)
.child(
div()
.flex_none()
.flex()
.items_start()
.justify_between()
.gap(Spacing::S3)
.px(if narrow { Spacing::S4 } else { Spacing::S6 })
.pt(N::HEADER_TOP)
.pb(N::HEADER_BOTTOM)
.child(
div()
.min_w(px(0.0))
.flex_1()
.child(
div()
.flex()
.items_center()
.gap(Spacing::S2)
.child(
div()
.text_size(if narrow {
Typography::TEXT_LG
} else {
Typography::TEXT_XL
})
.font_medium()
.child(label.clone()),
)
.child(
div()
.id(child_id(id, "count"))
.test_support()
.min_w(N::COUNT)
.h(N::COUNT)
.px(Spacing::S1)
.rounded(N::COUNT_RADIUS)
.bg(colors.surface_muted)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.flex()
.items_center()
.justify_center()
.child(rolling_count(
child_id(id, "heading-roll"),
unread,
false,
window,
cx,
)),
),
)
.child(
div()
.id(child_id(id, "summary"))
.role(Role::Status)
.aria_label(summary.clone())
.mt(Spacing::S1)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child(summary),
),
)
.child(
BaseButton::new(child_id(id, "close"))
.accessibility_label("Close notifications")
.size(N::CLOSE)
.flex_none()
.rounded(Radii::CONTROL)
.flex()
.items_center()
.justify_center()
.text_color(colors.text_muted)
.hover(|s| s.bg(colors.surface_muted).text_color(colors.foreground))
.child(notification_icon(
IconName::Close,
Spacing::S4,
colors.text_muted,
))
.on_click(move |_, w, cx| close_button(w, cx)),
),
);
let mut toolbar = div()
.flex_none()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S3)
.min_h(N::TOOLBAR)
.px(if narrow { Spacing::S3 } else { Spacing::S5 })
.pb(N::TOOLBAR_BOTTOM)
.border_b_1()
.border_color(colors.border_subtle);
let tab_x = arc_spring(
(id.clone(), "view-highlight"),
if snap.unread_only {
f32::from(N::TAB_WIDTH + N::TAB_GAP)
} else {
0.0
},
motion.spring.morph,
window,
cx,
);
let mut switch = div().relative().flex().gap(N::TAB_GAP).child(
div()
.absolute()
.left(px(tab_x))
.top_0()
.w(N::TAB_WIDTH)
.h(N::TAB)
.rounded(N::TAB_RADIUS)
.bg(colors.surface_muted),
);
for (key, title, unread_only, handle) in [
("all", "All", false, all_tab.clone()),
("unread", "Unread", true, unread_tab.clone()),
] {
let state = state.clone();
switch = switch.child(
BaseButton::new(child_id(id, key))
.accessibility_label(title)
.relative()
.w(N::TAB_WIDTH)
.h(N::TAB)
.rounded(N::TAB_RADIUS)
.text_size(Typography::TEXT_XS)
.text_color(if snap.unread_only == unread_only {
colors.foreground
} else {
colors.text_secondary
})
.flex()
.items_center()
.justify_center()
.child(title)
.track_focus(&handle)
.on_click(move |_, w, cx| {
state.update(cx, |s, _| {
s.unread_only = unread_only;
s.expanded = None
});
w.refresh()
}),
);
}
toolbar = toolbar.child(switch);
if unread > 0 {
let state = state.clone();
let read = read.clone();
let focus_target = if snap.unread_only {
unread_tab.clone()
} else {
all_tab.clone()
};
toolbar = toolbar.child(
BaseButton::new(child_id(id, "mark-all"))
.accessibility_label("Mark all read")
.flex_none()
.flex()
.items_center()
.gap(N::DOT)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.py(N::DOT)
.child(notification_icon(
IconName::CheckCheck,
Spacing::S4,
colors.text_secondary,
))
.when(!narrow, |d| d.child("Mark all read"))
.on_click(move |_, w, cx| {
let changed = state
.read(cx)
.items
.iter()
.filter(|i| !i.read)
.cloned()
.collect::<Vec<_>>();
state.update(cx, |s, _| {
for i in &mut s.items {
i.read = true
}
s.expanded = None;
});
if let Some(cb) = &read {
for i in &changed {
cb(i, true, w, cx)
}
}
w.focus(&focus_target, cx);
w.refresh();
}),
);
}
root = root.child(toolbar);
let mut rows = div()
.id(child_id(id, "list"))
.test_support()
.role(Role::List)
.aria_label(if snap.unread_only {
"Unread notifications"
} else {
"All notifications"
})
.min_h(px(0.0))
.flex_shrink(1.0)
.max_h((panel_height - reserved_height).max(px(0.0)))
.px(if narrow { Spacing::S1 } else { N::LIST_X })
.pt(N::LIST_TOP)
.pb(N::ITEM_PAD)
.overflow_y_scroll();
let mut keep = vec![];
for item in retained {
let present = ids.contains(&item.id);
let presence = ArcPresence::new((child_id(id, item.id.clone()), "row"), present)
.animate_initial(false)
.sample(window, cx);
if !presence.should_render() {
continue;
}
keep.push(item.clone());
let expanded = present && snap.expanded.as_ref() == Some(&item.id);
let item_id = child_id(id, format!("item-{}", item.id));
let st = state.clone();
let key = item.id.clone();
let position = visible_ids.iter().position(|v| v == &item.id);
let neighbor = position
.and_then(|i| {
visible_ids
.get(i + 1)
.or_else(|| i.checked_sub(1).and_then(|p| visible_ids.get(p)))
})
.and_then(|next| focus.get(next))
.cloned();
let handle = focus.get(&item.id).cloned();
let mut toggle = BaseButton::new(child_id(&item_id, "toggle"))
.accessibility_label(format!(
"{}{}{}",
item.title,
if item.read { "" } else { ", unread" },
if expanded {
". Hide details"
} else {
". Show details"
}
))
.flex_1()
.min_w(px(0.0))
.flex()
.flex_col()
.gap(Spacing::S1)
.pt(px(2.0))
.text_color(colors.foreground)
.child(
div()
.w_full()
.flex()
.items_center()
.gap(N::DOT)
.child(
div()
.flex_1()
.min_w(px(0.0))
.truncate()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(if item.read {
colors.text_secondary
} else {
colors.foreground
})
.child(item.title.clone()),
)
.when(!item.read, |d| {
d.child(
div()
.flex_none()
.size(N::DOT)
.rounded_full()
.bg(colors.foreground),
)
}),
)
.child(
div()
.w_full()
.truncate()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child(item.preview()),
)
.disabled(!present)
.on_click(move |_, w, cx| {
st.update(cx, |s, _| {
s.expanded = if s.expanded.as_ref() == Some(&key) {
None
} else {
Some(key.clone())
}
});
w.refresh()
});
if let Some(handle) = &handle {
toggle = toggle.track_focus(handle);
}
let mut row = div()
.id(item_id.clone())
.test_support()
.role(Role::ListItem)
.overflow_hidden()
.opacity(presence.progress)
.rounded(N::ITEM_RADIUS)
.p(N::ITEM_PAD)
.flex_none()
.w_full()
.flex()
.flex_col()
.when(expanded, |d| d.bg(colors.surface_muted))
.hover(|s| s.bg(colors.surface_muted))
.child(
div()
.id(child_id(&item_id, "main"))
.test_support()
.w_full()
.min_w(px(0.0))
.flex()
.items_start()
.gap(N::VISUAL_GAP)
.child(visual(&item, &item_id, cx))
.child(toggle)
.child(
div()
.flex_none()
.pt(Spacing::S1)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(item.time.clone()),
),
);
let detail_h = arc_spring(
(item_id.clone(), "details-height"),
if expanded { 1.0 } else { 0.0 },
motion.spring.smooth,
window,
cx,
)
.clamp(0.0, 1.0);
if detail_h > 0.001 {
let st = state.clone();
let entry = item.clone();
let cb = read.clone();
let st_remove = state.clone();
let removed = item.clone();
let on_dismiss = dismiss.clone();
let after_read = neighbor.clone().unwrap_or_else(|| unread_tab.clone());
let after_remove = neighbor.clone().unwrap_or_else(|| unread_tab.clone());
let details = div()
.id(child_id(&item_id, "details"))
.test_support()
.w_full()
.pl(N::DETAILS_INDENT)
.overflow_hidden()
.opacity(detail_h)
.child(text(item.body(), cx).my(Spacing::S3))
.child(
div()
.flex()
.flex_wrap()
.gap(N::DOT)
.pb(Spacing::S1)
.child(
Button::new(child_id(&item_id, "read"))
.label(if item.read {
"Mark unread"
} else {
"Mark read"
})
.size(ButtonSize::Sm)
.variant(ButtonVariant::Secondary)
.icon(if item.read {
IconName::CircleDot
} else {
IconName::Check
})
.disabled(!present || !expanded)
.on_click(move |_, w, cx| {
st.update(cx, |s, _| {
if let Some(i) =
s.items.iter_mut().find(|i| i.id == entry.id)
{
i.read = !entry.read
}
if s.unread_only {
s.expanded = None
}
});
if let Some(cb) = &cb {
cb(&entry, !entry.read, w, cx)
}
if !entry.read {
w.focus(&after_read, cx);
}
w.refresh();
}),
)
.child(
Button::new(child_id(&item_id, "dismiss"))
.label("Dismiss")
.icon(IconName::Close)
.accessibility_label(format!("Dismiss {}", item.title))
.size(ButtonSize::Sm)
.variant(ButtonVariant::Secondary)
.disabled(!present || !expanded)
.on_click(move |_, w, cx| {
st_remove.update(cx, |s, _| {
s.items.retain(|i| i.id != removed.id);
s.expanded = None
});
if let Some(cb) = &on_dismiss {
cb(&removed, w, cx)
}
w.focus(&after_remove, cx);
w.refresh();
}),
),
);
row = row.child(MotionReveal::new(
child_id(&item_id, "details-reveal"),
detail_h,
details.into_any_element(),
));
}
rows = rows.child(MotionReveal::new(
child_id(&item_id, "reveal"),
presence.progress,
row.into_any_element(),
));
}
state.update(cx, |s, _| s.retained = keep);
if visible.is_empty() {
let st = state.clone();
rows = rows.child(
div()
.id(child_id(id, "empty"))
.test_support()
.flex()
.flex_col()
.items_center()
.gap(Spacing::S2)
.min_h(N::EMPTY)
.justify_center()
.p(Spacing::S6)
.child(notification_icon(
IconName::CircleCheck,
Spacing::S6,
colors.text_muted,
))
.child(div().text_size(Typography::TEXT_SM).font_medium().child(
if snap.unread_only {
"Nothing unread"
} else {
"All clear"
},
))
.child(
div()
.text_color(colors.text_muted)
.child(if snap.unread_only {
"You’ve seen every update."
} else {
"New updates will appear here."
}),
)
.when(snap.unread_only && !snap.items.is_empty(), |d| {
d.child(
Button::new(child_id(id, "view-all"))
.label("View all updates")
.size(ButtonSize::Sm)
.variant(ButtonVariant::Secondary)
.on_click(move |_, w, cx| {
st.update(cx, |s, _| s.unread_only = false);
w.refresh()
}),
)
}),
);
}
root = root.child(rows);
if read_count > 0 {
let st = state.clone();
let cb = dismiss;
let focus_target = all_tab;
root = root.child(
div()
.flex_none()
.min_h(N::FOOTER)
.px(N::FOOTER_X)
.py(Spacing::S2)
.border_t_1()
.border_color(colors.border_subtle)
.text_size(Typography::TEXT_XS)
.flex()
.justify_between()
.items_center()
.child(
div()
.flex()
.items_center()
.gap(Spacing::S1)
.text_color(colors.text_muted)
.child(rolling_count(
child_id(id, "read-roll"),
read_count,
false,
window,
cx,
))
.child("read"),
)
.child(
BaseButton::new(child_id(id, "clear-read"))
.accessibility_label("Clear read")
.py(Spacing::S1)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.hover(|s| s.text_color(colors.foreground))
.child("Clear read")
.on_click(move |_, w, cx| {
let removed = st
.read(cx)
.items
.iter()
.filter(|i| i.read)
.cloned()
.collect::<Vec<_>>();
st.update(cx, |s, _| {
s.items.retain(|i| !i.read);
s.expanded = None
});
if let Some(cb) = &cb {
for i in &removed {
cb(i, w, cx)
}
}
w.focus(&focus_target, cx);
w.refresh();
}),
),
);
}
root.into_any_element()
}
#[cfg(test)]
mod tests {
use super::*;
use gpui_kit::point;
fn bounds(x: f32, y: f32, w: f32, h: f32) -> Bounds<Pixels> {
Bounds {
origin: point(px(x), px(y)),
size: size(px(w), px(h)),
}
}
#[test]
fn svg_icons_have_explicit_theme_color_and_fixed_size() {
for mode in [arc_tokens::ThemeMode::Light, arc_tokens::ThemeMode::Dark] {
let colors = arc_tokens::ArcTheme::new(mode, arc_tokens::Accent::Violet).colors;
for (name, size, color) in [
(IconName::Bell, N::BELL, colors.foreground),
(IconName::MessageCircle, N::EVENT_ICON, colors.accent),
(IconName::TriangleAlert, N::EVENT_ICON, colors.warning),
(IconName::CircleCheck, N::EVENT_ICON, colors.success),
(IconName::Close, Spacing::S4, colors.text_muted),
(IconName::CheckCheck, Spacing::S4, colors.text_secondary),
] {
let mut icon = notification_icon(name, size, color);
let style = icon.style();
assert_eq!(style.text.color, Some(color));
assert!(color.a > 0.0);
assert_eq!(style.size.width, Some(size.into()));
assert_eq!(style.size.height, Some(size.into()));
}
}
}
#[test]
fn defaults_match_upstream() {
let i = NotificationItem::new("a", "Ready", "now");
assert!(!i.read);
assert_eq!(i.tone, NotificationTone::Info);
assert!(i.actor.is_none());
assert_eq!(i.preview(), "View update details");
assert_eq!(i.body(), "This update is ready to review.");
}
#[test]
fn actor_copy_matches_upstream() {
let i = NotificationItem::new("a", "Ready", "now").actor("Emma", "/emma.svg");
assert_eq!(i.preview(), "From Emma");
assert_eq!(i.body(), "Emma shared an update with you.");
let described = i.description("Full text");
assert_eq!(described.preview(), "Full text");
assert_eq!(described.body(), "Full text");
}
#[test]
fn placement_stays_below_right_when_space_is_enough() {
let trigger = bounds(400.0, 40.0, 120.0, 32.0);
let panel = size(px(424.0), px(300.0));
let viewport = size(px(1024.0), px(768.0));
assert_eq!(
resolve_placement(trigger, panel, viewport, true),
(false, false)
);
}
#[test]
fn placement_flips_above_when_bottom_space_is_tight() {
let trigger = bounds(400.0, 568.0, 120.0, 32.0);
let panel = size(px(424.0), px(300.0));
let viewport = size(px(1024.0), px(800.0));
assert_eq!(
resolve_placement(trigger, panel, viewport, true),
(true, false)
);
}
#[test]
fn placement_keeps_below_when_top_space_is_not_better() {
let trigger = bounds(400.0, 100.0, 120.0, 32.0);
let panel = size(px(424.0), px(300.0));
let viewport = size(px(1024.0), px(410.0));
assert_eq!(
resolve_placement(trigger, panel, viewport, true),
(false, false)
);
}
#[test]
fn placement_aligns_left_when_trigger_hugs_the_left_edge() {
let trigger = bounds(0.0, 40.0, 120.0, 32.0);
let panel = size(px(424.0), px(300.0));
let viewport = size(px(1024.0), px(768.0));
assert_eq!(
resolve_placement(trigger, panel, viewport, true),
(false, true)
);
}
#[test]
fn placement_respects_avoid_collisions_disabled() {
let trigger = bounds(400.0, 568.0, 120.0, 32.0);
let panel = size(px(424.0), px(300.0));
let viewport = size(px(1024.0), px(800.0));
assert_eq!(
resolve_placement(trigger, panel, viewport, false),
(false, false)
);
}
}