BlueGit

ict rusty-teams

Files

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

app_state.rs

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