| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::Instant; |
| 4 | |
| 5 | use chatsvc::TypingEvent; |
| 6 | use chrono::{DateTime, Utc}; |
| 7 | use gpui_kit::*; |
| 8 | use store::{ChatRecord, Sidebar, Store}; |
| 9 | use teams_core::{ |
| 10 | ChatApp, ChatSection, ChatSectionSettings, CoreEvent, ImageRef, PinnedMessage, PresenceStatus, |
| 11 | ScheduledDraft, |
| 12 | }; |
| 13 | |
| 14 | use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState}; |
| 15 | use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings}; |
| 16 | use crate::card_state::{CardState, TaskDialogState}; |
| 17 | use crate::data::{self, Directory}; |
| 18 | use crate::forward_selection::ForwardSelection; |
| 19 | use crate::image_view_gallery::ViewerRequest; |
| 20 | use crate::local_previews::{LocalPreview, load_local_previews}; |
| 21 | use crate::message_actions::{ForwardSource, SavedSet}; |
| 22 | use crate::notice::Notice; |
| 23 | use crate::notify::LateArrivals; |
| 24 | use crate::profile_state::{ProfileCache, ProfileRequest}; |
| 25 | use crate::translation::TranslationState; |
| 26 | use crate::typing::TypingState; |
| 27 | use calling::meeting::LiveMeeting; |
| 28 | |
| 29 | const COLLAPSED_META_KEY: &str = "ui.collapsed_sections"; |
| 30 | const RECENT_MESSAGES_FOR_TYPING: usize = 5; |
| 31 | |
| 32 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 33 | pub enum Selection { |
| 34 | Chat(String), |
| 35 | Channel(String), |
| 36 | } |
| 37 | |
| 38 | impl Selection { |
| 39 | pub fn conversation_id(&self) -> &str { |
| 40 | match self { |
| 41 | Selection::Chat(id) | Selection::Channel(id) => id, |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | pub enum AppEvent { |
| 47 | Sidebar, |
| 48 | Activity, |
| 49 | Selection, |
| 50 | Messages(String), |
| 51 | Images(Vec<String>), |
| 52 | Jump, |
| 53 | Status, |
| 54 | Directory, |
| 55 | Cards(String), |
| 56 | TaskDialog, |
| 57 | Typing, |
| 58 | LocalPreviews, |
| 59 | Outbox(String), |
| 60 | Scheduled, |
| 61 | Pins(String), |
| 62 | Saved, |
| 63 | CallHistory, |
| 64 | Translation, |
| 65 | Forward, |
| 66 | ForwardSelection, |
| 67 | ImageViewer, |
| 68 | StatusMessage, |
| 69 | Settings(crate::settings_section::SettingsSection), |
| 70 | Profile, |
| 71 | Call, |
| 72 | Ring, |
| 73 | LiveMeeting, |
| 74 | MissedCall(MissedCall), |
| 75 | MeetingReminder, |
| 76 | MeetingChime, |
| 77 | CallTone(chatsvc::sounds::CallTone), |
| 78 | SoundSettings, |
| 79 | ChatSettings, |
| 80 | FollowedStatus { |
| 81 | user_id: String, |
| 82 | text: &'static str, |
| 83 | }, |
| 84 | } |
| 85 | |
| 86 | #[derive(Debug, Clone, Copy, Default)] |
| 87 | pub struct Mode { |
| 88 | pub demo: bool, |
| 89 | pub read_only: bool, |
| 90 | pub demo_sync: Option<std::time::Duration>, |
| 91 | } |
| 92 | |
| 93 | pub struct AppState { |
| 94 | pub store: Arc<Store>, |
| 95 | pub engine: Option<Arc<Engine>>, |
| 96 | pub sidebar: Sidebar, |
| 97 | pub favorite_ids: Vec<String>, |
| 98 | pub selection: Option<Selection>, |
| 99 | pub late_arrivals: LateArrivals, |
| 100 | pub acked_urgent: std::collections::HashSet<String>, |
| 101 | pub new_chat: bool, |
| 102 | pub new_chat_people: Vec<store::MemberRecord>, |
| 103 | pub connection: ConnectionState, |
| 104 | pub live: LiveState, |
| 105 | pub last_sync: Option<DateTime<Utc>>, |
| 106 | pub mode: Mode, |
| 107 | pub directory: Directory, |
| 108 | pub collapsed: HashSet<String>, |
| 109 | pub expanded_lists: HashSet<String>, |
| 110 | pub start_on_channels: bool, |
| 111 | pub pending_jump: Option<(String, String)>, |
| 112 | pub cards: CardState, |
| 113 | pub task_dialog: Option<TaskDialogState>, |
| 114 | pub bot_apps: HashMap<String, Vec<ChatApp>>, |
| 115 | pub bot_apps_pending: HashSet<String>, |
| 116 | pub notice: Option<Notice>, |
| 117 | pub connection_banner: crate::connection_banner::BannerTiming, |
| 118 | pub live_retry: Option<Arc<tokio::sync::Notify>>, |
| 119 | pub notice_count: u64, |
| 120 | pub followed_presence: Vec<crate::presence_follow::FollowedPerson>, |
| 121 | pub followed_changes: Vec<(String, &'static str)>, |
| 122 | pub keep_unread: Option<String>, |
| 123 | pub restorable_deletes: crate::restorable_deletes::RestorableDeletes, |
| 124 | pub typing: TypingState, |
| 125 | typing_timer_running: bool, |
| 126 | pub local_previews: HashMap<String, LocalPreview>, |
| 127 | pub scheduled: Vec<ScheduledDraft>, |
| 128 | pub scheduled_polling: bool, |
| 129 | pub saved: SavedSet, |
| 130 | pub call_history: Vec<teams_core::CallLogEntry>, |
| 131 | pub calendar_events: Vec<chatsvc::CalendarEvent>, |
| 132 | pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>, |
| 133 | pub calls_list: crate::call::CallsList, |
| 134 | pub pins: HashMap<String, Vec<PinnedMessage>>, |
| 135 | pub post_follows: crate::post_follow::PostFollows, |
| 136 | pub forward_request: Option<ForwardSource>, |
| 137 | pub forward_selection: Option<ForwardSelection>, |
| 138 | pub image_viewer_request: Option<ViewerRequest>, |
| 139 | pub own_status: PresenceStatus, |
| 140 | pub own_email: String, |
| 141 | pub own_time_zone: Option<String>, |
| 142 | pub own_time_zone_requested: bool, |
| 143 | pub status_menu_open: bool, |
| 144 | pub status_message_request: bool, |
| 145 | pub profiles: ProfileCache, |
| 146 | pub profile_request: Option<ProfileRequest>, |
| 147 | pub call: Option<ActiveCall>, |
| 148 | pub held_call: Option<ActiveCall>, |
| 149 | pub call_end: Option<crate::call::end_screen::CallEndScreen>, |
| 150 | pub call_media: Option<Entity<CallMedia>>, |
| 151 | pub call_launcher: Option<Arc<CallLauncher>>, |
| 152 | pub call_count: u64, |
| 153 | pub call_share_sound: bool, |
| 154 | pub recording_policy: teams_core::RecordingPolicy, |
| 155 | pub allow_priority_messages: bool, |
| 156 | pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>, |
| 157 | pub chat_settings: teams_core::ChatSettingsDocument, |
| 158 | pub markdown_mode: bool, |
| 159 | pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>, |
| 160 | pub own_tenant: Option<String>, |
| 161 | pub call_share_motion: bool, |
| 162 | pub call_share_standout: bool, |
| 163 | pub call_report_enabled: bool, |
| 164 | pub call_strip_width: f32, |
| 165 | pub call_view: crate::call::ViewSettings, |
| 166 | pub call_background: crate::call::BackgroundPick, |
| 167 | pub call_camera: calling::DeviceChoice, |
| 168 | pub call_input: calling::DeviceChoice, |
| 169 | pub call_output: calling::DeviceChoice, |
| 170 | pub call_mic: calling::MicSettings, |
| 171 | pub call_effects: calling::CameraEffects, |
| 172 | pub meet_now_pending: bool, |
| 173 | pub prejoin: Option<crate::call::PendingJoin>, |
| 174 | pub prejoin_count: u64, |
| 175 | pub join_options: crate::call::JoinOptions, |
| 176 | pub rsvp_send_response: bool, |
| 177 | pub meeting_toasts: crate::call::MeetingToasts, |
| 178 | pub demo_meetings: Vec<chatsvc::CalendarEvent>, |
| 179 | pub call_backgrounds: crate::call::BackgroundLibrary, |
| 180 | pub transfer_picker: Option<AnyView>, |
| 181 | pub transcript_panel: Option<AnyView>, |
| 182 | pub rings: Rings, |
| 183 | pub live_meetings: HashMap<String, LiveMeeting>, |
| 184 | pub live_refreshing: HashSet<String>, |
| 185 | pub translation: TranslationState, |
| 186 | pub section_changes: crate::section_actions::SectionChanges, |
| 187 | } |
| 188 | |
| 189 | pub struct AppHandle(pub Entity<AppState>); |
| 190 | |
| 191 | impl Global for AppHandle {} |
| 192 | |
| 193 | impl EventEmitter<AppEvent> for AppState {} |
| 194 | |
| 195 | pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selection> { |
| 196 | if sidebar.chats.iter().any(|chat| chat.id == conversation_id) { |
| 197 | return Some(Selection::Chat(conversation_id.to_owned())); |
| 198 | } |
| 199 | sidebar |
| 200 | .teams |
| 201 | .iter() |
| 202 | .flat_map(|team| team.channels.iter()) |
| 203 | .any(|channel| channel.id == conversation_id) |
| 204 | .then(|| Selection::Channel(conversation_id.to_owned())) |
| 205 | } |
| 206 | |
| 207 | pub fn chat_title(chat: &ChatRecord) -> String { |
| 208 | chat.display_title() |
| 209 | } |
| 210 | |
| 211 | pub fn composer_name(sidebar: &Sidebar, selection: &Selection) -> String { |
| 212 | let unnamed_group = match selection { |
| 213 | Selection::Chat(id) => sidebar.chats.iter().any(|chat| { |
| 214 | &chat.id == id |
| 215 | && chat.title.trim().is_empty() |
| 216 | && !chat.kind.eq_ignore_ascii_case("oneOnOne") |
| 217 | }), |
| 218 | Selection::Channel(_) => false, |
| 219 | }; |
| 220 | if unnamed_group { |
| 221 | String::new() |
| 222 | } else { |
| 223 | selection_title(sidebar, selection) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String { |
| 228 | match selection { |
| 229 | Selection::Chat(id) => sidebar |
| 230 | .chats |
| 231 | .iter() |
| 232 | .find(|chat| &chat.id == id) |
| 233 | .map(chat_title) |
| 234 | .unwrap_or_else(|| "Chat".to_owned()), |
| 235 | Selection::Channel(id) => sidebar |
| 236 | .teams |
| 237 | .iter() |
| 238 | .find_map(|team| { |
| 239 | team.channels |
| 240 | .iter() |
| 241 | .find(|channel| &channel.id == id) |
| 242 | .map(|channel| format!("{} / {}", team.team.name, channel.name)) |
| 243 | }) |
| 244 | .unwrap_or_else(|| "Channel".to_owned()), |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | impl AppState { |
| 249 | pub fn new(store: Arc<Store>, mode: Mode) -> Self { |
| 250 | let sidebar = store.sidebar().unwrap_or_default(); |
| 251 | let chat_settings = teams_core::stored_chat_settings(&store); |
| 252 | let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store); |
| 253 | let mut state = AppState { |
| 254 | store, |
| 255 | engine: None, |
| 256 | sidebar, |
| 257 | favorite_ids: Vec::new(), |
| 258 | selection: None, |
| 259 | late_arrivals: LateArrivals::default(), |
| 260 | acked_urgent: Default::default(), |
| 261 | new_chat: false, |
| 262 | new_chat_people: Vec::new(), |
| 263 | connection: if mode.demo { |
| 264 | ConnectionState::Online |
| 265 | } else { |
| 266 | ConnectionState::Connecting |
| 267 | }, |
| 268 | live: LiveState::Off, |
| 269 | last_sync: None, |
| 270 | mode, |
| 271 | directory: Directory::default(), |
| 272 | collapsed: HashSet::new(), |
| 273 | expanded_lists: HashSet::new(), |
| 274 | start_on_channels: false, |
| 275 | pending_jump: None, |
| 276 | cards: CardState::default(), |
| 277 | task_dialog: None, |
| 278 | bot_apps: HashMap::new(), |
| 279 | bot_apps_pending: HashSet::new(), |
| 280 | notice: None, |
| 281 | connection_banner: Default::default(), |
| 282 | live_retry: None, |
| 283 | notice_count: 0, |
| 284 | followed_presence: Vec::new(), |
| 285 | followed_changes: Vec::new(), |
| 286 | keep_unread: None, |
| 287 | restorable_deletes: Default::default(), |
| 288 | typing: TypingState::default(), |
| 289 | typing_timer_running: false, |
| 290 | local_previews: HashMap::new(), |
| 291 | scheduled: Vec::new(), |
| 292 | scheduled_polling: false, |
| 293 | saved: SavedSet::default(), |
| 294 | call_history: Vec::new(), |
| 295 | calendar_events: Vec::new(), |
| 296 | calendar_nudge: None, |
| 297 | calls_list: crate::call::CallsList::default(), |
| 298 | pins: HashMap::new(), |
| 299 | post_follows: Default::default(), |
| 300 | forward_request: None, |
| 301 | forward_selection: None, |
| 302 | image_viewer_request: None, |
| 303 | own_status: PresenceStatus::default(), |
| 304 | own_email: String::new(), |
| 305 | own_time_zone: None, |
| 306 | own_time_zone_requested: false, |
| 307 | status_menu_open: false, |
| 308 | status_message_request: false, |
| 309 | profiles: ProfileCache::new(), |
| 310 | profile_request: None, |
| 311 | call: None, |
| 312 | call_end: None, |
| 313 | held_call: None, |
| 314 | call_media: None, |
| 315 | call_launcher: None, |
| 316 | call_count: 0, |
| 317 | call_share_sound: false, |
| 318 | recording_policy: teams_core::RecordingPolicy::default(), |
| 319 | allow_priority_messages: true, |
| 320 | account_sounds: None, |
| 321 | chat_settings, |
| 322 | markdown_mode, |
| 323 | demo_chat_desktop: HashMap::new(), |
| 324 | own_tenant: None, |
| 325 | call_share_motion: false, |
| 326 | call_share_standout: false, |
| 327 | call_report_enabled: true, |
| 328 | call_strip_width: crate::call::STRIP_DEFAULT_WIDTH, |
| 329 | call_view: crate::call::ViewSettings::default(), |
| 330 | call_background: crate::call::BackgroundPick::None, |
| 331 | call_camera: calling::DeviceChoice::SystemDefault, |
| 332 | call_input: calling::DeviceChoice::SystemDefault, |
| 333 | call_output: calling::DeviceChoice::SystemDefault, |
| 334 | call_mic: calling::MicSettings::default(), |
| 335 | call_effects: calling::CameraEffects::default(), |
| 336 | meet_now_pending: false, |
| 337 | prejoin: None, |
| 338 | prejoin_count: 0, |
| 339 | join_options: crate::call::JoinOptions::default(), |
| 340 | rsvp_send_response: true, |
| 341 | meeting_toasts: crate::call::MeetingToasts::default(), |
| 342 | demo_meetings: Vec::new(), |
| 343 | call_backgrounds: if mode.demo { |
| 344 | crate::call::demo_library() |
| 345 | } else { |
| 346 | crate::call::BackgroundLibrary::new(crate::call::default_cache_directory()) |
| 347 | }, |
| 348 | transfer_picker: None, |
| 349 | transcript_panel: None, |
| 350 | rings: Rings::default(), |
| 351 | live_meetings: HashMap::new(), |
| 352 | live_refreshing: HashSet::new(), |
| 353 | translation: TranslationState::default(), |
| 354 | section_changes: crate::section_actions::SectionChanges::default(), |
| 355 | }; |
| 356 | state.local_previews = load_local_previews(&state.store); |
| 357 | state.followed_presence = crate::presence_follow::load_followed(&state.store); |
| 358 | state.collapsed = state.load_collapsed(); |
| 359 | state.call_share_sound = crate::call::load_share_sound(&state.store); |
| 360 | state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY); |
| 361 | state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY); |
| 362 | state.call_report_enabled = crate::call::load_report_enabled(&state.store); |
| 363 | state.call_strip_width = crate::call::load_strip_width(&state.store); |
| 364 | state.call_view = crate::call::ViewSettings::load(&state.store); |
| 365 | state.call_background = crate::call::load_background(&state.store); |
| 366 | state.call_camera = crate::call::load_camera(&state.store); |
| 367 | state.call_input = crate::call::load_input(&state.store); |
| 368 | state.call_output = crate::call::load_output(&state.store); |
| 369 | crate::call::apply_sound_output(&state.call_output); |
| 370 | state.call_mic = crate::call::load_mic(&state.store); |
| 371 | state.call_effects = crate::call::load_camera_effects(&state.store); |
| 372 | state.join_options = crate::call::load_join_options(&state.store); |
| 373 | state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store); |
| 374 | state.load_cached_translation_settings(); |
| 375 | if !mode.demo { |
| 376 | state.directory.load_cached_presence(&state.store); |
| 377 | state.reload_directory(); |
| 378 | } |
| 379 | state |
| 380 | } |
| 381 | |
| 382 | fn load_collapsed(&self) -> HashSet<String> { |
| 383 | self.store |
| 384 | .meta(COLLAPSED_META_KEY) |
| 385 | .ok() |
| 386 | .flatten() |
| 387 | .map(|value| { |
| 388 | value |
| 389 | .lines() |
| 390 | .map(str::to_owned) |
| 391 | .filter(|id| !id.is_empty()) |
| 392 | .collect() |
| 393 | }) |
| 394 | .unwrap_or_default() |
| 395 | } |
| 396 | |
| 397 | pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) { |
| 398 | if data::is_pending_folder(section_id) { |
| 399 | return; |
| 400 | } |
| 401 | let now_collapsed = self.collapsed.insert(section_id.to_owned()); |
| 402 | if !now_collapsed { |
| 403 | self.collapsed.remove(section_id); |
| 404 | } |
| 405 | self.save_collapsed(); |
| 406 | self.sync_folder_expanded(section_id, !now_collapsed); |
| 407 | cx.emit(AppEvent::Sidebar); |
| 408 | cx.notify(); |
| 409 | } |
| 410 | |
| 411 | pub fn older_chats(&self) -> (bool, bool) { |
| 412 | self.engine.as_ref().map_or((false, false), |engine| { |
| 413 | (engine.has_older_chats(), engine.is_loading_older_chats()) |
| 414 | }) |
| 415 | } |
| 416 | |
| 417 | pub fn request_older_chats(&self) { |
| 418 | let Some(engine) = self.engine.clone() else { |
| 419 | return; |
| 420 | }; |
| 421 | if !engine.has_older_chats() || engine.is_loading_older_chats() { |
| 422 | return; |
| 423 | } |
| 424 | drop(crate::runtime::spawn(async move { |
| 425 | if let Err(error) = engine.load_older_chats().await { |
| 426 | crate::diagnostics::record(format!("sync: older chats not loaded: {error}")); |
| 427 | } |
| 428 | })); |
| 429 | } |
| 430 | |
| 431 | pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) { |
| 432 | if !self.expanded_lists.remove(section_id) { |
| 433 | self.expanded_lists.insert(section_id.to_owned()); |
| 434 | } |
| 435 | cx.emit(AppEvent::Sidebar); |
| 436 | cx.notify(); |
| 437 | } |
| 438 | |
| 439 | fn save_collapsed(&self) { |
| 440 | let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect(); |
| 441 | ids.sort_unstable(); |
| 442 | let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n")); |
| 443 | } |
| 444 | |
| 445 | fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) { |
| 446 | let Some(folder) = self |
| 447 | .directory |
| 448 | .folders |
| 449 | .iter_mut() |
| 450 | .find(|folder| folder.id == folder_id && folder.expanded.is_some()) |
| 451 | else { |
| 452 | return; |
| 453 | }; |
| 454 | folder.expanded = Some(expanded); |
| 455 | let _ = self.store.set_folder_expanded(folder_id, expanded); |
| 456 | if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) { |
| 457 | let folder_id = folder_id.to_owned(); |
| 458 | drop(crate::runtime::spawn(async move { |
| 459 | engine.set_folder_expanded(&folder_id, expanded).await |
| 460 | })); |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | fn adopt_folder_expanded(&mut self) { |
| 465 | let snapshot = self.collapsed.clone(); |
| 466 | for folder in &self.directory.folders { |
| 467 | match folder.expanded { |
| 468 | Some(true) => { |
| 469 | self.collapsed.remove(&folder.id); |
| 470 | } |
| 471 | Some(false) => { |
| 472 | self.collapsed.insert(folder.id.clone()); |
| 473 | } |
| 474 | None => {} |
| 475 | } |
| 476 | } |
| 477 | if self.collapsed != snapshot { |
| 478 | self.save_collapsed(); |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | pub fn set_chat_section( |
| 483 | &mut self, |
| 484 | section: ChatSection, |
| 485 | enabled: bool, |
| 486 | cx: &mut Context<Self>, |
| 487 | ) { |
| 488 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 489 | return; |
| 490 | }; |
| 491 | let previous = self.directory.section_settings; |
| 492 | let mut updated = previous; |
| 493 | updated.set(section, enabled); |
| 494 | self.apply_section_settings(updated, cx); |
| 495 | let Some(engine) = engine_or_demo else { |
| 496 | return; |
| 497 | }; |
| 498 | self.run_chat_action( |
| 499 | "Chat list setting", |
| 500 | async move { engine.set_section_enabled(section, enabled).await }, |
| 501 | move |state, cx| state.apply_section_settings(previous, cx), |
| 502 | |_, _| {}, |
| 503 | cx, |
| 504 | ); |
| 505 | } |
| 506 | |
| 507 | pub fn set_skin_tone(&mut self, tone: u8, cx: &mut Context<Self>) { |
| 508 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 509 | return; |
| 510 | }; |
| 511 | let previous = teams_core::skin_tone(&self.store); |
| 512 | let _ = teams_core::store_account_skin_tone(&self.store, tone); |
| 513 | let Some(engine) = engine_or_demo else { |
| 514 | return; |
| 515 | }; |
| 516 | self.run_chat_action( |
| 517 | "Skin tone", |
| 518 | async move { engine.set_skin_tone(tone).await }, |
| 519 | move |state, _| { |
| 520 | let _ = teams_core::store_account_skin_tone(&state.store, previous); |
| 521 | }, |
| 522 | |_, _| {}, |
| 523 | cx, |
| 524 | ); |
| 525 | } |
| 526 | |
| 527 | fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) { |
| 528 | self.directory.section_settings = settings; |
| 529 | let _ = teams_core::store_section_settings(&self.store, &settings); |
| 530 | cx.emit(AppEvent::Sidebar); |
| 531 | cx.notify(); |
| 532 | } |
| 533 | |
| 534 | pub fn reload_directory(&mut self) { |
| 535 | self.directory.me = data::me(&self.store); |
| 536 | self.own_email = self |
| 537 | .store |
| 538 | .meta("me_email") |
| 539 | .ok() |
| 540 | .flatten() |
| 541 | .unwrap_or_default(); |
| 542 | self.directory.folders = data::folders(&self.store, &self.favorite_ids); |
| 543 | self.reapply_section_changes(); |
| 544 | self.directory.section_settings = teams_core::stored_section_settings(&self.store); |
| 545 | self.adopt_folder_expanded(); |
| 546 | self.directory.pinned_channels = data::pinned_channels(&self.store); |
| 547 | if self.directory.pinned_channels.is_empty() { |
| 548 | let known: HashSet<&str> = self |
| 549 | .sidebar |
| 550 | .teams |
| 551 | .iter() |
| 552 | .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str())) |
| 553 | .collect(); |
| 554 | self.directory.pinned_channels = self |
| 555 | .favorite_ids |
| 556 | .iter() |
| 557 | .filter(|id| known.contains(id.as_str())) |
| 558 | .cloned() |
| 559 | .collect(); |
| 560 | } |
| 561 | self.resolve_pending_avatars(); |
| 562 | self.sync_presence(); |
| 563 | self.directory.unread_counts = match &self.engine { |
| 564 | Some(engine) => data::unread_counts(engine, &self.sidebar.chats), |
| 565 | None => Default::default(), |
| 566 | }; |
| 567 | self.directory.unread_importance = match &self.engine { |
| 568 | Some(engine) => data::unread_importance(engine, &self.sidebar.chats), |
| 569 | None => Default::default(), |
| 570 | }; |
| 571 | } |
| 572 | |
| 573 | pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) { |
| 574 | let wanted = self.directory.missing_avatars(user_ids); |
| 575 | if wanted.is_empty() { |
| 576 | return; |
| 577 | } |
| 578 | let mut changed = false; |
| 579 | let mut uncached = Vec::new(); |
| 580 | for user_id in wanted { |
| 581 | match data::cached_avatar(&self.store, &user_id) { |
| 582 | Some(cached) => { |
| 583 | self.directory.set_avatar(&user_id, cached); |
| 584 | changed = true; |
| 585 | } |
| 586 | None => uncached.push(user_id), |
| 587 | } |
| 588 | } |
| 589 | if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) { |
| 590 | self.directory.mark_avatars_pending(&uncached); |
| 591 | let done = data::fetch_avatars(&engine, uncached); |
| 592 | self.on_done(done, cx, |state, cx| { |
| 593 | state.resolve_pending_avatars(); |
| 594 | cx.emit(AppEvent::Directory); |
| 595 | cx.notify(); |
| 596 | }); |
| 597 | changed = true; |
| 598 | } |
| 599 | if changed { |
| 600 | cx.emit(AppEvent::Directory); |
| 601 | cx.notify(); |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) { |
| 606 | let Some(engine) = self.engine.clone() else { |
| 607 | return; |
| 608 | }; |
| 609 | let wanted = self |
| 610 | .directory |
| 611 | .images_to_request(images.iter().map(|image| image.url.clone())); |
| 612 | let mut changed = false; |
| 613 | for image in images |
| 614 | .into_iter() |
| 615 | .filter(|image| wanted.contains(&image.url)) |
| 616 | { |
| 617 | match engine.image_path(&image) { |
| 618 | Some(path) => { |
| 619 | self.directory.set_image(&image.url, &path); |
| 620 | changed = true; |
| 621 | } |
| 622 | None => { |
| 623 | let done = data::fetch_image(&engine, image.clone()); |
| 624 | cx.spawn(async move |this, cx| { |
| 625 | if !matches!(done.await, Ok(Ok(()))) { |
| 626 | this.update(cx, |state, cx| { |
| 627 | state.directory.mark_image_failed(&image.url); |
| 628 | cx.notify(); |
| 629 | }) |
| 630 | .ok(); |
| 631 | } |
| 632 | }) |
| 633 | .detach(); |
| 634 | } |
| 635 | } |
| 636 | } |
| 637 | if changed { |
| 638 | cx.emit(AppEvent::Images(wanted)); |
| 639 | cx.notify(); |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | pub fn jump_to_message( |
| 644 | &mut self, |
| 645 | selection: Selection, |
| 646 | message_id: String, |
| 647 | cx: &mut Context<Self>, |
| 648 | ) { |
| 649 | self.pending_jump = Some((selection.conversation_id().to_owned(), message_id)); |
| 650 | if self.selection.as_ref() == Some(&selection) { |
| 651 | cx.emit(AppEvent::Jump); |
| 652 | } else { |
| 653 | self.select(selection, cx); |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | fn on_done( |
| 658 | &self, |
| 659 | done: data::Done, |
| 660 | cx: &mut Context<Self>, |
| 661 | then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static, |
| 662 | ) { |
| 663 | cx.spawn(async move |this, cx| { |
| 664 | let _ = done.await; |
| 665 | this.update(cx, |state, cx| then(state, cx)).ok(); |
| 666 | }) |
| 667 | .detach(); |
| 668 | } |
| 669 | |
| 670 | fn resolve_pending_avatars(&mut self) { |
| 671 | for user_id in self.directory.pending_avatars() { |
| 672 | if let Some(cached) = data::cached_avatar(&self.store, &user_id) { |
| 673 | self.directory.set_avatar(&user_id, cached); |
| 674 | } |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | fn sync_presence(&mut self) -> Vec<String> { |
| 679 | let Some(engine) = self.engine.clone() else { |
| 680 | return Vec::new(); |
| 681 | }; |
| 682 | self.directory |
| 683 | .requested_presence_ids() |
| 684 | .into_iter() |
| 685 | .filter(|user_id| { |
| 686 | let Some(kind) = data::presence_kind(&engine, user_id) else { |
| 687 | return false; |
| 688 | }; |
| 689 | let activity_changed = self |
| 690 | .directory |
| 691 | .set_activity(user_id, data::presence_activity(&engine, user_id)); |
| 692 | let previous = self.directory.presence_of(user_id); |
| 693 | let changed = self.directory.set_presence(user_id, kind); |
| 694 | if changed { |
| 695 | self.note_followed_change(user_id, previous, kind); |
| 696 | } |
| 697 | changed || activity_changed |
| 698 | }) |
| 699 | .collect() |
| 700 | } |
| 701 | |
| 702 | pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) { |
| 703 | let now = Instant::now(); |
| 704 | let pushed = self.live == LiveState::Live; |
| 705 | let wanted = self.directory.stale_presence(user_ids, now, pushed); |
| 706 | if wanted.is_empty() { |
| 707 | return; |
| 708 | } |
| 709 | self.directory.mark_presence_pending(&wanted); |
| 710 | if let Some(engine) = self.engine.clone() { |
| 711 | self.directory.mark_presence_requested(&wanted, now); |
| 712 | drop(data::watch_presence(&engine, wanted.clone())); |
| 713 | let done = data::refresh_presence(&engine, wanted.clone()); |
| 714 | self.on_done(done, cx, move |state, cx| { |
| 715 | state.sync_presence(); |
| 716 | state.announce_followed_changes(cx); |
| 717 | state.directory.save_presence(&state.store, &wanted); |
| 718 | state.directory.settle_presence(&wanted); |
| 719 | cx.emit(AppEvent::Directory); |
| 720 | cx.notify(); |
| 721 | }); |
| 722 | } |
| 723 | } |
| 724 | |
| 725 | pub fn move_chat( |
| 726 | &mut self, |
| 727 | conversation_id: &str, |
| 728 | folder_id: Option<&str>, |
| 729 | cx: &mut Context<Self>, |
| 730 | ) { |
| 731 | self.place_chat(conversation_id, folder_id, None, cx); |
| 732 | } |
| 733 | |
| 734 | pub fn drop_chat_on( |
| 735 | &mut self, |
| 736 | conversation_id: &str, |
| 737 | target_conversation_id: &str, |
| 738 | folder_id: &str, |
| 739 | cx: &mut Context<Self>, |
| 740 | ) { |
| 741 | if conversation_id == target_conversation_id { |
| 742 | return; |
| 743 | } |
| 744 | let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else { |
| 745 | return; |
| 746 | }; |
| 747 | self.place_chat(conversation_id, Some(folder_id), Some(slot), cx); |
| 748 | } |
| 749 | |
| 750 | pub fn place_chat( |
| 751 | &mut self, |
| 752 | conversation_id: &str, |
| 753 | folder_id: Option<&str>, |
| 754 | index: Option<usize>, |
| 755 | cx: &mut Context<Self>, |
| 756 | ) { |
| 757 | if self.mode.read_only { |
| 758 | return; |
| 759 | } |
| 760 | let previous_folder = self |
| 761 | .directory |
| 762 | .folder_of(conversation_id) |
| 763 | .map(|folder| folder.id.clone()); |
| 764 | self.directory.place(conversation_id, folder_id, index); |
| 765 | if let Some(engine) = self.engine.clone() { |
| 766 | let previous = previous_folder.clone(); |
| 767 | let done = match (folder_id, previous.as_deref()) { |
| 768 | (Some(folder_id), _) => Some(data::move_to_folder( |
| 769 | &engine, |
| 770 | conversation_id, |
| 771 | folder_id, |
| 772 | index, |
| 773 | )), |
| 774 | (None, Some(previous)) => { |
| 775 | Some(data::remove_from_folder(&engine, conversation_id, previous)) |
| 776 | } |
| 777 | (None, None) => None, |
| 778 | }; |
| 779 | if let Some(done) = done { |
| 780 | self.on_done(done, cx, |state, cx| { |
| 781 | state.reload_directory(); |
| 782 | cx.emit(AppEvent::Sidebar); |
| 783 | cx.notify(); |
| 784 | }); |
| 785 | } |
| 786 | } |
| 787 | cx.emit(AppEvent::Sidebar); |
| 788 | cx.notify(); |
| 789 | } |
| 790 | |
| 791 | pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 792 | if self.keeps_unread(conversation_id) { |
| 793 | self.keep_unread = None; |
| 794 | } |
| 795 | if self.mode.demo { |
| 796 | if let Some(chat) = self |
| 797 | .sidebar |
| 798 | .chats |
| 799 | .iter() |
| 800 | .find(|chat| chat.id == conversation_id) |
| 801 | { |
| 802 | let mut read = chat.clone(); |
| 803 | read.unread = false; |
| 804 | let _ = self.store.upsert_chats(&[read]); |
| 805 | self.reload_sidebar(cx); |
| 806 | } |
| 807 | return; |
| 808 | } |
| 809 | if self.mode.read_only { |
| 810 | return; |
| 811 | } |
| 812 | if let Some(engine) = self.engine.clone() { |
| 813 | let _ = self |
| 814 | .store |
| 815 | .mark_chat_read(conversation_id, chrono::Utc::now()); |
| 816 | self.reload_sidebar(cx); |
| 817 | let conversation_id = conversation_id.to_owned(); |
| 818 | drop(crate::runtime::spawn(async move { |
| 819 | engine.mark_read(&conversation_id).await |
| 820 | })); |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) { |
| 825 | if self.mode.read_only { |
| 826 | return; |
| 827 | } |
| 828 | let _ = self.store.mark_channel_read(channel_id); |
| 829 | self.reload_sidebar(cx); |
| 830 | if self.mode.demo { |
| 831 | return; |
| 832 | } |
| 833 | if let Some(engine) = self.engine.clone() { |
| 834 | let channel_id = channel_id.to_owned(); |
| 835 | drop(crate::runtime::spawn(async move { |
| 836 | engine.mark_read(&channel_id).await |
| 837 | })); |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) { |
| 842 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 843 | return; |
| 844 | }; |
| 845 | let previous_unread: Vec<(String, bool, Option<DateTime<Utc>>)> = self |
| 846 | .sidebar |
| 847 | .teams |
| 848 | .iter() |
| 849 | .flat_map(|team| team.channels.iter()) |
| 850 | .map(|channel| (channel.id.clone(), channel.unread, None)) |
| 851 | .collect(); |
| 852 | let previous_mentions: Vec<(String, store::ChannelMentions)> = self |
| 853 | .sidebar |
| 854 | .teams |
| 855 | .iter() |
| 856 | .flat_map(|team| team.mentions.iter()) |
| 857 | .map(|(channel_id, mentions)| (channel_id.clone(), *mentions)) |
| 858 | .collect(); |
| 859 | let _ = self.store.mark_all_channels_read(); |
| 860 | self.reload_sidebar(cx); |
| 861 | let Some(engine) = engine_or_demo else { |
| 862 | return; |
| 863 | }; |
| 864 | self.run_chat_action( |
| 865 | "Mark all as read", |
| 866 | async move { engine.mark_all_channels_read().await }, |
| 867 | move |state, cx| { |
| 868 | let _ = state.store.apply_channel_read_states(&previous_unread); |
| 869 | let _ = state.store.replace_channel_mentions(&previous_mentions); |
| 870 | state.reload_sidebar(cx); |
| 871 | }, |
| 872 | |_, _| {}, |
| 873 | cx, |
| 874 | ); |
| 875 | } |
| 876 | |
| 877 | pub fn start_new_chat(&mut self, cx: &mut Context<Self>) { |
| 878 | self.new_chat = true; |
| 879 | self.show_call(false, cx); |
| 880 | cx.emit(AppEvent::Selection); |
| 881 | cx.notify(); |
| 882 | } |
| 883 | |
| 884 | pub fn close_new_chat(&mut self, cx: &mut Context<Self>) { |
| 885 | if !self.new_chat { |
| 886 | return; |
| 887 | } |
| 888 | self.new_chat = false; |
| 889 | cx.emit(AppEvent::Selection); |
| 890 | cx.notify(); |
| 891 | } |
| 892 | |
| 893 | pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) { |
| 894 | self.show_call(false, cx); |
| 895 | self.cancel_prejoin(cx); |
| 896 | self.call_end = None; |
| 897 | let was_drafting = std::mem::take(&mut self.new_chat); |
| 898 | if !was_drafting && self.selection.as_ref() == Some(&selection) { |
| 899 | return; |
| 900 | } |
| 901 | let conversation_id = selection.conversation_id().to_owned(); |
| 902 | self.selection = Some(selection); |
| 903 | self.keep_unread = None; |
| 904 | self.forward_selection = None; |
| 905 | cx.emit(AppEvent::Selection); |
| 906 | cx.notify(); |
| 907 | self.refresh_live_meeting(&conversation_id, cx); |
| 908 | self.refresh_language_stamps(&conversation_id, cx); |
| 909 | } |
| 910 | |
| 911 | fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) { |
| 912 | let is_me = self |
| 913 | .directory |
| 914 | .me |
| 915 | .as_ref() |
| 916 | .is_some_and(|me| me.user_id == event.user_id); |
| 917 | if is_me { |
| 918 | return; |
| 919 | } |
| 920 | if event.active { |
| 921 | let display_name = match event.display_name.trim() { |
| 922 | "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id)) |
| 923 | .remove(&event.user_id) |
| 924 | .unwrap_or_default(), |
| 925 | _ => event.display_name.clone(), |
| 926 | }; |
| 927 | self.typing.start( |
| 928 | &event.conversation_id, |
| 929 | &event.user_id, |
| 930 | &display_name, |
| 931 | Instant::now(), |
| 932 | event.received_at, |
| 933 | ); |
| 934 | self.request_avatars(vec![event.user_id.clone()], cx); |
| 935 | self.schedule_typing_expiry(cx); |
| 936 | } else { |
| 937 | self.typing.clear(&event.conversation_id, &event.user_id); |
| 938 | } |
| 939 | cx.emit(AppEvent::Typing); |
| 940 | cx.notify(); |
| 941 | } |
| 942 | |
| 943 | fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 944 | if !self.typing.is_active(conversation_id) { |
| 945 | return; |
| 946 | } |
| 947 | let Ok(recent) = self |
| 948 | .store |
| 949 | .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING) |
| 950 | else { |
| 951 | return; |
| 952 | }; |
| 953 | let mut changed = false; |
| 954 | for message in recent { |
| 955 | if let Some(sender_id) = message.sender_id.as_deref() { |
| 956 | changed |= self |
| 957 | .typing |
| 958 | .message_from(conversation_id, sender_id, message.created_at); |
| 959 | } |
| 960 | } |
| 961 | if changed { |
| 962 | cx.emit(AppEvent::Typing); |
| 963 | cx.notify(); |
| 964 | } |
| 965 | } |
| 966 | |
| 967 | fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) { |
| 968 | if self.typing_timer_running { |
| 969 | return; |
| 970 | } |
| 971 | self.typing_timer_running = true; |
| 972 | cx.spawn(async move |this, cx| { |
| 973 | loop { |
| 974 | let next = this.update(cx, |state, _| { |
| 975 | let next = state.typing.next_expiry(); |
| 976 | state.typing_timer_running = next.is_some(); |
| 977 | next |
| 978 | }); |
| 979 | let Ok(Some(next)) = next else { return }; |
| 980 | cx.background_executor() |
| 981 | .timer(next.saturating_duration_since(Instant::now())) |
| 982 | .await; |
| 983 | let alive = this.update(cx, |state, cx| { |
| 984 | if state.typing.expire(Instant::now()) { |
| 985 | cx.emit(AppEvent::Typing); |
| 986 | cx.notify(); |
| 987 | } |
| 988 | }); |
| 989 | if alive.is_err() { |
| 990 | return; |
| 991 | } |
| 992 | } |
| 993 | }) |
| 994 | .detach(); |
| 995 | } |
| 996 | |
| 997 | pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) { |
| 998 | if let Ok(sidebar) = self.store.sidebar() { |
| 999 | self.sidebar = sidebar; |
| 1000 | self.apply_bot_titles(); |
| 1001 | } |
| 1002 | self.calls_list.invalidate(); |
| 1003 | if !self.mode.demo { |
| 1004 | self.reload_directory(); |
| 1005 | self.load_own_time_zone(cx); |
| 1006 | } |
| 1007 | cx.emit(AppEvent::Sidebar); |
| 1008 | cx.notify(); |
| 1009 | } |
| 1010 | |
| 1011 | pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) { |
| 1012 | match event { |
| 1013 | BackendEvent::Connection(connection) => { |
| 1014 | self.connection = connection; |
| 1015 | self.refresh_connection_banner(cx); |
| 1016 | cx.emit(AppEvent::Status); |
| 1017 | } |
| 1018 | BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry), |
| 1019 | BackendEvent::Calls(launcher) => { |
| 1020 | launcher.set_default_camera(self.call_camera.clone()); |
| 1021 | self.call_launcher = Some(launcher); |
| 1022 | self.load_own_time_zone(cx); |
| 1023 | } |
| 1024 | BackendEvent::Calendar(events) => self.apply_calendar(events, cx), |
| 1025 | BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge), |
| 1026 | BackendEvent::Ring(event) => self.on_engine_event(event, cx), |
| 1027 | BackendEvent::ThreadChanged(conversation_id) => { |
| 1028 | self.on_thread_changed(&conversation_id, cx) |
| 1029 | } |
| 1030 | BackendEvent::Engine(engine) => { |
| 1031 | crate::agent_api::engine_ready(engine.clone(), cx); |
| 1032 | self.engine = Some(engine); |
| 1033 | self.resend_outbox(cx); |
| 1034 | self.refresh_scheduled(cx); |
| 1035 | self.refresh_translation_settings(cx); |
| 1036 | self.refresh_recording_policy(cx); |
| 1037 | self.refresh_messaging_policy(cx); |
| 1038 | self.refresh_sound_settings(cx); |
| 1039 | self.refresh_chat_settings(cx); |
| 1040 | let waiting = self.directory.waiting_presence_ids(); |
| 1041 | self.request_presence(waiting, cx); |
| 1042 | self.watch_followed_presence(cx); |
| 1043 | self.refresh_own_status(cx); |
| 1044 | cx.emit(AppEvent::Status); |
| 1045 | } |
| 1046 | BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx), |
| 1047 | BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity), |
| 1048 | BackendEvent::Core( |
| 1049 | CoreEvent::MessagesChanged { conversation_id } |
| 1050 | | CoreEvent::ReceiptsChanged { conversation_id }, |
| 1051 | ) => { |
| 1052 | self.clear_typists_who_sent(&conversation_id, cx); |
| 1053 | self.refresh_language_stamps(&conversation_id, cx); |
| 1054 | cx.emit(AppEvent::Messages(conversation_id)); |
| 1055 | } |
| 1056 | BackendEvent::Core(CoreEvent::MessagesStoredLate { |
| 1057 | conversation_id, |
| 1058 | message_ids, |
| 1059 | }) => self.late_arrivals.insert(&conversation_id, message_ids), |
| 1060 | BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => { |
| 1061 | self.refresh_pins(&conversation_id, cx); |
| 1062 | } |
| 1063 | BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => { |
| 1064 | if let Some(engine) = &self.engine { |
| 1065 | for key in &keys { |
| 1066 | let image = ImageRef { |
| 1067 | id: String::new(), |
| 1068 | url: key.clone(), |
| 1069 | width: None, |
| 1070 | height: None, |
| 1071 | alt: None, |
| 1072 | }; |
| 1073 | if let Some(path) = engine.image_path(&image) { |
| 1074 | self.directory.set_image(key, &path); |
| 1075 | } |
| 1076 | } |
| 1077 | } |
| 1078 | cx.emit(AppEvent::Images(keys)); |
| 1079 | } |
| 1080 | BackendEvent::Core(CoreEvent::PresenceChanged) => { |
| 1081 | let changed = self.sync_presence(); |
| 1082 | self.announce_followed_changes(cx); |
| 1083 | self.directory.save_presence(&self.store, &changed); |
| 1084 | cx.emit(AppEvent::Directory); |
| 1085 | cx.notify(); |
| 1086 | } |
| 1087 | BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => { |
| 1088 | self.apply_own_status(status, cx); |
| 1089 | self.reload_directory(); |
| 1090 | } |
| 1091 | BackendEvent::Core(_) => { |
| 1092 | if !self.mode.demo { |
| 1093 | self.reload_directory(); |
| 1094 | } |
| 1095 | cx.emit(AppEvent::Directory); |
| 1096 | } |
| 1097 | BackendEvent::Typing(event) => self.apply_typing(event, cx), |
| 1098 | BackendEvent::Live(live) => { |
| 1099 | self.live = live; |
| 1100 | self.refresh_connection_banner(cx); |
| 1101 | cx.emit(AppEvent::Status); |
| 1102 | } |
| 1103 | BackendEvent::Favorites(ids) => { |
| 1104 | self.favorite_ids = ids; |
| 1105 | if !self.mode.demo { |
| 1106 | self.reload_directory(); |
| 1107 | } |
| 1108 | cx.emit(AppEvent::Sidebar); |
| 1109 | } |
| 1110 | BackendEvent::Synced(time) => { |
| 1111 | if self.last_sync.is_none() { |
| 1112 | self.refresh_saved(cx); |
| 1113 | } |
| 1114 | self.last_sync = Some(time); |
| 1115 | cx.emit(AppEvent::Status); |
| 1116 | } |
| 1117 | } |
| 1118 | cx.notify(); |
| 1119 | } |
| 1120 | } |
| 1121 | |
| 1122 | #[cfg(test)] |
| 1123 | mod tests { |
| 1124 | use std::sync::Arc; |
| 1125 | |
| 1126 | use chatsvc::TypingEvent; |
| 1127 | use chrono::{Duration, Utc}; |
| 1128 | use gpui_kit::{AppContext as _, TestAppContext}; |
| 1129 | use store::{ |
| 1130 | ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord, |
| 1131 | }; |
| 1132 | use teams_core::CoreEvent; |
| 1133 | |
| 1134 | use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title}; |
| 1135 | use crate::backend::BackendEvent; |
| 1136 | use crate::data::Person; |
| 1137 | use store::Sidebar; |
| 1138 | |
| 1139 | fn chat(id: &str, title: &str, unread: bool) -> ChatRecord { |
| 1140 | ChatRecord { |
| 1141 | id: id.into(), |
| 1142 | kind: "group".into(), |
| 1143 | title: title.into(), |
| 1144 | member_summary: "Member".into(), |
| 1145 | last_message_at: None, |
| 1146 | last_read_at: None, |
| 1147 | unread, |
| 1148 | ..Default::default() |
| 1149 | } |
| 1150 | } |
| 1151 | |
| 1152 | #[test] |
| 1153 | fn selection_kind_follows_sidebar() { |
| 1154 | assert_eq!( |
| 1155 | selection_for(&sidebar(), "c1"), |
| 1156 | Some(Selection::Chat("c1".into())) |
| 1157 | ); |
| 1158 | assert_eq!( |
| 1159 | selection_for(&sidebar(), "ch"), |
| 1160 | Some(Selection::Channel("ch".into())) |
| 1161 | ); |
| 1162 | assert_eq!(selection_for(&sidebar(), "x"), None); |
| 1163 | } |
| 1164 | |
| 1165 | fn sidebar() -> Sidebar { |
| 1166 | Sidebar { |
| 1167 | chats: vec![chat("c1", "First", true), chat("c2", "", false)], |
| 1168 | teams: vec![SidebarTeam { |
| 1169 | team: TeamRecord { |
| 1170 | id: "t".into(), |
| 1171 | name: "Team".into(), |
| 1172 | }, |
| 1173 | channels: vec![ChannelRecord { |
| 1174 | id: "ch".into(), |
| 1175 | team_id: "t".into(), |
| 1176 | name: "General".into(), |
| 1177 | membership_type: None, |
| 1178 | last_message_at: None, |
| 1179 | unread: false, |
| 1180 | }], |
| 1181 | hidden: false, |
| 1182 | hidden_channel_ids: Vec::new(), |
| 1183 | notifications: Default::default(), |
| 1184 | mentions: Default::default(), |
| 1185 | }], |
| 1186 | } |
| 1187 | } |
| 1188 | |
| 1189 | #[test] |
| 1190 | fn empty_chat_title_falls_back_to_members() { |
| 1191 | assert_eq!(chat_title(&sidebar().chats[1]), "Member"); |
| 1192 | } |
| 1193 | |
| 1194 | #[test] |
| 1195 | fn selection_titles() { |
| 1196 | assert_eq!( |
| 1197 | selection_title(&sidebar(), &Selection::Channel("ch".into())), |
| 1198 | "Team / General" |
| 1199 | ); |
| 1200 | assert_eq!( |
| 1201 | selection_title(&sidebar(), &Selection::Chat("c1".into())), |
| 1202 | "First" |
| 1203 | ); |
| 1204 | } |
| 1205 | |
| 1206 | fn typing_event(user_id: &str, active: bool) -> BackendEvent { |
| 1207 | BackendEvent::Typing(TypingEvent { |
| 1208 | conversation_id: "c1".into(), |
| 1209 | user_id: user_id.into(), |
| 1210 | display_name: format!("Name {user_id}"), |
| 1211 | active, |
| 1212 | received_at: Utc::now(), |
| 1213 | }) |
| 1214 | } |
| 1215 | |
| 1216 | #[gpui_kit::test] |
| 1217 | fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) { |
| 1218 | cx.update(gpui_kit::init); |
| 1219 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 1220 | let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default()))); |
| 1221 | cx.update(|cx| { |
| 1222 | app.update(cx, |state, cx| { |
| 1223 | state.toggle_collapsed("pending-section:1", cx); |
| 1224 | assert!(state.collapsed.is_empty()); |
| 1225 | }) |
| 1226 | }); |
| 1227 | } |
| 1228 | |
| 1229 | #[gpui_kit::test] |
| 1230 | fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) { |
| 1231 | cx.update(gpui_kit::init); |
| 1232 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 1233 | let app = cx.update(|cx| { |
| 1234 | cx.new(|_| { |
| 1235 | let mut state = AppState::new(store.clone(), Mode::default()); |
| 1236 | state.directory.me = Some(Person { |
| 1237 | user_id: "me".into(), |
| 1238 | display_name: "Me".into(), |
| 1239 | }); |
| 1240 | state |
| 1241 | }) |
| 1242 | }); |
| 1243 | let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1")); |
| 1244 | cx.update(|cx| { |
| 1245 | app.update(cx, |state, cx| { |
| 1246 | state.apply(typing_event("me", true), cx); |
| 1247 | state.apply(typing_event("ada", true), cx); |
| 1248 | }) |
| 1249 | }); |
| 1250 | assert_eq!(names(cx), vec!["Name ada".to_owned()]); |
| 1251 | |
| 1252 | let message = MessageRecord { |
| 1253 | conversation_id: "c1".into(), |
| 1254 | message_id: "m1".into(), |
| 1255 | sender_id: Some("ada".into()), |
| 1256 | created_at: Utc::now() + Duration::seconds(1), |
| 1257 | ..Default::default() |
| 1258 | }; |
| 1259 | store.upsert_messages(&[message]).unwrap(); |
| 1260 | cx.update(|cx| { |
| 1261 | app.update(cx, |state, cx| { |
| 1262 | state.apply( |
| 1263 | BackendEvent::Core(CoreEvent::MessagesChanged { |
| 1264 | conversation_id: "c1".into(), |
| 1265 | }), |
| 1266 | cx, |
| 1267 | ) |
| 1268 | }) |
| 1269 | }); |
| 1270 | assert!(names(cx).is_empty()); |
| 1271 | |
| 1272 | cx.update(|cx| { |
| 1273 | app.update(cx, |state, cx| { |
| 1274 | state.apply(typing_event("ada", true), cx); |
| 1275 | state.apply(typing_event("ada", false), cx); |
| 1276 | }) |
| 1277 | }); |
| 1278 | assert!(names(cx).is_empty()); |
| 1279 | } |
| 1280 | |
| 1281 | #[gpui_kit::test] |
| 1282 | fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) { |
| 1283 | cx.update(gpui_kit::init); |
| 1284 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 1285 | let app = cx.update(|cx| { |
| 1286 | cx.new(|_| { |
| 1287 | let mut state = AppState::new(store.clone(), Mode::default()); |
| 1288 | let mut member_chat = chat("c1", "First", false); |
| 1289 | member_chat.members = vec![MemberRecord { |
| 1290 | user_id: Some("ada".into()), |
| 1291 | display_name: "Ada Lovelace".into(), |
| 1292 | }]; |
| 1293 | state.sidebar.chats = vec![member_chat]; |
| 1294 | state |
| 1295 | }) |
| 1296 | }); |
| 1297 | cx.update(|cx| { |
| 1298 | app.update(cx, |state, cx| { |
| 1299 | state.apply( |
| 1300 | BackendEvent::Typing(TypingEvent { |
| 1301 | conversation_id: "c1".into(), |
| 1302 | user_id: "ada".into(), |
| 1303 | display_name: String::new(), |
| 1304 | active: true, |
| 1305 | received_at: Utc::now(), |
| 1306 | }), |
| 1307 | cx, |
| 1308 | ) |
| 1309 | }) |
| 1310 | }); |
| 1311 | assert_eq!( |
| 1312 | cx.update(|cx| app.read(cx).typing.names("c1")), |
| 1313 | vec!["Ada Lovelace".to_owned()] |
| 1314 | ); |
| 1315 | } |
| 1316 | } |