BlueGit

ict rusty-teams

Files

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

notice.rs

notice.rs 2.7 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 self.notice_count += 1;
55 let id = self.notice_count;
56 self.notice = Some(Notice { id, text, action });
57 cx.spawn(async move |this, cx| {
58 cx.background_executor().timer(NOTICE_DURATION).await;
59 this.update(cx, |state, cx| {
60 if state.notice.as_ref().is_some_and(|notice| notice.id == id) {
61 state.dismiss_notice(cx);
62 }
63 })
64 .ok();
65 })
66 .detach();
67 cx.emit(crate::app_state::AppEvent::Status);
68 cx.notify();
69 }
70
71 pub fn dismiss_notice(&mut self, cx: &mut Context<Self>) {
72 if self.notice.take().is_some() {
73 cx.emit(crate::app_state::AppEvent::Status);
74 cx.notify();
75 }
76 }
77
78 pub fn run_notice_action(&mut self, cx: &mut Context<Self>) {
79 let Some(notice) = self.notice.take() else {
80 return;
81 };
82 cx.emit(crate::app_state::AppEvent::Status);
83 cx.notify();
84 if let Some(action) = notice.action {
85 (action.run)(self, cx);
86 }
87 }
88}
89
90#[cfg(test)]
91mod tests {
92 use super::{short_error, truncated};
93
94 #[test]
95 fn short_titles_pass_through() {
96 assert_eq!(truncated("Planning", 40), "Planning");
97 }
98
99 #[test]
100 fn long_titles_are_cut_at_the_limit() {
101 let title = "x".repeat(60);
102 assert_eq!(truncated(&title, 40), format!("{}...", "x".repeat(40)));
103 }
104
105 #[test]
106 fn errors_are_capped() {
107 assert_eq!(short_error(&"y".repeat(500)).chars().count(), 140);
108 }
109}