BlueGit

ict rusty-teams

Files

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

chat_actions.rs

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