BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 17.1 KiB Download Raw
1use std::collections::HashSet;
2use std::sync::Arc;
3use std::time::Instant;
4
5use chrono::{DateTime, Utc};
6use gpui_kit::*;
7use store::{ChatRecord, Sidebar, Store};
8use teams_core::{CoreEvent, ImageRef};
9
10use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
11use crate::data::{self, Directory};
12
13const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Selection {
17 Chat(String),
18 Channel(String),
19}
20
21impl Selection {
22 pub fn conversation_id(&self) -> &str {
23 match self {
24 Selection::Chat(id) | Selection::Channel(id) => id,
25 }
26 }
27}
28
29pub enum AppEvent {
30 Sidebar,
31 Selection,
32 Messages(String),
33 Images(Vec<String>),
34 Jump,
35 Status,
36 Directory,
37}
38
39#[derive(Debug, Clone, Copy, Default)]
40pub struct Mode {
41 pub demo: bool,
42 pub read_only: bool,
43 pub demo_sync: Option<std::time::Duration>,
44}
45
46pub struct AppState {
47 pub store: Arc<Store>,
48 pub engine: Option<Arc<Engine>>,
49 pub sidebar: Sidebar,
50 pub favorite_ids: Vec<String>,
51 pub selection: Option<Selection>,
52 pub new_chat: bool,
53 pub connection: ConnectionState,
54 pub live: LiveState,
55 pub last_sync: Option<DateTime<Utc>>,
56 pub mode: Mode,
57 pub directory: Directory,
58 pub collapsed: HashSet<String>,
59 pub start_on_channels: bool,
60 pub pending_jump: Option<(String, String)>,
61}
62
63impl EventEmitter<AppEvent> for AppState {}
64
65pub fn chat_title(chat: &ChatRecord) -> String {
66 if !chat.title.trim().is_empty() {
67 chat.title.clone()
68 } else if !chat.member_summary.trim().is_empty() {
69 chat.member_summary.clone()
70 } else {
71 "Chat".to_owned()
72 }
73}
74
75pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
76 match selection {
77 Selection::Chat(id) => sidebar
78 .chats
79 .iter()
80 .find(|chat| &chat.id == id)
81 .map(chat_title)
82 .unwrap_or_else(|| "Chat".to_owned()),
83 Selection::Channel(id) => sidebar
84 .teams
85 .iter()
86 .find_map(|team| {
87 team.channels
88 .iter()
89 .find(|channel| &channel.id == id)
90 .map(|channel| format!("{} / {}", team.team.name, channel.name))
91 })
92 .unwrap_or_else(|| "Channel".to_owned()),
93 }
94}
95
96impl AppState {
97 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
98 let sidebar = store.sidebar().unwrap_or_default();
99 let mut state = AppState {
100 store,
101 engine: None,
102 sidebar,
103 favorite_ids: Vec::new(),
104 selection: None,
105 new_chat: false,
106 connection: if mode.demo {
107 ConnectionState::Online
108 } else {
109 ConnectionState::Connecting
110 },
111 live: LiveState::Off,
112 last_sync: None,
113 mode,
114 directory: Directory::default(),
115 collapsed: HashSet::new(),
116 start_on_channels: false,
117 pending_jump: None,
118 };
119 state.collapsed = state.load_collapsed();
120 if !mode.demo {
121 state.directory.load_cached_presence(&state.store);
122 state.reload_directory();
123 }
124 state
125 }
126
127 fn load_collapsed(&self) -> HashSet<String> {
128 self.store
129 .meta(COLLAPSED_META_KEY)
130 .ok()
131 .flatten()
132 .map(|value| {
133 value
134 .lines()
135 .map(str::to_owned)
136 .filter(|id| !id.is_empty())
137 .collect()
138 })
139 .unwrap_or_default()
140 }
141
142 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
143 if !self.collapsed.remove(section_id) {
144 self.collapsed.insert(section_id.to_owned());
145 }
146 let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
147 ids.sort_unstable();
148 let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
149 cx.emit(AppEvent::Sidebar);
150 cx.notify();
151 }
152
153 pub fn reload_directory(&mut self) {
154 self.directory.me = data::me(&self.store);
155 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
156 self.directory.pinned_channels = data::pinned_channels(&self.store);
157 if self.directory.pinned_channels.is_empty() {
158 let known: HashSet<&str> = self
159 .sidebar
160 .teams
161 .iter()
162 .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str()))
163 .collect();
164 self.directory.pinned_channels = self
165 .favorite_ids
166 .iter()
167 .filter(|id| known.contains(id.as_str()))
168 .cloned()
169 .collect();
170 }
171 self.resolve_pending_avatars();
172 self.sync_presence();
173 self.directory.unread_counts = match &self.engine {
174 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
175 None => Default::default(),
176 };
177 }
178
179 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
180 let wanted = self.directory.missing_avatars(user_ids);
181 if wanted.is_empty() {
182 return;
183 }
184 let mut changed = false;
185 let mut uncached = Vec::new();
186 for user_id in wanted {
187 match data::cached_avatar(&self.store, &user_id) {
188 Some(cached) => {
189 self.directory.set_avatar(&user_id, cached);
190 changed = true;
191 }
192 None => uncached.push(user_id),
193 }
194 }
195 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
196 self.directory.mark_avatars_pending(&uncached);
197 let done = data::fetch_avatars(&engine, uncached);
198 self.on_done(done, cx, |state, cx| {
199 state.resolve_pending_avatars();
200 cx.emit(AppEvent::Directory);
201 cx.notify();
202 });
203 changed = true;
204 }
205 if changed {
206 cx.emit(AppEvent::Directory);
207 cx.notify();
208 }
209 }
210
211 pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) {
212 let Some(engine) = self.engine.clone() else {
213 return;
214 };
215 let wanted = self
216 .directory
217 .images_to_request(images.iter().map(|image| image.url.clone()));
218 let mut changed = false;
219 for image in images
220 .into_iter()
221 .filter(|image| wanted.contains(&image.url))
222 {
223 match engine.image_path(&image) {
224 Some(path) => {
225 self.directory.set_image(&image.url, &path);
226 changed = true;
227 }
228 None => {
229 let done = data::fetch_image(&engine, image);
230 self.on_done(done, cx, |_, _| {});
231 }
232 }
233 }
234 if changed {
235 cx.emit(AppEvent::Images(wanted));
236 cx.notify();
237 }
238 }
239
240 pub fn jump_to_message(
241 &mut self,
242 selection: Selection,
243 message_id: String,
244 cx: &mut Context<Self>,
245 ) {
246 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
247 if self.selection.as_ref() == Some(&selection) {
248 cx.emit(AppEvent::Jump);
249 } else {
250 self.select(selection, cx);
251 }
252 }
253
254 fn on_done(
255 &self,
256 done: data::Done,
257 cx: &mut Context<Self>,
258 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
259 ) {
260 cx.spawn(async move |this, cx| {
261 let _ = done.await;
262 this.update(cx, |state, cx| then(state, cx)).ok();
263 })
264 .detach();
265 }
266
267 fn resolve_pending_avatars(&mut self) {
268 for user_id in self.directory.pending_avatars() {
269 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
270 self.directory.set_avatar(&user_id, cached);
271 }
272 }
273 }
274
275 fn sync_presence(&mut self) -> Vec<String> {
276 let Some(engine) = self.engine.clone() else {
277 return Vec::new();
278 };
279 self.directory
280 .requested_presence_ids()
281 .into_iter()
282 .filter(|user_id| {
283 data::presence_kind(&engine, user_id)
284 .is_some_and(|kind| self.directory.set_presence(user_id, kind))
285 })
286 .collect()
287 }
288
289 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
290 let now = Instant::now();
291 let pushed = self.live == LiveState::Live;
292 let wanted = self.directory.stale_presence(user_ids, now, pushed);
293 if wanted.is_empty() {
294 return;
295 }
296 self.directory.mark_presence_pending(&wanted);
297 if let Some(engine) = self.engine.clone() {
298 self.directory.mark_presence_requested(&wanted, now);
299 drop(data::watch_presence(&engine, wanted.clone()));
300 let done = data::refresh_presence(&engine, wanted.clone());
301 self.on_done(done, cx, move |state, cx| {
302 state.sync_presence();
303 state.directory.save_presence(&state.store, &wanted);
304 state.directory.settle_presence(&wanted);
305 cx.emit(AppEvent::Directory);
306 cx.notify();
307 });
308 }
309 }
310
311 pub fn move_chat(
312 &mut self,
313 conversation_id: &str,
314 folder_id: Option<&str>,
315 cx: &mut Context<Self>,
316 ) {
317 if self.mode.read_only {
318 return;
319 }
320 let previous_folder = self
321 .directory
322 .folder_of(conversation_id)
323 .map(|folder| folder.id.clone());
324 self.directory.assign(conversation_id, folder_id);
325 if let Some(engine) = self.engine.clone() {
326 let previous = previous_folder.clone();
327 let done = match (folder_id, previous.as_deref()) {
328 (Some(folder_id), _) => {
329 Some(data::move_to_folder(&engine, conversation_id, folder_id))
330 }
331 (None, Some(previous)) => {
332 Some(data::remove_from_folder(&engine, conversation_id, previous))
333 }
334 (None, None) => None,
335 };
336 if let Some(done) = done {
337 self.on_done(done, cx, |state, cx| {
338 state.reload_directory();
339 cx.emit(AppEvent::Sidebar);
340 cx.notify();
341 });
342 }
343 }
344 cx.emit(AppEvent::Sidebar);
345 cx.notify();
346 }
347
348 pub fn pin_chat(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
349 let favorites = self.directory.favorites().map(|folder| folder.id.clone());
350 self.move_chat(conversation_id, favorites.as_deref(), cx);
351 }
352
353 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
354 if self.mode.demo {
355 if let Some(chat) = self
356 .sidebar
357 .chats
358 .iter()
359 .find(|chat| chat.id == conversation_id)
360 {
361 let mut read = chat.clone();
362 read.unread = false;
363 let _ = self.store.upsert_chats(&[read]);
364 self.reload_sidebar(cx);
365 }
366 return;
367 }
368 if self.mode.read_only {
369 return;
370 }
371 if let Some(engine) = self.engine.clone() {
372 let _ = self
373 .store
374 .mark_chat_read(conversation_id, chrono::Utc::now());
375 self.reload_sidebar(cx);
376 let conversation_id = conversation_id.to_owned();
377 drop(crate::runtime::spawn(async move {
378 engine.mark_read(&conversation_id).await
379 }));
380 }
381 }
382
383 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
384 self.new_chat = true;
385 cx.emit(AppEvent::Selection);
386 cx.notify();
387 }
388
389 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
390 if !self.new_chat {
391 return;
392 }
393 self.new_chat = false;
394 cx.emit(AppEvent::Selection);
395 cx.notify();
396 }
397
398 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
399 let was_drafting = std::mem::take(&mut self.new_chat);
400 if !was_drafting && self.selection.as_ref() == Some(&selection) {
401 return;
402 }
403 self.selection = Some(selection);
404 cx.emit(AppEvent::Selection);
405 cx.notify();
406 }
407
408 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
409 if let Ok(sidebar) = self.store.sidebar() {
410 self.sidebar = sidebar;
411 }
412 if !self.mode.demo {
413 self.reload_directory();
414 }
415 cx.emit(AppEvent::Sidebar);
416 cx.notify();
417 }
418
419 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
420 match event {
421 BackendEvent::Connection(connection) => {
422 self.connection = connection;
423 cx.emit(AppEvent::Status);
424 }
425 BackendEvent::Engine(engine) => {
426 self.engine = Some(engine);
427 let waiting = self.directory.waiting_presence_ids();
428 self.request_presence(waiting, cx);
429 cx.emit(AppEvent::Status);
430 }
431 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),
432 BackendEvent::Core(
433 CoreEvent::MessagesChanged { conversation_id }
434 | CoreEvent::ReceiptsChanged { conversation_id },
435 ) => {
436 cx.emit(AppEvent::Messages(conversation_id));
437 }
438 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
439 if let Some(engine) = &self.engine {
440 for key in &keys {
441 let image = ImageRef {
442 id: String::new(),
443 url: key.clone(),
444 width: None,
445 height: None,
446 };
447 if let Some(path) = engine.image_path(&image) {
448 self.directory.set_image(key, &path);
449 }
450 }
451 }
452 cx.emit(AppEvent::Images(keys));
453 }
454 BackendEvent::Core(CoreEvent::PresenceChanged) => {
455 let changed = self.sync_presence();
456 self.directory.save_presence(&self.store, &changed);
457 cx.emit(AppEvent::Directory);
458 cx.notify();
459 }
460 BackendEvent::Core(_) => {
461 if !self.mode.demo {
462 self.reload_directory();
463 }
464 cx.emit(AppEvent::Directory);
465 }
466 BackendEvent::Live(live) => {
467 self.live = live;
468 cx.emit(AppEvent::Status);
469 }
470 BackendEvent::Favorites(ids) => {
471 self.favorite_ids = ids;
472 if !self.mode.demo {
473 self.reload_directory();
474 }
475 cx.emit(AppEvent::Sidebar);
476 }
477 BackendEvent::Synced(time) => {
478 self.last_sync = Some(time);
479 cx.emit(AppEvent::Status);
480 }
481 }
482 cx.notify();
483 }
484}
485
486#[cfg(test)]
487mod tests {
488 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
489
490 use super::{Selection, chat_title, selection_title};
491 use store::Sidebar;
492
493 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
494 ChatRecord {
495 id: id.into(),
496 kind: "group".into(),
497 title: title.into(),
498 member_summary: "Member".into(),
499 last_message_at: None,
500 last_read_at: None,
501 unread,
502 ..Default::default()
503 }
504 }
505
506 fn sidebar() -> Sidebar {
507 Sidebar {
508 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
509 teams: vec![SidebarTeam {
510 team: TeamRecord {
511 id: "t".into(),
512 name: "Team".into(),
513 },
514 channels: vec![ChannelRecord {
515 id: "ch".into(),
516 team_id: "t".into(),
517 name: "General".into(),
518 membership_type: None,
519 last_message_at: None,
520 unread: false,
521 }],
522 hidden: false,
523 hidden_channel_ids: Vec::new(),
524 }],
525 }
526 }
527
528 #[test]
529 fn empty_chat_title_falls_back_to_members() {
530 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
531 }
532
533 #[test]
534 fn selection_titles() {
535 assert_eq!(
536 selection_title(&sidebar(), &Selection::Channel("ch".into())),
537 "Team / General"
538 );
539 assert_eq!(
540 selection_title(&sidebar(), &Selection::Chat("c1".into())),
541 "First"
542 );
543 }
544}