BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / chat_actions.rs

chat_actions.rs

chat_actions.rs 10.0 KiB Download Raw
1use std::future::Future;
2
3use chrono::{DateTime, Duration, Local, Offset, Utc};
4use gpui_kit::*;
5use store::{ChannelNotifications, ChatRecord};
6
7use crate::app_state::{AppState, Selection, chat_title};
8use crate::notice::{NoticeAction, short_error, truncated};
9use crate::sidebar_model::{SectionInput, build_sections, next_chat_id};
10
11pub const TITLE_LIMIT: usize = 40;
12
13impl AppState {
14 pub fn keeps_unread(&self, chat_id: &str) -> bool {
15 self.keep_unread.as_deref() == Some(chat_id)
16 }
17
18 pub fn mark_chat_unread(&mut self, chat_id: &str, cx: &mut Context<Self>) {
19 self.mark_chat_unread_from(chat_id, None, cx);
20 }
21
22 pub fn mark_chat_unread_from(
23 &mut self,
24 chat_id: &str,
25 message_created_at: Option<DateTime<Utc>>,
26 cx: &mut Context<Self>,
27 ) {
28 let Some(chat) = self.chat_record(chat_id) else {
29 return;
30 };
31 let Some(last_message_at) = chat.last_message_at else {
32 return;
33 };
34 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
35 return;
36 };
37 let last_read_at =
38 message_created_at.unwrap_or(last_message_at) - Duration::milliseconds(1);
39 let _ = self.store.mark_chat_unread(chat_id, last_read_at);
40 if self.selection == Some(Selection::Chat(chat_id.to_owned())) {
41 self.keep_unread = Some(chat_id.to_owned());
42 }
43 self.reload_sidebar(cx);
44 let Some(engine) = engine_or_demo else {
45 return;
46 };
47 let owned_id = chat_id.to_owned();
48 let revert_id = owned_id.clone();
49 let restored_read_at = chat.last_read_at.unwrap_or(last_message_at);
50 self.run_chat_action(
51 "Mark as unread",
52 async move {
53 match message_created_at {
54 Some(created_at) => engine.mark_unread_from(&owned_id, created_at).await,
55 None => engine.mark_unread(&owned_id).await,
56 }
57 },
58 move |state, cx| {
59 let _ = state.store.mark_chat_read(&revert_id, restored_read_at);
60 if state.keep_unread.as_deref() == Some(revert_id.as_str()) {
61 state.keep_unread = None;
62 }
63 state.reload_sidebar(cx);
64 },
65 |_, _| {},
66 cx,
67 );
68 }
69
70 pub fn set_chat_muted(&mut self, chat_id: &str, muted: bool, cx: &mut Context<Self>) {
71 if self.chat_record(chat_id).is_none() {
72 return;
73 }
74 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
75 return;
76 };
77 let _ = self.store.set_chat_muted(chat_id, muted);
78 self.reload_sidebar(cx);
79 let Some(engine) = engine_or_demo else {
80 return;
81 };
82 let owned_id = chat_id.to_owned();
83 let revert_id = owned_id.clone();
84 self.run_chat_action(
85 if muted { "Mute" } else { "Unmute" },
86 async move { engine.set_chat_muted(&owned_id, muted).await },
87 move |state, cx| {
88 let _ = state.store.set_chat_muted(&revert_id, !muted);
89 state.reload_sidebar(cx);
90 },
91 |_, _| {},
92 cx,
93 );
94 }
95
96 pub fn set_channel_notifications(
97 &mut self,
98 channel_id: &str,
99 notifications: ChannelNotifications,
100 cx: &mut Context<Self>,
101 ) {
102 let Some(previous) = self.channel_notifications(channel_id) else {
103 return;
104 };
105 if previous == notifications {
106 return;
107 }
108 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
109 return;
110 };
111 let _ = self
112 .store
113 .set_channel_notifications(channel_id, notifications);
114 self.reload_sidebar(cx);
115 let Some(engine) = engine_or_demo else {
116 return;
117 };
118 let owned_id = channel_id.to_owned();
119 let revert_id = owned_id.clone();
120 self.run_chat_action(
121 "Change notifications",
122 async move {
123 engine
124 .set_channel_notifications(&owned_id, notifications)
125 .await
126 },
127 move |state, cx| {
128 let _ = state.store.set_channel_notifications(&revert_id, previous);
129 state.reload_sidebar(cx);
130 },
131 |_, _| {},
132 cx,
133 );
134 }
135
136 pub fn channel_notifications(&self, channel_id: &str) -> Option<ChannelNotifications> {
137 self.sidebar.teams.iter().find_map(|team| {
138 team.channels
139 .iter()
140 .any(|channel| channel.id == channel_id)
141 .then(|| team.channel_notifications(channel_id))
142 })
143 }
144
145 pub fn hide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
146 let Some(chat) = self.chat_record(chat_id) else {
147 return;
148 };
149 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
150 return;
151 };
152 self.remove_chat_locally(chat_id, cx);
153 let Some(engine) = engine_or_demo else {
154 return;
155 };
156 let owned_id = chat_id.to_owned();
157 let undo_id = owned_id.clone();
158 let text = format!("\"{}\" hidden", truncated(&chat_title(&chat), TITLE_LIMIT));
159 self.run_chat_action(
160 "Hide",
161 async move { engine.hide_chat(&owned_id).await },
162 move |state, cx| state.restore_chat_locally(&chat, cx),
163 move |state, cx| {
164 let undo =
165 NoticeAction::new("Undo", move |state, cx| state.unhide_chat(&undo_id, cx));
166 state.raise_notice(text, Some(undo), cx);
167 },
168 cx,
169 );
170 }
171
172 pub fn unhide_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
173 let Some(engine) = self.chat_action_engine(cx).flatten() else {
174 return;
175 };
176 let owned_id = chat_id.to_owned();
177 self.run_chat_action(
178 "Undo",
179 async move { engine.unhide_chat(&owned_id).await },
180 |_, _| {},
181 |_, _| {},
182 cx,
183 );
184 }
185
186 pub fn leave_chat(&mut self, chat_id: &str, cx: &mut Context<Self>) {
187 let Some(chat) = self.chat_record(chat_id) else {
188 return;
189 };
190 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
191 return;
192 };
193 self.remove_chat_locally(chat_id, cx);
194 let Some(engine) = engine_or_demo else {
195 return;
196 };
197 let owned_id = chat_id.to_owned();
198 self.run_chat_action(
199 "Leave chat",
200 async move { engine.leave_chat(&owned_id).await },
201 move |state, cx| state.restore_chat_locally(&chat, cx),
202 |_, _| {},
203 cx,
204 );
205 }
206
207 fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
208 self.sidebar
209 .chats
210 .iter()
211 .find(|chat| chat.id == chat_id)
212 .cloned()
213 }
214
215 /// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.
216 pub(crate) fn chat_action_engine(
217 &mut self,
218 cx: &mut Context<Self>,
219 ) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {
220 if self.mode.read_only {
221 self.raise_notice("Read-only mode: chat not changed".to_owned(), None, cx);
222 return None;
223 }
224 match self.engine.clone() {
225 Some(engine) => Some(Some(engine)),
226 None if self.mode.demo => Some(None),
227 None => None,
228 }
229 }
230
231 fn remove_chat_locally(&mut self, chat_id: &str, cx: &mut Context<Self>) {
232 let was_selected = self.selection == Some(Selection::Chat(chat_id.to_owned()));
233 let next = was_selected
234 .then(|| self.next_chat_after(chat_id))
235 .flatten();
236 let _ = self.store.remove_chats(&[chat_id.to_owned()]);
237 self.reload_sidebar(cx);
238 if was_selected {
239 match next {
240 Some(next_id) => self.select(Selection::Chat(next_id), cx),
241 None => {
242 self.selection = None;
243 self.keep_unread = None;
244 cx.emit(crate::app_state::AppEvent::Selection);
245 cx.notify();
246 }
247 }
248 }
249 }
250
251 fn restore_chat_locally(&mut self, chat: &ChatRecord, cx: &mut Context<Self>) {
252 let _ = self.store.upsert_chats(std::slice::from_ref(chat));
253 let _ = self.store.set_chat_muted(&chat.id, chat.muted);
254 self.reload_sidebar(cx);
255 }
256
257 fn next_chat_after(&self, chat_id: &str) -> Option<String> {
258 let input = SectionInput {
259 chats: &self.sidebar.chats,
260 directory: &self.directory,
261 collapsed: &self.collapsed,
262 expanded_lists: &self.expanded_lists,
263 typing: &self.typing,
264 now: Utc::now(),
265 offset: Local::now().offset().fix(),
266 };
267 next_chat_id(&build_sections(&input), chat_id)
268 }
269
270 pub(crate) fn run_chat_action(
271 &mut self,
272 label: &'static str,
273 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
274 revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
275 on_success: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
276 cx: &mut Context<Self>,
277 ) {
278 let receiver = crate::runtime::spawn(call);
279 cx.spawn(async move |this, cx| {
280 let failure = match receiver.await {
281 Ok(Ok(())) => None,
282 Ok(Err(error)) => Some(short_error(&error)),
283 Err(_) => Some("cancelled".to_owned()),
284 };
285 this.update(cx, |state, cx| match failure {
286 None => on_success(state, cx),
287 Some(reason) => {
288 revert(state, cx);
289 state.raise_notice(format!("{label} failed: {reason}"), None, cx);
290 }
291 })
292 .ok();
293 })
294 .detach();
295 }
296}