Skip to main content

arc_ui/blocks/
notification_center.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: registry/components/notification-center/{notification-center.tsx,notification-center.module.css}.
3//! 浮层用 `deferred` 提升到独立绘制层(等价于 Portal 的分层),开合由 `ArcPresence` 控制,
4//! 因此关闭时面板整体淡出/上移,而不是立即消失。
5use super::{child_id, text};
6use crate::{Avatar, Button, ButtonSize, ButtonVariant};
7use arc_motion::{ArcPresence, ArcPresenceConfig, arc_spring};
8use arc_tokens::{
9    ActiveArcTheme as _, BlockTokens, NotificationTokens as N, Radii, Shadows, Spacing, Typography,
10};
11use gpui_kit::base::{ElementExt as _, StyledExt as _};
12use gpui_kit::{
13    Anchor, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, KeyDownEvent,
14    MouseDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Size, Styled,
15    TestSupportExt as _, Transformation, Window, anchored,
16    assets::IconName,
17    base::{Button as BaseButton, MotionReveal},
18    canvas, deferred, div, point,
19    prelude::*,
20    px, size, svg,
21};
22use std::{
23    cell::RefCell,
24    collections::{HashMap, HashSet},
25    rc::Rc,
26};
27
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub enum NotificationTone {
30    #[default]
31    Info,
32    Success,
33    Warning,
34}
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct NotificationActor {
37    pub name: SharedString,
38    pub photo: SharedString,
39}
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct NotificationItem {
42    pub id: SharedString,
43    pub title: SharedString,
44    pub description: Option<SharedString>,
45    pub time: SharedString,
46    pub read: bool,
47    pub tone: NotificationTone,
48    pub actor: Option<NotificationActor>,
49}
50impl NotificationItem {
51    pub fn new(
52        id: impl Into<SharedString>,
53        title: impl Into<SharedString>,
54        time: impl Into<SharedString>,
55    ) -> Self {
56        Self {
57            id: id.into(),
58            title: title.into(),
59            time: time.into(),
60            description: None,
61            read: false,
62            tone: NotificationTone::Info,
63            actor: None,
64        }
65    }
66    pub fn description(mut self, value: impl Into<SharedString>) -> Self {
67        self.description = Some(value.into());
68        self
69    }
70    pub fn read(mut self, value: bool) -> Self {
71        self.read = value;
72        self
73    }
74    pub fn tone(mut self, value: NotificationTone) -> Self {
75        self.tone = value;
76        self
77    }
78    pub fn actor(mut self, name: impl Into<SharedString>, photo: impl Into<SharedString>) -> Self {
79        self.actor = Some(NotificationActor {
80            name: name.into(),
81            photo: photo.into(),
82        });
83        self
84    }
85    /// 折叠时的摘要:上游优先描述,其次作者,最后是通用提示。
86    fn preview(&self) -> SharedString {
87        self.description
88            .clone()
89            .unwrap_or_else(|| match &self.actor {
90                Some(actor) => format!("From {}", actor.name).into(),
91                None => "View update details".into(),
92            })
93    }
94    /// 展开后的正文,比摘要更完整。
95    fn body(&self) -> SharedString {
96        self.description
97            .clone()
98            .unwrap_or_else(|| match &self.actor {
99                Some(actor) => format!("{} shared an update with you.", actor.name).into(),
100                None => "This update is ready to review.".into(),
101            })
102    }
103}
104#[derive(Clone)]
105struct State {
106    items: Vec<NotificationItem>,
107    unread_only: bool,
108    expanded: Option<SharedString>,
109    retained: Vec<NotificationItem>,
110    focus: HashMap<SharedString, FocusHandle>,
111    tabs: [FocusHandle; 2],
112    open: bool,
113    was_open: bool,
114    panel_focus: FocusHandle,
115    trigger_focus: FocusHandle,
116    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
117    panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
118}
119type ReadHandler = Rc<dyn Fn(&NotificationItem, bool, &mut Window, &mut App)>;
120type DismissHandler = Rc<dyn Fn(&NotificationItem, &mut Window, &mut App)>;
121type OpenHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
122type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
123#[derive(Clone)]
124struct PanelHandlers {
125    read: Option<ReadHandler>,
126    dismiss: Option<DismissHandler>,
127    close: CloseHandler,
128}
129#[derive(IntoElement)]
130pub struct NotificationCenter {
131    id: ElementId,
132    notifications: Vec<NotificationItem>,
133    label: SharedString,
134    open: Option<bool>,
135    on_read_change: Option<ReadHandler>,
136    on_dismiss: Option<DismissHandler>,
137    on_open_change: Option<OpenHandler>,
138    avoid_collisions: bool,
139}
140impl NotificationCenter {
141    pub fn new(id: impl Into<ElementId>) -> Self {
142        Self {
143            id: id.into(),
144            notifications: vec![],
145            label: "Notifications".into(),
146            open: None,
147            on_read_change: None,
148            on_dismiss: None,
149            on_open_change: None,
150            avoid_collisions: true,
151        }
152    }
153    pub fn notifications(mut self, items: impl IntoIterator<Item = NotificationItem>) -> Self {
154        self.notifications = items.into_iter().collect();
155        self
156    }
157    pub fn label(mut self, v: impl Into<SharedString>) -> Self {
158        self.label = v.into();
159        self
160    }
161    pub fn open(mut self, v: bool) -> Self {
162        self.open = Some(v);
163        self
164    }
165    /// 上游 `avoidCollisions`:开启时按视口空间自动翻转面板(下方放不下翻上方、
166    /// 靠近视口左缘时改左对齐);关闭则固定下方右对齐。
167    pub fn avoid_collisions(mut self, v: bool) -> Self {
168        self.avoid_collisions = v;
169        self
170    }
171    pub fn on_read_change(
172        mut self,
173        f: impl Fn(&NotificationItem, bool, &mut Window, &mut App) + 'static,
174    ) -> Self {
175        self.on_read_change = Some(Rc::new(f));
176        self
177    }
178    pub fn on_dismiss(
179        mut self,
180        f: impl Fn(&NotificationItem, &mut Window, &mut App) + 'static,
181    ) -> Self {
182        self.on_dismiss = Some(Rc::new(f));
183        self
184    }
185    pub fn on_open_change(mut self, f: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
186        self.on_open_change = Some(Rc::new(f));
187        self
188    }
189}
190/// GPUI 的原始 Svg 不解析父级 currentColor;必须把主题色写在图元本身。
191/// 通知中心所有独立 SVG 统一由此构造,避免按钮可点击却没有图标。
192fn notification_icon(name: IconName, size: Pixels, color: Hsla) -> gpui_kit::Svg {
193    svg()
194        .path(name.path())
195        .size(size)
196        .flex_none()
197        .text_color(color)
198}
199
200impl RenderOnce for NotificationCenter {
201    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
202        let initial = self.notifications;
203        // 与上游一致:notifications 是首次挂载的初值,后续读/删除由内部维护。
204        let state = window.use_keyed_state(child_id(&self.id, "state"), cx, |_, cx| State {
205            retained: initial.clone(),
206            items: initial,
207            unread_only: false,
208            expanded: None,
209            focus: HashMap::new(),
210            tabs: [cx.focus_handle(), cx.focus_handle()],
211            open: false,
212            was_open: false,
213            panel_focus: cx.focus_handle(),
214            trigger_focus: cx.focus_handle(),
215            trigger_bounds: Rc::new(RefCell::new(None)),
216            panel_bounds: Rc::new(RefCell::new(None)),
217        });
218        let unread = state.read(cx).items.iter().filter(|i| !i.read).count();
219        let label = self.label.clone();
220        let id = self.id.clone();
221        let read = self.on_read_change;
222        let dismiss = self.on_dismiss;
223        let open_change = self.on_open_change;
224        let controlled = self.open;
225        let is_open = controlled.unwrap_or(state.read(cx).open);
226        let motion = cx.arc_theme().motion;
227        // 关闭时面板继续留在 deferred 层,直到退场曲线结束。
228        let presence = ArcPresence::new((child_id(&self.id, "presence"), "panel"), is_open)
229            .animate_initial(false)
230            .config(ArcPresenceConfig {
231                enter_duration: motion.duration.standard,
232                exit_duration: motion.duration.instant,
233                enter_ease: motion.ease.enter,
234                exit_ease: motion.ease.standard,
235                fade_on_reduced_motion: true,
236            })
237            .sample(window, cx);
238        let close: CloseHandler = {
239            let st = state.clone();
240            let cb = open_change.clone();
241            Rc::new(move |w: &mut Window, cx: &mut App| {
242                close_panel(&st, cb.as_ref(), w, cx);
243            })
244        };
245        let was_open = state.read(cx).was_open;
246        if is_open && !was_open {
247            let handle = state.read(cx).panel_focus.clone();
248            window.focus(&handle, cx);
249            state.update(cx, |s, _| s.was_open = true);
250        } else if !is_open && was_open {
251            state.update(cx, |s, _| s.was_open = false);
252        }
253        let trigger_focus = state.read(cx).trigger_focus.clone();
254        let panel_focus = state.read(cx).panel_focus.clone();
255        let trigger_bounds = state.read(cx).trigger_bounds.clone();
256        let panel_bounds = state.read(cx).panel_bounds.clone();
257        let toggle_state = state.clone();
258        let toggle_cb = open_change.clone();
259        let colors = cx.arc_theme().colors;
260        let tilt = arc_spring(
261            (self.id.clone(), "bell-tilt"),
262            if is_open && !arc_motion::is_reduced_motion(cx) {
263                N::BELL_TILT_DEG
264            } else {
265                0.0
266            },
267            motion.spring.snappy,
268            window,
269            cx,
270        );
271        let badge = ArcPresence::new((self.id.clone(), "badge"), unread > 0)
272            .animate_initial(false)
273            .sample(window, cx);
274        let mut trigger = BaseButton::new(child_id(&self.id, "trigger"))
275            .relative()
276            .flex_none()
277            .size(N::TRIGGER)
278            .rounded(N::TRIGGER_RADIUS)
279            .border_1()
280            .border_color(colors.border)
281            .bg(if is_open {
282                colors.surface_muted
283            } else {
284                colors.surface
285            })
286            .text_color(colors.foreground)
287            .flex()
288            .items_center()
289            .justify_center()
290            .hover(|s| {
291                s.bg(colors.surface_muted)
292                    .border_color(colors.border_strong)
293            })
294            .child(
295                notification_icon(IconName::Bell, N::BELL, colors.foreground)
296                    .with_transformation(Transformation::rotate(gpui_kit::Radians(
297                        tilt.to_radians(),
298                    )))
299                    .id(child_id(&self.id, "bell"))
300                    .test_support(),
301            )
302            .accessibility_label(if unread == 0 {
303                label.to_string()
304            } else {
305                format!("{label}, {unread} unread")
306            })
307            .track_focus(&trigger_focus)
308            .on_click(move |_, w, cx| {
309                let next = !is_open;
310                if controlled.is_none() {
311                    toggle_state.update(cx, |s, _| s.open = next);
312                }
313                if let Some(cb) = &toggle_cb {
314                    cb(next, w, cx)
315                }
316                w.refresh();
317            });
318        if badge.should_render() {
319            trigger = trigger.child(
320                div()
321                    .id(child_id(&self.id, "badge"))
322                    .test_support()
323                    .absolute()
324                    .top(N::BADGE_OFFSET)
325                    .right(N::BADGE_OFFSET)
326                    .min_w(N::BADGE)
327                    .h(N::BADGE)
328                    .px(Spacing::S1)
329                    .border_2()
330                    .border_color(colors.surface)
331                    .rounded_full()
332                    .bg(colors.foreground)
333                    .text_color(colors.background)
334                    .text_size(Typography::TEXT_XS)
335                    .font_medium()
336                    .flex()
337                    .items_center()
338                    .justify_center()
339                    .opacity(badge.progress)
340                    .child(rolling_count(
341                        child_id(&self.id, "badge-roll"),
342                        unread,
343                        true,
344                        window,
345                        cx,
346                    )),
347            );
348        }
349        let escape_close = close.clone();
350        let bounds_state = trigger_bounds.clone();
351        let mut root = div()
352            .id(self.id.clone())
353            .relative()
354            .flex_none()
355            .size(N::TRIGGER)
356            .track_focus(&panel_focus)
357            .on_prepaint(move |bounds, _, _| {
358                *bounds_state.borrow_mut() = Some(bounds);
359            })
360            .on_key_down(move |event: &KeyDownEvent, w, cx| {
361                if is_open && event.keystroke.key == "escape" {
362                    escape_close(w, cx);
363                }
364            })
365            .child(
366                canvas(|_, _, _| {}, {
367                    let trigger_bounds = trigger_bounds.clone();
368                    let panel_bounds = panel_bounds.clone();
369                    let close = close.clone();
370                    move |_, _, window, _| {
371                        if !is_open {
372                            return;
373                        }
374                        let trigger_bounds = trigger_bounds.clone();
375                        let panel_bounds = panel_bounds.clone();
376                        let close = close.clone();
377                        window.on_mouse_event(move |event: &MouseDownEvent, phase, w, cx| {
378                            if !phase.bubble() {
379                                return;
380                            }
381                            let inside_trigger = trigger_bounds
382                                .borrow()
383                                .is_some_and(|b| b.contains(&event.position));
384                            let inside_panel = panel_bounds
385                                .borrow()
386                                .is_some_and(|b| b.contains(&event.position));
387                            if !inside_trigger && !inside_panel {
388                                close(w, cx);
389                            }
390                        });
391                    }
392                })
393                .absolute()
394                .inset_0(),
395            )
396            .child(trigger);
397        if presence.should_render() {
398            let p = presence.progress.clamp(0.0, 1.0);
399            let lift = if arc_motion::is_reduced_motion(cx) {
400                0.0
401            } else {
402                -N::PANEL_TRAVEL * (1.0 - p)
403            };
404            let panel = render_panel(
405                &id,
406                &label,
407                &state,
408                PanelHandlers {
409                    read: read.clone(),
410                    dismiss: dismiss.clone(),
411                    close: close.clone(),
412                },
413                window,
414                cx,
415            );
416            // Radix 式防碰撞:用上一帧记录的触发器/面板几何决定翻转;首帧用默认定位。
417            let viewport = window.viewport_size();
418            let (place_above, align_left) = {
419                let trigger_snapshot = trigger_bounds.borrow();
420                let panel_snapshot = panel_bounds.borrow();
421                let panel_estimate = panel_snapshot.map(|b| b.size).unwrap_or_else(|| {
422                    size(
423                        BlockTokens::NOTIFICATIONS_WIDTH,
424                        BlockTokens::NOTIFICATIONS_HEIGHT,
425                    )
426                });
427                trigger_snapshot
428                    .map(|t| resolve_placement(t, panel_estimate, viewport, self.avoid_collisions))
429                    .unwrap_or((false, false))
430            };
431            // 使用窗口坐标锚点,避免把 flex 拉宽的故事容器误当触发器;
432            // anchored 的窗口边缘吸附负责水平 shift,翻转仍由实测空间决定。
433            let trigger_rect = *trigger_bounds.borrow();
434            let anchor = match (place_above, align_left) {
435                (true, true) => Anchor::BottomLeft,
436                (true, false) => Anchor::BottomCenter,
437                (false, true) => Anchor::TopLeft,
438                (false, false) => Anchor::TopCenter,
439            };
440            let mut layer = anchored().anchor(anchor);
441            if let Some(t) = trigger_rect {
442                let x = if align_left {
443                    t.origin.x
444                } else {
445                    t.origin.x + t.size.width / 2.0
446                };
447                let y = if place_above {
448                    t.origin.y - N::PANEL_GAP - px(lift)
449                } else {
450                    t.origin.y + t.size.height + N::PANEL_GAP + px(lift)
451                };
452                layer = layer.position(point(x, y));
453            }
454            if self.avoid_collisions {
455                layer = layer.snap_to_window_with_margin(N::PANEL_GAP);
456            }
457            root =
458                root.child(deferred(layer.child(div().opacity(p).child(panel))).with_priority(1));
459        }
460        root
461    }
462}
463/// 与上游 Radix `avoidCollisions` 等价的纯决策函数:
464/// 返回 `(翻转到触发器上方, 改为左对齐)`。
465fn resolve_placement(
466    trigger: Bounds<Pixels>,
467    panel: Size<Pixels>,
468    viewport: Size<Pixels>,
469    avoid_collisions: bool,
470) -> (bool, bool) {
471    if !avoid_collisions {
472        return (false, false);
473    }
474    let gap = 12.0f32;
475    let below = f32::from(viewport.height) - f32::from(trigger.origin.y + trigger.size.height);
476    let above = f32::from(trigger.origin.y);
477    let place_above = f32::from(panel.height) + gap > below && above > below;
478    let margin = f32::from(Spacing::S6);
479    let align_left =
480        f32::from(trigger.origin.x + trigger.size.width) < f32::from(panel.width) + margin;
481    (place_above, align_left)
482}
483fn close_panel(state: &Entity<State>, cb: Option<&OpenHandler>, w: &mut Window, cx: &mut App) {
484    state.update(cx, |s, _| s.open = false);
485    if let Some(cb) = cb {
486        cb(false, w, cx)
487    }
488    let handle = state.read(cx).trigger_focus.clone();
489    w.focus(&handle, cx);
490    w.refresh();
491}
492/// 上游 RollingCount:按增减方向滚动整份计数,避免用字符补间产生中间假计数。
493fn rolling_count(
494    id: ElementId,
495    value: usize,
496    capped: bool,
497    window: &mut Window,
498    cx: &mut App,
499) -> gpui_kit::AnyElement {
500    let pitch = f32::from(Typography::TEXT_XS) * Typography::LEADING_BODY;
501    let position = arc_spring(
502        (id.clone(), "roll"),
503        value as f32 * pitch,
504        cx.arc_theme().motion.spring.snappy,
505        window,
506        cx,
507    );
508    let display = if capped && value > 9 {
509        "9+".to_owned()
510    } else {
511        value.to_string()
512    };
513    div()
514        .relative()
515        .overflow_hidden()
516        .h(px(pitch))
517        .min_w(Spacing::S2)
518        .child(
519            div()
520                .relative()
521                .top(px((value as f32 * pitch - position).clamp(-pitch, pitch)))
522                .text_size(Typography::TEXT_XS)
523                .child(display),
524        )
525        .into_any_element()
526}
527
528fn visual(item: &NotificationItem, id: &ElementId, cx: &App) -> gpui_kit::AnyElement {
529    if let Some(actor) = item.actor.as_ref() {
530        return Avatar::new(child_id(id, "avatar"), actor.name.clone())
531            .src(actor.photo.clone())
532            .into_any_element();
533    }
534    let colors = cx.arc_theme().colors;
535    let (glyph, color) = match item.tone {
536        NotificationTone::Warning => (IconName::TriangleAlert, colors.warning),
537        NotificationTone::Success => (IconName::CircleCheck, colors.success),
538        NotificationTone::Info => (IconName::MessageCircle, colors.accent),
539    };
540    div()
541        .flex_none()
542        .size(N::VISUAL)
543        .flex()
544        .items_center()
545        .justify_center()
546        .text_color(color)
547        .child(
548            notification_icon(glyph, N::EVENT_ICON, color)
549                .id(child_id(id, "event-icon"))
550                .test_support(),
551        )
552        .into_any_element()
553}
554fn render_panel(
555    id: &ElementId,
556    label: &SharedString,
557    state: &Entity<State>,
558    handlers: PanelHandlers,
559    window: &mut Window,
560    cx: &mut App,
561) -> gpui_kit::AnyElement {
562    let PanelHandlers {
563        read,
564        dismiss,
565        close,
566    } = handlers;
567    let motion = cx.arc_theme().motion;
568    let colors = cx.arc_theme().colors;
569    let snap = state.read(cx).clone();
570    let unread = snap.items.iter().filter(|i| !i.read).count();
571    let read_count = snap.items.len() - unread;
572    let visible: Vec<_> = snap
573        .items
574        .iter()
575        .filter(|i| !snap.unread_only || !i.read)
576        .cloned()
577        .collect();
578    let visible_ids: Vec<SharedString> = visible.iter().map(|i| i.id.clone()).collect();
579    let ids: HashSet<_> = visible_ids.iter().cloned().collect();
580    let mut focus = snap.focus.clone();
581    for item in &snap.items {
582        focus
583            .entry(item.id.clone())
584            .or_insert_with(|| cx.focus_handle());
585    }
586    if focus.len() != snap.focus.len() {
587        let next = focus.clone();
588        state.update(cx, |s, _| s.focus = next);
589    }
590    let (all_tab, unread_tab) = (snap.tabs[0].clone(), snap.tabs[1].clone());
591    let mut retained = snap.retained;
592    for item in &snap.items {
593        if let Some(old) = retained.iter_mut().find(|i| i.id == item.id) {
594            *old = item.clone()
595        } else {
596            retained.push(item.clone())
597        }
598    }
599    let close_button = close.clone();
600    let panel_bounds = state.read(cx).panel_bounds.clone();
601    let summary = match unread {
602        0 => "You’re all caught up".to_owned(),
603        1 => "1 update waiting for you".to_owned(),
604        n => format!("{n} updates waiting for you"),
605    };
606    let narrow = f32::from(window.viewport_size().width) < N::NARROW;
607    let panel_height = BlockTokens::NOTIFICATIONS_HEIGHT
608        .min((window.viewport_size().height - N::PANEL_GAP * 2.0).max(px(0.0)));
609    let reserved_height = N::HEADER_TOP
610        + N::HEADER_BOTTOM
611        + Typography::TEXT_XL * 1.2
612        + Spacing::S1
613        + Typography::TEXT_XS * Typography::LEADING_BODY
614        + N::TOOLBAR
615        + if read_count > 0 { N::FOOTER } else { px(0.0) };
616    let mut root = div()
617        .flex()
618        .flex_col()
619        .min_w(px(0.0))
620        .rounded(N::PANEL_RADIUS)
621        .border_1()
622        .border_color(colors.border)
623        .bg(colors.surface_raised)
624        .text_color(colors.foreground)
625        .text_size(Typography::TEXT_SM)
626        .shadow(Shadows::floating(cx.arc_theme().mode))
627        .id(child_id(id, "panel"))
628        .test_support()
629        .on_prepaint(move |bounds, _, _| {
630            *panel_bounds.borrow_mut() = Some(bounds);
631        })
632        .role(Role::Dialog)
633        .aria_label(label.clone())
634        .w(BlockTokens::NOTIFICATIONS_WIDTH)
635        .max_w(window.viewport_size().width - Spacing::S6)
636        .max_h(panel_height)
637        .child(
638            div()
639                .flex_none()
640                .flex()
641                .items_start()
642                .justify_between()
643                .gap(Spacing::S3)
644                .px(if narrow { Spacing::S4 } else { Spacing::S6 })
645                .pt(N::HEADER_TOP)
646                .pb(N::HEADER_BOTTOM)
647                .child(
648                    div()
649                        .min_w(px(0.0))
650                        .flex_1()
651                        .child(
652                            div()
653                                .flex()
654                                .items_center()
655                                .gap(Spacing::S2)
656                                .child(
657                                    div()
658                                        .text_size(if narrow {
659                                            Typography::TEXT_LG
660                                        } else {
661                                            Typography::TEXT_XL
662                                        })
663                                        .font_medium()
664                                        .child(label.clone()),
665                                )
666                                .child(
667                                    div()
668                                        .id(child_id(id, "count"))
669                                        .test_support()
670                                        .min_w(N::COUNT)
671                                        .h(N::COUNT)
672                                        .px(Spacing::S1)
673                                        .rounded(N::COUNT_RADIUS)
674                                        .bg(colors.surface_muted)
675                                        .text_size(Typography::TEXT_XS)
676                                        .text_color(colors.text_secondary)
677                                        .flex()
678                                        .items_center()
679                                        .justify_center()
680                                        .child(rolling_count(
681                                            child_id(id, "heading-roll"),
682                                            unread,
683                                            false,
684                                            window,
685                                            cx,
686                                        )),
687                                ),
688                        )
689                        .child(
690                            div()
691                                .id(child_id(id, "summary"))
692                                .role(Role::Status)
693                                .aria_label(summary.clone())
694                                .mt(Spacing::S1)
695                                .text_size(Typography::TEXT_XS)
696                                .text_color(colors.text_secondary)
697                                .child(summary),
698                        ),
699                )
700                .child(
701                    BaseButton::new(child_id(id, "close"))
702                        .accessibility_label("Close notifications")
703                        .size(N::CLOSE)
704                        .flex_none()
705                        .rounded(Radii::CONTROL)
706                        .flex()
707                        .items_center()
708                        .justify_center()
709                        .text_color(colors.text_muted)
710                        .hover(|s| s.bg(colors.surface_muted).text_color(colors.foreground))
711                        .child(notification_icon(
712                            IconName::Close,
713                            Spacing::S4,
714                            colors.text_muted,
715                        ))
716                        .on_click(move |_, w, cx| close_button(w, cx)),
717                ),
718        );
719    let mut toolbar = div()
720        .flex_none()
721        .flex()
722        .items_center()
723        .justify_between()
724        .gap(Spacing::S3)
725        .min_h(N::TOOLBAR)
726        .px(if narrow { Spacing::S3 } else { Spacing::S5 })
727        .pb(N::TOOLBAR_BOTTOM)
728        .border_b_1()
729        .border_color(colors.border_subtle);
730    let tab_x = arc_spring(
731        (id.clone(), "view-highlight"),
732        if snap.unread_only {
733            f32::from(N::TAB_WIDTH + N::TAB_GAP)
734        } else {
735            0.0
736        },
737        motion.spring.morph,
738        window,
739        cx,
740    );
741    let mut switch = div().relative().flex().gap(N::TAB_GAP).child(
742        div()
743            .absolute()
744            .left(px(tab_x))
745            .top_0()
746            .w(N::TAB_WIDTH)
747            .h(N::TAB)
748            .rounded(N::TAB_RADIUS)
749            .bg(colors.surface_muted),
750    );
751    for (key, title, unread_only, handle) in [
752        ("all", "All", false, all_tab.clone()),
753        ("unread", "Unread", true, unread_tab.clone()),
754    ] {
755        let state = state.clone();
756        switch = switch.child(
757            BaseButton::new(child_id(id, key))
758                .accessibility_label(title)
759                .relative()
760                .w(N::TAB_WIDTH)
761                .h(N::TAB)
762                .rounded(N::TAB_RADIUS)
763                .text_size(Typography::TEXT_XS)
764                .text_color(if snap.unread_only == unread_only {
765                    colors.foreground
766                } else {
767                    colors.text_secondary
768                })
769                .flex()
770                .items_center()
771                .justify_center()
772                .child(title)
773                .track_focus(&handle)
774                .on_click(move |_, w, cx| {
775                    state.update(cx, |s, _| {
776                        s.unread_only = unread_only;
777                        s.expanded = None
778                    });
779                    w.refresh()
780                }),
781        );
782    }
783    toolbar = toolbar.child(switch);
784    if unread > 0 {
785        let state = state.clone();
786        let read = read.clone();
787        let focus_target = if snap.unread_only {
788            unread_tab.clone()
789        } else {
790            all_tab.clone()
791        };
792        toolbar = toolbar.child(
793            BaseButton::new(child_id(id, "mark-all"))
794                .accessibility_label("Mark all read")
795                .flex_none()
796                .flex()
797                .items_center()
798                .gap(N::DOT)
799                .text_size(Typography::TEXT_XS)
800                .text_color(colors.text_secondary)
801                .py(N::DOT)
802                .child(notification_icon(
803                    IconName::CheckCheck,
804                    Spacing::S4,
805                    colors.text_secondary,
806                ))
807                .when(!narrow, |d| d.child("Mark all read"))
808                .on_click(move |_, w, cx| {
809                    let changed = state
810                        .read(cx)
811                        .items
812                        .iter()
813                        .filter(|i| !i.read)
814                        .cloned()
815                        .collect::<Vec<_>>();
816                    state.update(cx, |s, _| {
817                        for i in &mut s.items {
818                            i.read = true
819                        }
820                        s.expanded = None;
821                    });
822                    if let Some(cb) = &read {
823                        for i in &changed {
824                            cb(i, true, w, cx)
825                        }
826                    }
827                    w.focus(&focus_target, cx);
828                    w.refresh();
829                }),
830        );
831    }
832    root = root.child(toolbar);
833    let mut rows = div()
834        .id(child_id(id, "list"))
835        .test_support()
836        .role(Role::List)
837        .aria_label(if snap.unread_only {
838            "Unread notifications"
839        } else {
840            "All notifications"
841        })
842        .min_h(px(0.0))
843        .flex_shrink(1.0)
844        .max_h((panel_height - reserved_height).max(px(0.0)))
845        .px(if narrow { Spacing::S1 } else { N::LIST_X })
846        .pt(N::LIST_TOP)
847        .pb(N::ITEM_PAD)
848        .overflow_y_scroll();
849    let mut keep = vec![];
850    for item in retained {
851        let present = ids.contains(&item.id);
852        let presence = ArcPresence::new((child_id(id, item.id.clone()), "row"), present)
853            .animate_initial(false)
854            .sample(window, cx);
855        if !presence.should_render() {
856            continue;
857        }
858        keep.push(item.clone());
859        let expanded = present && snap.expanded.as_ref() == Some(&item.id);
860        let item_id = child_id(id, format!("item-{}", item.id));
861        let st = state.clone();
862        let key = item.id.clone();
863        let position = visible_ids.iter().position(|v| v == &item.id);
864        let neighbor = position
865            .and_then(|i| {
866                visible_ids
867                    .get(i + 1)
868                    .or_else(|| i.checked_sub(1).and_then(|p| visible_ids.get(p)))
869            })
870            .and_then(|next| focus.get(next))
871            .cloned();
872        let handle = focus.get(&item.id).cloned();
873        let mut toggle = BaseButton::new(child_id(&item_id, "toggle"))
874            .accessibility_label(format!(
875                "{}{}{}",
876                item.title,
877                if item.read { "" } else { ", unread" },
878                if expanded {
879                    ". Hide details"
880                } else {
881                    ". Show details"
882                }
883            ))
884            .flex_1()
885            .min_w(px(0.0))
886            .flex()
887            .flex_col()
888            .gap(Spacing::S1)
889            .pt(px(2.0))
890            .text_color(colors.foreground)
891            .child(
892                div()
893                    .w_full()
894                    .flex()
895                    .items_center()
896                    .gap(N::DOT)
897                    .child(
898                        div()
899                            .flex_1()
900                            .min_w(px(0.0))
901                            .truncate()
902                            .text_size(Typography::TEXT_SM)
903                            .font_medium()
904                            .text_color(if item.read {
905                                colors.text_secondary
906                            } else {
907                                colors.foreground
908                            })
909                            .child(item.title.clone()),
910                    )
911                    .when(!item.read, |d| {
912                        d.child(
913                            div()
914                                .flex_none()
915                                .size(N::DOT)
916                                .rounded_full()
917                                .bg(colors.foreground),
918                        )
919                    }),
920            )
921            .child(
922                div()
923                    .w_full()
924                    .truncate()
925                    .text_size(Typography::TEXT_XS)
926                    .text_color(colors.text_secondary)
927                    .child(item.preview()),
928            )
929            .disabled(!present)
930            .on_click(move |_, w, cx| {
931                st.update(cx, |s, _| {
932                    s.expanded = if s.expanded.as_ref() == Some(&key) {
933                        None
934                    } else {
935                        Some(key.clone())
936                    }
937                });
938                w.refresh()
939            });
940        if let Some(handle) = &handle {
941            toggle = toggle.track_focus(handle);
942        }
943        let mut row = div()
944            .id(item_id.clone())
945            .test_support()
946            .role(Role::ListItem)
947            .overflow_hidden()
948            .opacity(presence.progress)
949            .rounded(N::ITEM_RADIUS)
950            .p(N::ITEM_PAD)
951            .flex_none()
952            .w_full()
953            .flex()
954            .flex_col()
955            .when(expanded, |d| d.bg(colors.surface_muted))
956            .hover(|s| s.bg(colors.surface_muted))
957            .child(
958                div()
959                    .id(child_id(&item_id, "main"))
960                    .test_support()
961                    .w_full()
962                    .min_w(px(0.0))
963                    .flex()
964                    .items_start()
965                    .gap(N::VISUAL_GAP)
966                    .child(visual(&item, &item_id, cx))
967                    .child(toggle)
968                    .child(
969                        div()
970                            .flex_none()
971                            .pt(Spacing::S1)
972                            .text_size(Typography::TEXT_XS)
973                            .text_color(colors.text_muted)
974                            .child(item.time.clone()),
975                    ),
976            );
977        let detail_h = arc_spring(
978            (item_id.clone(), "details-height"),
979            if expanded { 1.0 } else { 0.0 },
980            motion.spring.smooth,
981            window,
982            cx,
983        )
984        .clamp(0.0, 1.0);
985        if detail_h > 0.001 {
986            let st = state.clone();
987            let entry = item.clone();
988            let cb = read.clone();
989            let st_remove = state.clone();
990            let removed = item.clone();
991            let on_dismiss = dismiss.clone();
992            let after_read = neighbor.clone().unwrap_or_else(|| unread_tab.clone());
993            let after_remove = neighbor.clone().unwrap_or_else(|| unread_tab.clone());
994            let details = div()
995                .id(child_id(&item_id, "details"))
996                .test_support()
997                .w_full()
998                .pl(N::DETAILS_INDENT)
999                .overflow_hidden()
1000                .opacity(detail_h)
1001                .child(text(item.body(), cx).my(Spacing::S3))
1002                .child(
1003                    div()
1004                        .flex()
1005                        .flex_wrap()
1006                        .gap(N::DOT)
1007                        .pb(Spacing::S1)
1008                        .child(
1009                            Button::new(child_id(&item_id, "read"))
1010                                .label(if item.read {
1011                                    "Mark unread"
1012                                } else {
1013                                    "Mark read"
1014                                })
1015                                .size(ButtonSize::Sm)
1016                                .variant(ButtonVariant::Secondary)
1017                                .icon(if item.read {
1018                                    IconName::CircleDot
1019                                } else {
1020                                    IconName::Check
1021                                })
1022                                .disabled(!present || !expanded)
1023                                .on_click(move |_, w, cx| {
1024                                    st.update(cx, |s, _| {
1025                                        if let Some(i) =
1026                                            s.items.iter_mut().find(|i| i.id == entry.id)
1027                                        {
1028                                            i.read = !entry.read
1029                                        }
1030                                        if s.unread_only {
1031                                            s.expanded = None
1032                                        }
1033                                    });
1034                                    if let Some(cb) = &cb {
1035                                        cb(&entry, !entry.read, w, cx)
1036                                    }
1037                                    // 仅取消未读时需要把焦点交给下一条,避免落回文档。
1038                                    if !entry.read {
1039                                        w.focus(&after_read, cx);
1040                                    }
1041                                    w.refresh();
1042                                }),
1043                        )
1044                        .child(
1045                            Button::new(child_id(&item_id, "dismiss"))
1046                                .label("Dismiss")
1047                                .icon(IconName::Close)
1048                                .accessibility_label(format!("Dismiss {}", item.title))
1049                                .size(ButtonSize::Sm)
1050                                .variant(ButtonVariant::Secondary)
1051                                .disabled(!present || !expanded)
1052                                .on_click(move |_, w, cx| {
1053                                    st_remove.update(cx, |s, _| {
1054                                        s.items.retain(|i| i.id != removed.id);
1055                                        s.expanded = None
1056                                    });
1057                                    if let Some(cb) = &on_dismiss {
1058                                        cb(&removed, w, cx)
1059                                    }
1060                                    w.focus(&after_remove, cx);
1061                                    w.refresh();
1062                                }),
1063                        ),
1064                );
1065            row = row.child(MotionReveal::new(
1066                child_id(&item_id, "details-reveal"),
1067                detail_h,
1068                details.into_any_element(),
1069            ));
1070        }
1071        rows = rows.child(MotionReveal::new(
1072            child_id(&item_id, "reveal"),
1073            presence.progress,
1074            row.into_any_element(),
1075        ));
1076    }
1077    state.update(cx, |s, _| s.retained = keep);
1078    if visible.is_empty() {
1079        let st = state.clone();
1080        rows = rows.child(
1081            div()
1082                .id(child_id(id, "empty"))
1083                .test_support()
1084                .flex()
1085                .flex_col()
1086                .items_center()
1087                .gap(Spacing::S2)
1088                .min_h(N::EMPTY)
1089                .justify_center()
1090                .p(Spacing::S6)
1091                .child(notification_icon(
1092                    IconName::CircleCheck,
1093                    Spacing::S6,
1094                    colors.text_muted,
1095                ))
1096                .child(div().text_size(Typography::TEXT_SM).font_medium().child(
1097                    if snap.unread_only {
1098                        "Nothing unread"
1099                    } else {
1100                        "All clear"
1101                    },
1102                ))
1103                .child(
1104                    div()
1105                        .text_color(colors.text_muted)
1106                        .child(if snap.unread_only {
1107                            "You’ve seen every update."
1108                        } else {
1109                            "New updates will appear here."
1110                        }),
1111                )
1112                .when(snap.unread_only && !snap.items.is_empty(), |d| {
1113                    d.child(
1114                        Button::new(child_id(id, "view-all"))
1115                            .label("View all updates")
1116                            .size(ButtonSize::Sm)
1117                            .variant(ButtonVariant::Secondary)
1118                            .on_click(move |_, w, cx| {
1119                                st.update(cx, |s, _| s.unread_only = false);
1120                                w.refresh()
1121                            }),
1122                    )
1123                }),
1124        );
1125    }
1126    root = root.child(rows);
1127    if read_count > 0 {
1128        let st = state.clone();
1129        let cb = dismiss;
1130        let focus_target = all_tab;
1131        root = root.child(
1132            div()
1133                .flex_none()
1134                .min_h(N::FOOTER)
1135                .px(N::FOOTER_X)
1136                .py(Spacing::S2)
1137                .border_t_1()
1138                .border_color(colors.border_subtle)
1139                .text_size(Typography::TEXT_XS)
1140                .flex()
1141                .justify_between()
1142                .items_center()
1143                .child(
1144                    div()
1145                        .flex()
1146                        .items_center()
1147                        .gap(Spacing::S1)
1148                        .text_color(colors.text_muted)
1149                        .child(rolling_count(
1150                            child_id(id, "read-roll"),
1151                            read_count,
1152                            false,
1153                            window,
1154                            cx,
1155                        ))
1156                        .child("read"),
1157                )
1158                .child(
1159                    BaseButton::new(child_id(id, "clear-read"))
1160                        .accessibility_label("Clear read")
1161                        .py(Spacing::S1)
1162                        .text_size(Typography::TEXT_XS)
1163                        .text_color(colors.text_secondary)
1164                        .hover(|s| s.text_color(colors.foreground))
1165                        .child("Clear read")
1166                        .on_click(move |_, w, cx| {
1167                            let removed = st
1168                                .read(cx)
1169                                .items
1170                                .iter()
1171                                .filter(|i| i.read)
1172                                .cloned()
1173                                .collect::<Vec<_>>();
1174                            st.update(cx, |s, _| {
1175                                s.items.retain(|i| !i.read);
1176                                s.expanded = None
1177                            });
1178                            if let Some(cb) = &cb {
1179                                for i in &removed {
1180                                    cb(i, w, cx)
1181                                }
1182                            }
1183                            w.focus(&focus_target, cx);
1184                            w.refresh();
1185                        }),
1186                ),
1187        );
1188    }
1189    root.into_any_element()
1190}
1191#[cfg(test)]
1192mod tests {
1193    use super::*;
1194    use gpui_kit::point;
1195
1196    fn bounds(x: f32, y: f32, w: f32, h: f32) -> Bounds<Pixels> {
1197        Bounds {
1198            origin: point(px(x), px(y)),
1199            size: size(px(w), px(h)),
1200        }
1201    }
1202    #[test]
1203    fn svg_icons_have_explicit_theme_color_and_fixed_size() {
1204        for mode in [arc_tokens::ThemeMode::Light, arc_tokens::ThemeMode::Dark] {
1205            let colors = arc_tokens::ArcTheme::new(mode, arc_tokens::Accent::Violet).colors;
1206            for (name, size, color) in [
1207                (IconName::Bell, N::BELL, colors.foreground),
1208                (IconName::MessageCircle, N::EVENT_ICON, colors.accent),
1209                (IconName::TriangleAlert, N::EVENT_ICON, colors.warning),
1210                (IconName::CircleCheck, N::EVENT_ICON, colors.success),
1211                (IconName::Close, Spacing::S4, colors.text_muted),
1212                (IconName::CheckCheck, Spacing::S4, colors.text_secondary),
1213            ] {
1214                let mut icon = notification_icon(name, size, color);
1215                let style = icon.style();
1216                // 原始 Svg::paint 直接读取此字段,不会回退到父级 text_style。
1217                assert_eq!(style.text.color, Some(color));
1218                assert!(color.a > 0.0);
1219                assert_eq!(style.size.width, Some(size.into()));
1220                assert_eq!(style.size.height, Some(size.into()));
1221            }
1222        }
1223    }
1224
1225    #[test]
1226    fn defaults_match_upstream() {
1227        let i = NotificationItem::new("a", "Ready", "now");
1228        assert!(!i.read);
1229        assert_eq!(i.tone, NotificationTone::Info);
1230        assert!(i.actor.is_none());
1231        assert_eq!(i.preview(), "View update details");
1232        assert_eq!(i.body(), "This update is ready to review.");
1233    }
1234    #[test]
1235    fn actor_copy_matches_upstream() {
1236        let i = NotificationItem::new("a", "Ready", "now").actor("Emma", "/emma.svg");
1237        assert_eq!(i.preview(), "From Emma");
1238        assert_eq!(i.body(), "Emma shared an update with you.");
1239        let described = i.description("Full text");
1240        assert_eq!(described.preview(), "Full text");
1241        assert_eq!(described.body(), "Full text");
1242    }
1243    #[test]
1244    fn placement_stays_below_right_when_space_is_enough() {
1245        let trigger = bounds(400.0, 40.0, 120.0, 32.0);
1246        let panel = size(px(424.0), px(300.0));
1247        let viewport = size(px(1024.0), px(768.0));
1248        assert_eq!(
1249            resolve_placement(trigger, panel, viewport, true),
1250            (false, false)
1251        );
1252    }
1253    #[test]
1254    fn placement_flips_above_when_bottom_space_is_tight() {
1255        // 下方仅剩 200px,面板 300px 放不下;上方 620px 更宽裕 → 翻到上方。
1256        let trigger = bounds(400.0, 568.0, 120.0, 32.0);
1257        let panel = size(px(424.0), px(300.0));
1258        let viewport = size(px(1024.0), px(800.0));
1259        assert_eq!(
1260            resolve_placement(trigger, panel, viewport, true),
1261            (true, false)
1262        );
1263    }
1264    #[test]
1265    fn placement_keeps_below_when_top_space_is_not_better() {
1266        // 下方放不下(278px < 312px),但上方 100px 并不更大,保持下方由 max_h 兜底。
1267        let trigger = bounds(400.0, 100.0, 120.0, 32.0);
1268        let panel = size(px(424.0), px(300.0));
1269        let viewport = size(px(1024.0), px(410.0));
1270        assert_eq!(
1271            resolve_placement(trigger, panel, viewport, true),
1272            (false, false)
1273        );
1274    }
1275    #[test]
1276    fn placement_aligns_left_when_trigger_hugs_the_left_edge() {
1277        let trigger = bounds(0.0, 40.0, 120.0, 32.0);
1278        let panel = size(px(424.0), px(300.0));
1279        let viewport = size(px(1024.0), px(768.0));
1280        assert_eq!(
1281            resolve_placement(trigger, panel, viewport, true),
1282            (false, true)
1283        );
1284    }
1285    #[test]
1286    fn placement_respects_avoid_collisions_disabled() {
1287        let trigger = bounds(400.0, 568.0, 120.0, 32.0);
1288        let panel = size(px(424.0), px(300.0));
1289        let viewport = size(px(1024.0), px(800.0));
1290        assert_eq!(
1291            resolve_placement(trigger, panel, viewport, false),
1292            (false, false)
1293        );
1294    }
1295}