BlueGit

ict rusty-teams

Files

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

chat_actions.rs

chat_actions.rs 12.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 pub fn remove_chat_member(&mut self, chat_id: &str, user_id: &str, cx: &mut Context<Self>) {
210 let Some(chat) = self.chat_record(chat_id) else {
211 return;
212 };
213 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
214 return;
215 };
216 let mut without_member = chat.clone();
217 without_member
218 .members
219 .retain(|member| member.user_id.as_deref() != Some(user_id));
220 let _ = self
221 .store
222 .upsert_chats(std::slice::from_ref(&without_member));
223 self.reload_sidebar(cx);
224 let Some(engine) = engine_or_demo else {
225 return;
226 };
227 let (owned_chat_id, owned_user_id) = (chat_id.to_owned(), user_id.to_owned());
228 self.run_chat_action(
229 "Remove from chat",
230 async move {
231 engine
232 .remove_chat_member(&owned_chat_id, &owned_user_id)
233 .await
234 },
235 move |state, cx| state.restore_chat_locally(&chat, cx),
236 |_, _| {},
237 cx,
238 );
239 }
240
241 fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
242 self.sidebar
243 .chats
244 .iter()
245 .find(|chat| chat.id == chat_id)
246 .cloned()
247 }
248
249 /// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.
250 pub fn chat_action_engine(
251 &mut self,
252 cx: &mut Context<Self>,
253 ) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {
254 if self.mode.read_only {
255 self.raise_notice("Read-only mode: chat not changed".to_owned(), None, cx);
256 return None;
257 }
258 match self.engine.clone() {
259 Some(engine) => Some(Some(engine)),
260 None if self.mode.demo => Some(None),
261 None => None,
262 }
263 }
264
265 fn remove_chat_locally(&mut self, chat_id: &str, cx: &mut Context<Self>) {
266 let was_selected = self.selection == Some(Selection::Chat(chat_id.to_owned()));
267 let next = was_selected
268 .then(|| self.next_chat_after(chat_id))
269 .flatten();
270 let _ = self.store.remove_chats(&[chat_id.to_owned()]);
271 self.reload_sidebar(cx);
272 if was_selected {
273 self.leave_removed_selection(next, cx);
274 }
275 }
276
277 fn leave_removed_selection(&mut self, next: Option<String>, cx: &mut Context<Self>) {
278 match next {
279 Some(next_id) => self.select(Selection::Chat(next_id), cx),
280 None => {
281 self.selection = None;
282 self.keep_unread = None;
283 cx.emit(crate::app_state::AppEvent::Selection);
284 cx.notify();
285 }
286 }
287 }
288
289 pub fn reload_sidebar_after_sync(&mut self, cx: &mut Context<Self>) {
290 let selected = match &self.selection {
291 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
292 _ => None,
293 };
294 let is_listed =
295 |state: &Self, chat_id: &str| state.sidebar.chats.iter().any(|chat| chat.id == chat_id);
296 let was_listed = selected
297 .as_deref()
298 .is_some_and(|chat_id| is_listed(self, chat_id));
299 let next = selected
300 .as_deref()
301 .filter(|_| was_listed)
302 .and_then(|chat_id| self.next_chat_after(chat_id));
303 self.reload_sidebar(cx);
304 let removed = was_listed
305 && selected
306 .as_deref()
307 .is_some_and(|chat_id| !is_listed(self, chat_id));
308 if removed {
309 self.leave_removed_selection(next, cx);
310 }
311 }
312
313 fn restore_chat_locally(&mut self, chat: &ChatRecord, cx: &mut Context<Self>) {
314 let _ = self.store.upsert_chats(std::slice::from_ref(chat));
315 let _ = self.store.set_chat_muted(&chat.id, chat.muted);
316 self.reload_sidebar(cx);
317 }
318
319 fn next_chat_after(&self, chat_id: &str) -> Option<String> {
320 next_chat_id(&self.chat_sections(), chat_id)
321 }
322
323 pub fn adjacent_chat_id(&self, step: Step) -> Option<String> {
324 let current = match &self.selection {
325 Some(Selection::Chat(chat_id)) => Some(chat_id.as_str()),
326 _ => None,
327 };
328 step_id(&visible_chat_ids(&self.chat_sections()), current, step)
329 }
330
331 fn chat_sections(&self) -> Vec<Section> {
332 let input = SectionInput {
333 chats: &self.sidebar.chats,
334 directory: &self.directory,
335 collapsed: &self.collapsed,
336 expanded_lists: &self.expanded_lists,
337 typing: &self.typing,
338 now: Utc::now(),
339 offset: Local::now().offset().fix(),
340 };
341 build_sections(&input)
342 }
343
344 pub fn run_chat_action(
345 &mut self,
346 label: &'static str,
347 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
348 revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
349 on_success: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
350 cx: &mut Context<Self>,
351 ) {
352 let receiver = crate::runtime::spawn(call);
353 cx.spawn(async move |this, cx| {
354 let failure = match receiver.await {
355 Ok(Ok(())) => None,
356 Ok(Err(error)) => Some(short_error(&error)),
357 Err(_) => Some("cancelled".to_owned()),
358 };
359 this.update(cx, |state, cx| match failure {
360 None => on_success(state, cx),
361 Some(reason) => {
362 revert(state, cx);
363 state.raise_notice(format!("{label} failed: {reason}"), None, cx);
364 }
365 })
366 .ok();
367 })
368 .detach();
369 }
370}