BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 33.5 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3use std::time::Instant;
4
5use chatsvc::TypingEvent;
6use chrono::{DateTime, Utc};
7use gpui_kit::*;
8use store::{ChatRecord, Sidebar, Store};
9use teams_core::{
10 ChatApp, ChatSection, ChatSectionSettings, CoreEvent, ImageRef, PinnedMessage, PresenceStatus,
11 ScheduledDraft,
12};
13
14use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16use calling::meeting::LiveMeeting;
17use crate::card_state::{CardState, TaskDialogState};
18use crate::data::{self, Directory};
19use crate::image_view_gallery::ViewerRequest;
20use crate::local_previews::{LocalPreview, load_local_previews};
21use crate::message_actions::{ForwardSource, SavedSet};
22use crate::notice::Notice;
23use crate::profile_state::{ProfileCache, ProfileRequest};
24use crate::translation::TranslationState;
25use crate::typing::TypingState;
26
27const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
28const RECENT_MESSAGES_FOR_TYPING: usize = 5;
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum Selection {
32 Chat(String),
33 Channel(String),
34}
35
36impl Selection {
37 pub fn conversation_id(&self) -> &str {
38 match self {
39 Selection::Chat(id) | Selection::Channel(id) => id,
40 }
41 }
42}
43
44pub enum AppEvent {
45 Sidebar,
46 Selection,
47 Messages(String),
48 Images(Vec<String>),
49 Jump,
50 Status,
51 Directory,
52 Cards(String),
53 TaskDialog,
54 Typing,
55 LocalPreviews,
56 Outbox(String),
57 Scheduled,
58 Pins(String),
59 Saved,
60 CallHistory,
61 Translation,
62 Forward,
63 ImageViewer,
64 StatusMessage,
65 NotificationSettings,
66 Profile,
67 Call,
68 Ring,
69 LiveMeeting,
70 MissedCall(MissedCall),
71}
72
73#[derive(Debug, Clone, Copy, Default)]
74pub struct Mode {
75 pub demo: bool,
76 pub read_only: bool,
77 pub demo_sync: Option<std::time::Duration>,
78}
79
80pub struct AppState {
81 pub store: Arc<Store>,
82 pub engine: Option<Arc<Engine>>,
83 pub sidebar: Sidebar,
84 pub favorite_ids: Vec<String>,
85 pub selection: Option<Selection>,
86 pub new_chat: bool,
87 pub connection: ConnectionState,
88 pub live: LiveState,
89 pub last_sync: Option<DateTime<Utc>>,
90 pub mode: Mode,
91 pub directory: Directory,
92 pub collapsed: HashSet<String>,
93 pub expanded_lists: HashSet<String>,
94 pub start_on_channels: bool,
95 pub pending_jump: Option<(String, String)>,
96 pub cards: CardState,
97 pub task_dialog: Option<TaskDialogState>,
98 pub bot_apps: HashMap<String, Vec<ChatApp>>,
99 pub bot_apps_pending: HashSet<String>,
100 pub notice: Option<Notice>,
101 pub notice_count: u64,
102 pub keep_unread: Option<String>,
103 pub typing: TypingState,
104 typing_timer_running: bool,
105 pub local_previews: HashMap<String, LocalPreview>,
106 pub scheduled: Vec<ScheduledDraft>,
107 pub scheduled_polling: bool,
108 pub saved: SavedSet,
109 pub call_history: Vec<teams_core::CallLogEntry>,
110 pub calendar_events: Vec<chatsvc::CalendarEvent>,
111 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
112 pub calls_list: crate::call::CallsList,
113 pub pins: HashMap<String, Vec<PinnedMessage>>,
114 pub forward_request: Option<ForwardSource>,
115 pub image_viewer_request: Option<ViewerRequest>,
116 pub own_status: PresenceStatus,
117 pub own_email: String,
118 pub status_menu_open: bool,
119 pub status_message_request: bool,
120 pub profiles: ProfileCache,
121 pub profile_request: Option<ProfileRequest>,
122 pub call: Option<ActiveCall>,
123 pub call_media: Option<Entity<CallMedia>>,
124 pub call_launcher: Option<Arc<CallLauncher>>,
125 pub call_count: u64,
126 pub call_share_sound: bool,
127 pub call_background: crate::call::BackgroundPick,
128 pub call_camera: calling::DeviceChoice,
129 pub meet_now_pending: bool,
130 pub call_backgrounds: crate::call::BackgroundLibrary,
131 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
132 pub rings: Rings,
133 pub live_meetings: HashMap<String, LiveMeeting>,
134 pub live_refreshing: HashSet<String>,
135 pub translation: TranslationState,
136}
137
138pub struct AppHandle(pub Entity<AppState>);
139
140impl Global for AppHandle {}
141
142impl EventEmitter<AppEvent> for AppState {}
143
144pub fn chat_title(chat: &ChatRecord) -> String {
145 if !chat.title.trim().is_empty() {
146 chat.title.clone()
147 } else if !chat.member_summary.trim().is_empty() {
148 chat.member_summary.clone()
149 } else {
150 "Chat".to_owned()
151 }
152}
153
154pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
155 match selection {
156 Selection::Chat(id) => sidebar
157 .chats
158 .iter()
159 .find(|chat| &chat.id == id)
160 .map(chat_title)
161 .unwrap_or_else(|| "Chat".to_owned()),
162 Selection::Channel(id) => sidebar
163 .teams
164 .iter()
165 .find_map(|team| {
166 team.channels
167 .iter()
168 .find(|channel| &channel.id == id)
169 .map(|channel| format!("{} / {}", team.team.name, channel.name))
170 })
171 .unwrap_or_else(|| "Channel".to_owned()),
172 }
173}
174
175impl AppState {
176 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
177 let sidebar = store.sidebar().unwrap_or_default();
178 let mut state = AppState {
179 store,
180 engine: None,
181 sidebar,
182 favorite_ids: Vec::new(),
183 selection: None,
184 new_chat: false,
185 connection: if mode.demo {
186 ConnectionState::Online
187 } else {
188 ConnectionState::Connecting
189 },
190 live: LiveState::Off,
191 last_sync: None,
192 mode,
193 directory: Directory::default(),
194 collapsed: HashSet::new(),
195 expanded_lists: HashSet::new(),
196 start_on_channels: false,
197 pending_jump: None,
198 cards: CardState::default(),
199 task_dialog: None,
200 bot_apps: HashMap::new(),
201 bot_apps_pending: HashSet::new(),
202 notice: None,
203 notice_count: 0,
204 keep_unread: None,
205 typing: TypingState::default(),
206 typing_timer_running: false,
207 local_previews: HashMap::new(),
208 scheduled: Vec::new(),
209 scheduled_polling: false,
210 saved: SavedSet::default(),
211 call_history: Vec::new(),
212 calendar_events: Vec::new(),
213 calendar_nudge: None,
214 calls_list: crate::call::CallsList::default(),
215 pins: HashMap::new(),
216 forward_request: None,
217 image_viewer_request: None,
218 own_status: PresenceStatus::default(),
219 own_email: String::new(),
220 status_menu_open: false,
221 status_message_request: false,
222 profiles: ProfileCache::new(),
223 profile_request: None,
224 call: None,
225 call_media: None,
226 call_launcher: None,
227 call_count: 0,
228 call_share_sound: false,
229 call_background: crate::call::BackgroundPick::None,
230 call_camera: calling::DeviceChoice::SystemDefault,
231 meet_now_pending: false,
232 call_backgrounds: if mode.demo {
233 crate::call::demo_library()
234 } else {
235 crate::call::BackgroundLibrary::new(crate::call::default_cache_directory())
236 },
237 transfer_picker: None,
238 rings: Rings::default(),
239 live_meetings: HashMap::new(),
240 live_refreshing: HashSet::new(),
241 translation: TranslationState::default(),
242 };
243 state.local_previews = load_local_previews(&state.store);
244 state.collapsed = state.load_collapsed();
245 state.call_share_sound = crate::call::load_share_sound(&state.store);
246 state.call_background = crate::call::load_background(&state.store);
247 state.call_camera = crate::call::load_camera(&state.store);
248 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
249 state.load_cached_translation_settings();
250 if !mode.demo {
251 state.directory.load_cached_presence(&state.store);
252 state.reload_directory();
253 }
254 state
255 }
256
257 fn load_collapsed(&self) -> HashSet<String> {
258 self.store
259 .meta(COLLAPSED_META_KEY)
260 .ok()
261 .flatten()
262 .map(|value| {
263 value
264 .lines()
265 .map(str::to_owned)
266 .filter(|id| !id.is_empty())
267 .collect()
268 })
269 .unwrap_or_default()
270 }
271
272 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
273 let now_collapsed = self.collapsed.insert(section_id.to_owned());
274 if !now_collapsed {
275 self.collapsed.remove(section_id);
276 }
277 self.save_collapsed();
278 self.sync_folder_expanded(section_id, !now_collapsed);
279 cx.emit(AppEvent::Sidebar);
280 cx.notify();
281 }
282
283 pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {
284 if !self.expanded_lists.remove(section_id) {
285 self.expanded_lists.insert(section_id.to_owned());
286 }
287 cx.emit(AppEvent::Sidebar);
288 cx.notify();
289 }
290
291 fn save_collapsed(&self) {
292 let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
293 ids.sort_unstable();
294 let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
295 }
296
297 fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) {
298 let Some(folder) = self
299 .directory
300 .folders
301 .iter_mut()
302 .find(|folder| folder.id == folder_id && folder.expanded.is_some())
303 else {
304 return;
305 };
306 folder.expanded = Some(expanded);
307 let _ = self.store.set_folder_expanded(folder_id, expanded);
308 if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) {
309 let folder_id = folder_id.to_owned();
310 drop(crate::runtime::spawn(async move {
311 engine.set_folder_expanded(&folder_id, expanded).await
312 }));
313 }
314 }
315
316 fn adopt_folder_expanded(&mut self) {
317 let snapshot = self.collapsed.clone();
318 for folder in &self.directory.folders {
319 match folder.expanded {
320 Some(true) => {
321 self.collapsed.remove(&folder.id);
322 }
323 Some(false) => {
324 self.collapsed.insert(folder.id.clone());
325 }
326 None => {}
327 }
328 }
329 if self.collapsed != snapshot {
330 self.save_collapsed();
331 }
332 }
333
334 pub fn set_chat_section(
335 &mut self,
336 section: ChatSection,
337 enabled: bool,
338 cx: &mut Context<Self>,
339 ) {
340 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
341 return;
342 };
343 let previous = self.directory.section_settings;
344 let mut updated = previous;
345 updated.set(section, enabled);
346 self.apply_section_settings(updated, cx);
347 let Some(engine) = engine_or_demo else {
348 return;
349 };
350 self.run_chat_action(
351 "Chat list setting",
352 async move { engine.set_section_enabled(section, enabled).await },
353 move |state, cx| state.apply_section_settings(previous, cx),
354 |_, _| {},
355 cx,
356 );
357 }
358
359 fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {
360 self.directory.section_settings = settings;
361 let _ = teams_core::store_section_settings(&self.store, &settings);
362 cx.emit(AppEvent::Sidebar);
363 cx.notify();
364 }
365
366 pub fn reload_directory(&mut self) {
367 self.directory.me = data::me(&self.store);
368 self.own_email = self
369 .store
370 .meta("me_email")
371 .ok()
372 .flatten()
373 .unwrap_or_default();
374 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
375 self.directory.section_settings = teams_core::stored_section_settings(&self.store);
376 self.adopt_folder_expanded();
377 self.directory.pinned_channels = data::pinned_channels(&self.store);
378 if self.directory.pinned_channels.is_empty() {
379 let known: HashSet<&str> = self
380 .sidebar
381 .teams
382 .iter()
383 .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str()))
384 .collect();
385 self.directory.pinned_channels = self
386 .favorite_ids
387 .iter()
388 .filter(|id| known.contains(id.as_str()))
389 .cloned()
390 .collect();
391 }
392 self.resolve_pending_avatars();
393 self.sync_presence();
394 self.directory.unread_counts = match &self.engine {
395 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
396 None => Default::default(),
397 };
398 }
399
400 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
401 let wanted = self.directory.missing_avatars(user_ids);
402 if wanted.is_empty() {
403 return;
404 }
405 let mut changed = false;
406 let mut uncached = Vec::new();
407 for user_id in wanted {
408 match data::cached_avatar(&self.store, &user_id) {
409 Some(cached) => {
410 self.directory.set_avatar(&user_id, cached);
411 changed = true;
412 }
413 None => uncached.push(user_id),
414 }
415 }
416 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
417 self.directory.mark_avatars_pending(&uncached);
418 let done = data::fetch_avatars(&engine, uncached);
419 self.on_done(done, cx, |state, cx| {
420 state.resolve_pending_avatars();
421 cx.emit(AppEvent::Directory);
422 cx.notify();
423 });
424 changed = true;
425 }
426 if changed {
427 cx.emit(AppEvent::Directory);
428 cx.notify();
429 }
430 }
431
432 pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) {
433 let Some(engine) = self.engine.clone() else {
434 return;
435 };
436 let wanted = self
437 .directory
438 .images_to_request(images.iter().map(|image| image.url.clone()));
439 let mut changed = false;
440 for image in images
441 .into_iter()
442 .filter(|image| wanted.contains(&image.url))
443 {
444 match engine.image_path(&image) {
445 Some(path) => {
446 self.directory.set_image(&image.url, &path);
447 changed = true;
448 }
449 None => {
450 let done = data::fetch_image(&engine, image);
451 self.on_done(done, cx, |_, _| {});
452 }
453 }
454 }
455 if changed {
456 cx.emit(AppEvent::Images(wanted));
457 cx.notify();
458 }
459 }
460
461 pub fn jump_to_message(
462 &mut self,
463 selection: Selection,
464 message_id: String,
465 cx: &mut Context<Self>,
466 ) {
467 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
468 if self.selection.as_ref() == Some(&selection) {
469 cx.emit(AppEvent::Jump);
470 } else {
471 self.select(selection, cx);
472 }
473 }
474
475 fn on_done(
476 &self,
477 done: data::Done,
478 cx: &mut Context<Self>,
479 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
480 ) {
481 cx.spawn(async move |this, cx| {
482 let _ = done.await;
483 this.update(cx, |state, cx| then(state, cx)).ok();
484 })
485 .detach();
486 }
487
488 fn resolve_pending_avatars(&mut self) {
489 for user_id in self.directory.pending_avatars() {
490 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
491 self.directory.set_avatar(&user_id, cached);
492 }
493 }
494 }
495
496 fn sync_presence(&mut self) -> Vec<String> {
497 let Some(engine) = self.engine.clone() else {
498 return Vec::new();
499 };
500 self.directory
501 .requested_presence_ids()
502 .into_iter()
503 .filter(|user_id| {
504 let Some(kind) = data::presence_kind(&engine, user_id) else {
505 return false;
506 };
507 let activity_changed = self
508 .directory
509 .set_activity(user_id, data::presence_activity(&engine, user_id));
510 self.directory.set_presence(user_id, kind) || activity_changed
511 })
512 .collect()
513 }
514
515 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
516 let now = Instant::now();
517 let pushed = self.live == LiveState::Live;
518 let wanted = self.directory.stale_presence(user_ids, now, pushed);
519 if wanted.is_empty() {
520 return;
521 }
522 self.directory.mark_presence_pending(&wanted);
523 if let Some(engine) = self.engine.clone() {
524 self.directory.mark_presence_requested(&wanted, now);
525 drop(data::watch_presence(&engine, wanted.clone()));
526 let done = data::refresh_presence(&engine, wanted.clone());
527 self.on_done(done, cx, move |state, cx| {
528 state.sync_presence();
529 state.directory.save_presence(&state.store, &wanted);
530 state.directory.settle_presence(&wanted);
531 cx.emit(AppEvent::Directory);
532 cx.notify();
533 });
534 }
535 }
536
537 pub fn move_chat(
538 &mut self,
539 conversation_id: &str,
540 folder_id: Option<&str>,
541 cx: &mut Context<Self>,
542 ) {
543 if self.mode.read_only {
544 return;
545 }
546 let previous_folder = self
547 .directory
548 .folder_of(conversation_id)
549 .map(|folder| folder.id.clone());
550 self.directory.assign(conversation_id, folder_id);
551 if let Some(engine) = self.engine.clone() {
552 let previous = previous_folder.clone();
553 let done = match (folder_id, previous.as_deref()) {
554 (Some(folder_id), _) => {
555 Some(data::move_to_folder(&engine, conversation_id, folder_id))
556 }
557 (None, Some(previous)) => {
558 Some(data::remove_from_folder(&engine, conversation_id, previous))
559 }
560 (None, None) => None,
561 };
562 if let Some(done) = done {
563 self.on_done(done, cx, |state, cx| {
564 state.reload_directory();
565 cx.emit(AppEvent::Sidebar);
566 cx.notify();
567 });
568 }
569 }
570 cx.emit(AppEvent::Sidebar);
571 cx.notify();
572 }
573
574 pub fn pin_chat(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
575 let favorites = self.directory.favorites().map(|folder| folder.id.clone());
576 self.move_chat(conversation_id, favorites.as_deref(), cx);
577 }
578
579 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
580 if self.keeps_unread(conversation_id) {
581 self.keep_unread = None;
582 }
583 if self.mode.demo {
584 if let Some(chat) = self
585 .sidebar
586 .chats
587 .iter()
588 .find(|chat| chat.id == conversation_id)
589 {
590 let mut read = chat.clone();
591 read.unread = false;
592 let _ = self.store.upsert_chats(&[read]);
593 self.reload_sidebar(cx);
594 }
595 return;
596 }
597 if self.mode.read_only {
598 return;
599 }
600 if let Some(engine) = self.engine.clone() {
601 let _ = self
602 .store
603 .mark_chat_read(conversation_id, chrono::Utc::now());
604 self.reload_sidebar(cx);
605 let conversation_id = conversation_id.to_owned();
606 drop(crate::runtime::spawn(async move {
607 engine.mark_read(&conversation_id).await
608 }));
609 }
610 }
611
612 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
613 self.new_chat = true;
614 self.show_call(false, cx);
615 cx.emit(AppEvent::Selection);
616 cx.notify();
617 }
618
619 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
620 if !self.new_chat {
621 return;
622 }
623 self.new_chat = false;
624 cx.emit(AppEvent::Selection);
625 cx.notify();
626 }
627
628 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
629 self.show_call(false, cx);
630 let was_drafting = std::mem::take(&mut self.new_chat);
631 if !was_drafting && self.selection.as_ref() == Some(&selection) {
632 return;
633 }
634 let conversation_id = selection.conversation_id().to_owned();
635 self.selection = Some(selection);
636 self.keep_unread = None;
637 cx.emit(AppEvent::Selection);
638 cx.notify();
639 self.refresh_live_meeting(&conversation_id, cx);
640 self.refresh_language_stamps(&conversation_id, cx);
641 }
642
643 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
644 let is_me = self
645 .directory
646 .me
647 .as_ref()
648 .is_some_and(|me| me.user_id == event.user_id);
649 if is_me {
650 return;
651 }
652 if event.active {
653 let display_name = match event.display_name.trim() {
654 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
655 .remove(&event.user_id)
656 .unwrap_or_default(),
657 _ => event.display_name.clone(),
658 };
659 self.typing.start(
660 &event.conversation_id,
661 &event.user_id,
662 &display_name,
663 Instant::now(),
664 event.received_at,
665 );
666 self.request_avatars(vec![event.user_id.clone()], cx);
667 self.schedule_typing_expiry(cx);
668 } else {
669 self.typing.clear(&event.conversation_id, &event.user_id);
670 }
671 cx.emit(AppEvent::Typing);
672 cx.notify();
673 }
674
675 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
676 if !self.typing.is_active(conversation_id) {
677 return;
678 }
679 let Ok(recent) = self
680 .store
681 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
682 else {
683 return;
684 };
685 let mut changed = false;
686 for message in recent {
687 if let Some(sender_id) = message.sender_id.as_deref() {
688 changed |= self
689 .typing
690 .message_from(conversation_id, sender_id, message.created_at);
691 }
692 }
693 if changed {
694 cx.emit(AppEvent::Typing);
695 cx.notify();
696 }
697 }
698
699 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
700 if self.typing_timer_running {
701 return;
702 }
703 self.typing_timer_running = true;
704 cx.spawn(async move |this, cx| {
705 loop {
706 let next = this.update(cx, |state, _| {
707 let next = state.typing.next_expiry();
708 state.typing_timer_running = next.is_some();
709 next
710 });
711 let Ok(Some(next)) = next else { return };
712 cx.background_executor()
713 .timer(next.saturating_duration_since(Instant::now()))
714 .await;
715 let alive = this.update(cx, |state, cx| {
716 if state.typing.expire(Instant::now()) {
717 cx.emit(AppEvent::Typing);
718 cx.notify();
719 }
720 });
721 if alive.is_err() {
722 return;
723 }
724 }
725 })
726 .detach();
727 }
728
729 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
730 if let Ok(sidebar) = self.store.sidebar() {
731 self.sidebar = sidebar;
732 self.apply_bot_titles();
733 }
734 self.calls_list.invalidate();
735 if !self.mode.demo {
736 self.reload_directory();
737 }
738 cx.emit(AppEvent::Sidebar);
739 cx.notify();
740 }
741
742 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
743 match event {
744 BackendEvent::Connection(connection) => {
745 self.connection = connection;
746 cx.emit(AppEvent::Status);
747 }
748 BackendEvent::Calls(launcher) => {
749 launcher.set_default_camera(self.call_camera.clone());
750 self.call_launcher = Some(launcher);
751 }
752 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
753 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
754 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
755 BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),
756 BackendEvent::Engine(engine) => {
757 self.engine = Some(engine);
758 self.resend_outbox(cx);
759 self.refresh_scheduled(cx);
760 self.refresh_translation_settings(cx);
761 let waiting = self.directory.waiting_presence_ids();
762 self.request_presence(waiting, cx);
763 self.refresh_own_status(cx);
764 cx.emit(AppEvent::Status);
765 }
766 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),
767 BackendEvent::Core(
768 CoreEvent::MessagesChanged { conversation_id }
769 | CoreEvent::ReceiptsChanged { conversation_id },
770 ) => {
771 self.clear_typists_who_sent(&conversation_id, cx);
772 self.refresh_language_stamps(&conversation_id, cx);
773 cx.emit(AppEvent::Messages(conversation_id));
774 }
775 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
776 self.refresh_pins(&conversation_id, cx);
777 }
778 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
779 if let Some(engine) = &self.engine {
780 for key in &keys {
781 let image = ImageRef {
782 id: String::new(),
783 url: key.clone(),
784 width: None,
785 height: None,
786 };
787 if let Some(path) = engine.image_path(&image) {
788 self.directory.set_image(key, &path);
789 }
790 }
791 }
792 cx.emit(AppEvent::Images(keys));
793 }
794 BackendEvent::Core(CoreEvent::PresenceChanged) => {
795 let changed = self.sync_presence();
796 self.directory.save_presence(&self.store, &changed);
797 cx.emit(AppEvent::Directory);
798 cx.notify();
799 }
800 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
801 self.apply_own_status(status, cx);
802 self.reload_directory();
803 }
804 BackendEvent::Core(_) => {
805 if !self.mode.demo {
806 self.reload_directory();
807 }
808 cx.emit(AppEvent::Directory);
809 }
810 BackendEvent::Typing(event) => self.apply_typing(event, cx),
811 BackendEvent::Live(live) => {
812 self.live = live;
813 cx.emit(AppEvent::Status);
814 }
815 BackendEvent::Favorites(ids) => {
816 self.favorite_ids = ids;
817 if !self.mode.demo {
818 self.reload_directory();
819 }
820 cx.emit(AppEvent::Sidebar);
821 }
822 BackendEvent::Synced(time) => {
823 if self.last_sync.is_none() {
824 self.refresh_saved(cx);
825 }
826 self.last_sync = Some(time);
827 cx.emit(AppEvent::Status);
828 }
829 }
830 cx.notify();
831 }
832}
833
834#[cfg(test)]
835mod tests {
836 use std::sync::Arc;
837
838 use chatsvc::TypingEvent;
839 use chrono::{Duration, Utc};
840 use gpui_kit::{AppContext as _, TestAppContext};
841 use store::{
842 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
843 };
844 use teams_core::CoreEvent;
845
846 use super::{AppState, Mode, Selection, chat_title, selection_title};
847 use crate::backend::BackendEvent;
848 use crate::data::Person;
849 use store::Sidebar;
850
851 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
852 ChatRecord {
853 id: id.into(),
854 kind: "group".into(),
855 title: title.into(),
856 member_summary: "Member".into(),
857 last_message_at: None,
858 last_read_at: None,
859 unread,
860 ..Default::default()
861 }
862 }
863
864 fn sidebar() -> Sidebar {
865 Sidebar {
866 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
867 teams: vec![SidebarTeam {
868 team: TeamRecord {
869 id: "t".into(),
870 name: "Team".into(),
871 },
872 channels: vec![ChannelRecord {
873 id: "ch".into(),
874 team_id: "t".into(),
875 name: "General".into(),
876 membership_type: None,
877 last_message_at: None,
878 unread: false,
879 }],
880 hidden: false,
881 hidden_channel_ids: Vec::new(),
882 notifications: Default::default(),
883 }],
884 }
885 }
886
887 #[test]
888 fn empty_chat_title_falls_back_to_members() {
889 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
890 }
891
892 #[test]
893 fn selection_titles() {
894 assert_eq!(
895 selection_title(&sidebar(), &Selection::Channel("ch".into())),
896 "Team / General"
897 );
898 assert_eq!(
899 selection_title(&sidebar(), &Selection::Chat("c1".into())),
900 "First"
901 );
902 }
903
904 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
905 BackendEvent::Typing(TypingEvent {
906 conversation_id: "c1".into(),
907 user_id: user_id.into(),
908 display_name: format!("Name {user_id}"),
909 active,
910 received_at: Utc::now(),
911 })
912 }
913
914 #[gpui_kit::test]
915 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
916 cx.update(gpui_kit::init);
917 let store = Arc::new(Store::open_in_memory().unwrap());
918 let app = cx.update(|cx| {
919 cx.new(|_| {
920 let mut state = AppState::new(store.clone(), Mode::default());
921 state.directory.me = Some(Person {
922 user_id: "me".into(),
923 display_name: "Me".into(),
924 });
925 state
926 })
927 });
928 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
929 cx.update(|cx| {
930 app.update(cx, |state, cx| {
931 state.apply(typing_event("me", true), cx);
932 state.apply(typing_event("ada", true), cx);
933 })
934 });
935 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
936
937 let message = MessageRecord {
938 conversation_id: "c1".into(),
939 message_id: "m1".into(),
940 sender_id: Some("ada".into()),
941 created_at: Utc::now() + Duration::seconds(1),
942 ..Default::default()
943 };
944 store.upsert_messages(&[message]).unwrap();
945 cx.update(|cx| {
946 app.update(cx, |state, cx| {
947 state.apply(
948 BackendEvent::Core(CoreEvent::MessagesChanged {
949 conversation_id: "c1".into(),
950 }),
951 cx,
952 )
953 })
954 });
955 assert!(names(cx).is_empty());
956
957 cx.update(|cx| {
958 app.update(cx, |state, cx| {
959 state.apply(typing_event("ada", true), cx);
960 state.apply(typing_event("ada", false), cx);
961 })
962 });
963 assert!(names(cx).is_empty());
964 }
965
966 #[gpui_kit::test]
967 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
968 cx.update(gpui_kit::init);
969 let store = Arc::new(Store::open_in_memory().unwrap());
970 let app = cx.update(|cx| {
971 cx.new(|_| {
972 let mut state = AppState::new(store.clone(), Mode::default());
973 let mut member_chat = chat("c1", "First", false);
974 member_chat.members = vec![MemberRecord {
975 user_id: Some("ada".into()),
976 display_name: "Ada Lovelace".into(),
977 }];
978 state.sidebar.chats = vec![member_chat];
979 state
980 })
981 });
982 cx.update(|cx| {
983 app.update(cx, |state, cx| {
984 state.apply(
985 BackendEvent::Typing(TypingEvent {
986 conversation_id: "c1".into(),
987 user_id: "ada".into(),
988 display_name: String::new(),
989 active: true,
990 received_at: Utc::now(),
991 }),
992 cx,
993 )
994 })
995 });
996 assert_eq!(
997 cx.update(|cx| app.read(cx).typing.names("c1")),
998 vec!["Ada Lovelace".to_owned()]
999 );
1000 }
1001}