BlueGit

ict rusty-teams

Files

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

app_state.rs

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