BlueGit

ict rusty-teams

Files

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

app_state.rs

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