BlueGit

ict rusty-teams

Files

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

app_state.rs

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