BlueGit

ict rusty-teams

Files

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

app_state.rs

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