BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / notice.rs

notice.rs

notice.rs 2.8 KiB Download Raw
1use std::rc::Rc;
2use std::time::Duration;
3
4use gpui_kit::*;
5
6use crate::app_state::AppState;
7
8const NOTICE_DURATION: Duration = Duration::from_secs(6);
9const MAX_REASON_CHARS: usize = 140;
10
11type NoticeCallback = Rc<dyn Fn(&mut AppState, &mut Context<AppState>)>;
12
13#[derive(Clone)]
14pub struct NoticeAction {
15 pub label: String,
16 pub run: NoticeCallback,
17}
18
19impl NoticeAction {
20 pub fn new(label: &str, run: impl Fn(&mut AppState, &mut Context<AppState>) + 'static) -> Self {
21 NoticeAction {
22 label: label.to_owned(),
23 run: Rc::new(run),
24 }
25 }
26}
27
28#[derive(Clone)]
29pub struct Notice {
30 pub id: u64,
31 pub text: String,
32 pub action: Option<NoticeAction>,
33}
34
35pub fn short_error(error: &dyn std::fmt::Display) -> String {
36 error.to_string().chars().take(MAX_REASON_CHARS).collect()
37}
38
39pub fn truncated(text: &str, limit: usize) -> String {
40 if text.chars().count() <= limit {
41 return text.to_owned();
42 }
43 let kept: String = text.chars().take(limit).collect();
44 format!("{}...", kept.trim_end())
45}
46
47impl AppState {
48 pub fn raise_notice(
49 &mut self,
50 text: String,
51 action: Option<NoticeAction>,
52 cx: &mut Context<Self>,
53 ) {
54 app_base::diagnostics::record(format!("notice: {text}"));
55 self.notice_count += 1;
56 let id = self.notice_count;
57 self.notice = Some(Notice { id, text, action });
58 cx.spawn(async move |this, cx| {
59 cx.background_executor().timer(NOTICE_DURATION).await;
60 this.update(cx, |state, cx| {
61 if state.notice.as_ref().is_some_and(|notice| notice.id == id) {
62 state.dismiss_notice(cx);
63 }
64 })
65 .ok();
66 })
67 .detach();
68 cx.emit(crate::app_state::AppEvent::Status);
69 cx.notify();
70 }
71
72 pub fn dismiss_notice(&mut self, cx: &mut Context<Self>) {
73 if self.notice.take().is_some() {
74 cx.emit(crate::app_state::AppEvent::Status);
75 cx.notify();
76 }
77 }
78
79 pub fn run_notice_action(&mut self, cx: &mut Context<Self>) {
80 let Some(notice) = self.notice.take() else {
81 return;
82 };
83 cx.emit(crate::app_state::AppEvent::Status);
84 cx.notify();
85 if let Some(action) = notice.action {
86 (action.run)(self, cx);
87 }
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use super::{short_error, truncated};
94
95 #[test]
96 fn short_titles_pass_through() {
97 assert_eq!(truncated("Planning", 40), "Planning");
98 }
99
100 #[test]
101 fn long_titles_are_cut_at_the_limit() {
102 let title = "x".repeat(60);
103 assert_eq!(truncated(&title, 40), format!("{}...", "x".repeat(40)));
104 }
105
106 #[test]
107 fn errors_are_capped() {
108 assert_eq!(short_error(&"y".repeat(500)).chars().count(), 140);
109 }
110}