BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / notice_toast.rs

notice_toast.rs

notice_toast.rs 2.9 KiB Download Raw
1use gpui_kit::component::WindowExt as _;
2use gpui_kit::component::button::{Button, ButtonVariants as _};
3use gpui_kit::component::notification::Notification;
4use gpui_kit::*;
5
6use crate::app_state::AppState;
7use crate::notice::Notice;
8
9struct NoticeToast;
10struct UpdateFailedToast;
11
12/// Mirrors `AppState::notice` as a toast bottom right; the state keeps the 6 s lifetime.
13#[derive(Default)]
14pub struct NoticeToasts {
15 shown: Option<u64>,
16 update_failure: Option<String>,
17}
18
19fn toast_placement() -> Anchor {
20 Anchor::BottomRight
21}
22
23impl NoticeToasts {
24 pub fn sync(
25 &mut self,
26 app: &Entity<AppState>,
27 notice: Option<&Notice>,
28 window: &mut Window,
29 cx: &mut App,
30 ) {
31 let current = notice.map(|notice| notice.id);
32 if current == self.shown {
33 return;
34 }
35 if let Some(previous) = self.shown.take() {
36 window.defer(cx, move |window, cx| {
37 window.remove_notification1::<NoticeToast>(previous, cx)
38 });
39 }
40 let Some(notice) = notice else {
41 return;
42 };
43 self.shown = Some(notice.id);
44 let mut toast = Notification::new()
45 .id1::<NoticeToast>(notice.id)
46 .placement(toast_placement())
47 .message(notice.text.clone())
48 .autohide(false);
49 if let Some(action) = notice.action.as_ref() {
50 let label = SharedString::from(action.label.clone());
51 let app = app.clone();
52 toast = toast.action(move |_, _, _| {
53 let app = app.clone();
54 Button::new("notice-toast-action")
55 .primary()
56 .label(label.clone())
57 .on_click(move |_, _, cx| {
58 app.update(cx, |state, cx| state.run_notice_action(cx))
59 })
60 });
61 }
62 let dismiss = app.clone();
63 let notice_id = notice.id;
64 toast = toast.on_close(move |_, cx| {
65 dismiss.update(cx, |state, cx| {
66 if state
67 .notice
68 .as_ref()
69 .is_some_and(|notice| notice.id == notice_id)
70 {
71 state.dismiss_notice(cx);
72 }
73 })
74 });
75 window.defer(cx, move |window, cx| window.push_notification(toast, cx));
76 }
77
78 pub fn update_failed(&mut self, message: Option<&str>, window: &mut Window, cx: &mut App) {
79 if message == self.update_failure.as_deref() {
80 return;
81 }
82 self.update_failure = message.map(str::to_owned);
83 let Some(message) = message else {
84 return;
85 };
86 let toast = Notification::error(format!("Update failed: {message}"))
87 .id::<UpdateFailedToast>()
88 .placement(toast_placement());
89 window.defer(cx, move |window, cx| window.push_notification(toast, cx));
90 }
91}