| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::Instant; |
| 4 | |
| 5 | use chrono::{DateTime, Utc}; |
| 6 | use gpui_kit::*; |
| 7 | use store::{ChatRecord, Sidebar, Store}; |
| 8 | use teams_core::{ChatApp, CoreEvent, ImageRef}; |
| 9 | |
| 10 | use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState}; |
| 11 | use crate::card_state::{CardState, TaskDialogState}; |
| 12 | use crate::data::{self, Directory}; |
| 13 | use crate::notice::Notice; |
| 14 | use crate::notify; |
| 15 | |
| 16 | const COLLAPSED_META_KEY: &str = "ui.collapsed_sections"; |
| 17 | |
| 18 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 19 | pub enum Selection { |
| 20 | Chat(String), |
| 21 | Channel(String), |
| 22 | } |
| 23 | |
| 24 | impl Selection { |
| 25 | pub fn conversation_id(&self) -> &str { |
| 26 | match self { |
| 27 | Selection::Chat(id) | Selection::Channel(id) => id, |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | pub enum AppEvent { |
| 33 | Sidebar, |
| 34 | Selection, |
| 35 | Messages(String), |
| 36 | Images(Vec<String>), |
| 37 | Jump, |
| 38 | Status, |
| 39 | Directory, |
| 40 | Cards(String), |
| 41 | TaskDialog, |
| 42 | } |
| 43 | |
| 44 | #[derive(Debug, Clone, Copy, Default)] |
| 45 | pub struct Mode { |
| 46 | pub demo: bool, |
| 47 | pub read_only: bool, |
| 48 | pub demo_sync: Option<std::time::Duration>, |
| 49 | } |
| 50 | |
| 51 | pub struct AppState { |
| 52 | pub store: Arc<Store>, |
| 53 | pub engine: Option<Arc<Engine>>, |
| 54 | pub sidebar: Sidebar, |
| 55 | pub favorite_ids: Vec<String>, |
| 56 | pub selection: Option<Selection>, |
| 57 | pub new_chat: bool, |
| 58 | pub connection: ConnectionState, |
| 59 | pub live: LiveState, |
| 60 | pub last_sync: Option<DateTime<Utc>>, |
| 61 | pub mode: Mode, |
| 62 | pub directory: Directory, |
| 63 | pub collapsed: HashSet<String>, |
| 64 | pub followed_channels: HashSet<String>, |
| 65 | pub start_on_channels: bool, |
| 66 | pub pending_jump: Option<(String, String)>, |
| 67 | pub cards: CardState, |
| 68 | pub task_dialog: Option<TaskDialogState>, |
| 69 | pub bot_apps: HashMap<String, Vec<ChatApp>>, |
| 70 | pub bot_apps_pending: HashSet<String>, |
| 71 | pub notice: Option<Notice>, |
| 72 | pub notice_count: u64, |
| 73 | pub keep_unread: Option<String>, |
| 74 | } |
| 75 | |
| 76 | pub struct AppHandle(pub Entity<AppState>); |
| 77 | |
| 78 | impl Global for AppHandle {} |
| 79 | |
| 80 | impl EventEmitter<AppEvent> for AppState {} |
| 81 | |
| 82 | pub fn chat_title(chat: &ChatRecord) -> String { |
| 83 | if !chat.title.trim().is_empty() { |
| 84 | chat.title.clone() |
| 85 | } else if !chat.member_summary.trim().is_empty() { |
| 86 | chat.member_summary.clone() |
| 87 | } else { |
| 88 | "Chat".to_owned() |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String { |
| 93 | match selection { |
| 94 | Selection::Chat(id) => sidebar |
| 95 | .chats |
| 96 | .iter() |
| 97 | .find(|chat| &chat.id == id) |
| 98 | .map(chat_title) |
| 99 | .unwrap_or_else(|| "Chat".to_owned()), |
| 100 | Selection::Channel(id) => sidebar |
| 101 | .teams |
| 102 | .iter() |
| 103 | .find_map(|team| { |
| 104 | team.channels |
| 105 | .iter() |
| 106 | .find(|channel| &channel.id == id) |
| 107 | .map(|channel| format!("{} / {}", team.team.name, channel.name)) |
| 108 | }) |
| 109 | .unwrap_or_else(|| "Channel".to_owned()), |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | impl AppState { |
| 114 | pub fn new(store: Arc<Store>, mode: Mode) -> Self { |
| 115 | let sidebar = store.sidebar().unwrap_or_default(); |
| 116 | let mut state = AppState { |
| 117 | store, |
| 118 | engine: None, |
| 119 | sidebar, |
| 120 | favorite_ids: Vec::new(), |
| 121 | selection: None, |
| 122 | new_chat: false, |
| 123 | connection: if mode.demo { |
| 124 | ConnectionState::Online |
| 125 | } else { |
| 126 | ConnectionState::Connecting |
| 127 | }, |
| 128 | live: LiveState::Off, |
| 129 | last_sync: None, |
| 130 | mode, |
| 131 | directory: Directory::default(), |
| 132 | collapsed: HashSet::new(), |
| 133 | followed_channels: HashSet::new(), |
| 134 | start_on_channels: false, |
| 135 | pending_jump: None, |
| 136 | cards: CardState::default(), |
| 137 | task_dialog: None, |
| 138 | bot_apps: HashMap::new(), |
| 139 | bot_apps_pending: HashSet::new(), |
| 140 | notice: None, |
| 141 | notice_count: 0, |
| 142 | keep_unread: None, |
| 143 | }; |
| 144 | state.collapsed = state.load_collapsed(); |
| 145 | state.followed_channels = notify::load_followed_channels(&state.store); |
| 146 | if !mode.demo { |
| 147 | state.directory.load_cached_presence(&state.store); |
| 148 | state.reload_directory(); |
| 149 | } |
| 150 | state |
| 151 | } |
| 152 | |
| 153 | fn load_collapsed(&self) -> HashSet<String> { |
| 154 | self.store |
| 155 | .meta(COLLAPSED_META_KEY) |
| 156 | .ok() |
| 157 | .flatten() |
| 158 | .map(|value| { |
| 159 | value |
| 160 | .lines() |
| 161 | .map(str::to_owned) |
| 162 | .filter(|id| !id.is_empty()) |
| 163 | .collect() |
| 164 | }) |
| 165 | .unwrap_or_default() |
| 166 | } |
| 167 | |
| 168 | pub fn toggle_followed_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) { |
| 169 | if !self.followed_channels.remove(channel_id) { |
| 170 | self.followed_channels.insert(channel_id.to_owned()); |
| 171 | } |
| 172 | notify::save_followed_channels(&self.store, &self.followed_channels); |
| 173 | cx.notify(); |
| 174 | } |
| 175 | |
| 176 | pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) { |
| 177 | if !self.collapsed.remove(section_id) { |
| 178 | self.collapsed.insert(section_id.to_owned()); |
| 179 | } |
| 180 | let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect(); |
| 181 | ids.sort_unstable(); |
| 182 | let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n")); |
| 183 | cx.emit(AppEvent::Sidebar); |
| 184 | cx.notify(); |
| 185 | } |
| 186 | |
| 187 | pub fn reload_directory(&mut self) { |
| 188 | self.directory.me = data::me(&self.store); |
| 189 | self.directory.folders = data::folders(&self.store, &self.favorite_ids); |
| 190 | self.directory.pinned_channels = data::pinned_channels(&self.store); |
| 191 | if self.directory.pinned_channels.is_empty() { |
| 192 | let known: HashSet<&str> = self |
| 193 | .sidebar |
| 194 | .teams |
| 195 | .iter() |
| 196 | .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str())) |
| 197 | .collect(); |
| 198 | self.directory.pinned_channels = self |
| 199 | .favorite_ids |
| 200 | .iter() |
| 201 | .filter(|id| known.contains(id.as_str())) |
| 202 | .cloned() |
| 203 | .collect(); |
| 204 | } |
| 205 | self.resolve_pending_avatars(); |
| 206 | self.sync_presence(); |
| 207 | self.directory.unread_counts = match &self.engine { |
| 208 | Some(engine) => data::unread_counts(engine, &self.sidebar.chats), |
| 209 | None => Default::default(), |
| 210 | }; |
| 211 | } |
| 212 | |
| 213 | pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) { |
| 214 | let wanted = self.directory.missing_avatars(user_ids); |
| 215 | if wanted.is_empty() { |
| 216 | return; |
| 217 | } |
| 218 | let mut changed = false; |
| 219 | let mut uncached = Vec::new(); |
| 220 | for user_id in wanted { |
| 221 | match data::cached_avatar(&self.store, &user_id) { |
| 222 | Some(cached) => { |
| 223 | self.directory.set_avatar(&user_id, cached); |
| 224 | changed = true; |
| 225 | } |
| 226 | None => uncached.push(user_id), |
| 227 | } |
| 228 | } |
| 229 | if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) { |
| 230 | self.directory.mark_avatars_pending(&uncached); |
| 231 | let done = data::fetch_avatars(&engine, uncached); |
| 232 | self.on_done(done, cx, |state, cx| { |
| 233 | state.resolve_pending_avatars(); |
| 234 | cx.emit(AppEvent::Directory); |
| 235 | cx.notify(); |
| 236 | }); |
| 237 | changed = true; |
| 238 | } |
| 239 | if changed { |
| 240 | cx.emit(AppEvent::Directory); |
| 241 | cx.notify(); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) { |
| 246 | let Some(engine) = self.engine.clone() else { |
| 247 | return; |
| 248 | }; |
| 249 | let wanted = self |
| 250 | .directory |
| 251 | .images_to_request(images.iter().map(|image| image.url.clone())); |
| 252 | let mut changed = false; |
| 253 | for image in images |
| 254 | .into_iter() |
| 255 | .filter(|image| wanted.contains(&image.url)) |
| 256 | { |
| 257 | match engine.image_path(&image) { |
| 258 | Some(path) => { |
| 259 | self.directory.set_image(&image.url, &path); |
| 260 | changed = true; |
| 261 | } |
| 262 | None => { |
| 263 | let done = data::fetch_image(&engine, image); |
| 264 | self.on_done(done, cx, |_, _| {}); |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | if changed { |
| 269 | cx.emit(AppEvent::Images(wanted)); |
| 270 | cx.notify(); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | pub fn jump_to_message( |
| 275 | &mut self, |
| 276 | selection: Selection, |
| 277 | message_id: String, |
| 278 | cx: &mut Context<Self>, |
| 279 | ) { |
| 280 | self.pending_jump = Some((selection.conversation_id().to_owned(), message_id)); |
| 281 | if self.selection.as_ref() == Some(&selection) { |
| 282 | cx.emit(AppEvent::Jump); |
| 283 | } else { |
| 284 | self.select(selection, cx); |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | fn on_done( |
| 289 | &self, |
| 290 | done: data::Done, |
| 291 | cx: &mut Context<Self>, |
| 292 | then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static, |
| 293 | ) { |
| 294 | cx.spawn(async move |this, cx| { |
| 295 | let _ = done.await; |
| 296 | this.update(cx, |state, cx| then(state, cx)).ok(); |
| 297 | }) |
| 298 | .detach(); |
| 299 | } |
| 300 | |
| 301 | fn resolve_pending_avatars(&mut self) { |
| 302 | for user_id in self.directory.pending_avatars() { |
| 303 | if let Some(cached) = data::cached_avatar(&self.store, &user_id) { |
| 304 | self.directory.set_avatar(&user_id, cached); |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | fn sync_presence(&mut self) -> Vec<String> { |
| 310 | let Some(engine) = self.engine.clone() else { |
| 311 | return Vec::new(); |
| 312 | }; |
| 313 | self.directory |
| 314 | .requested_presence_ids() |
| 315 | .into_iter() |
| 316 | .filter(|user_id| { |
| 317 | data::presence_kind(&engine, user_id) |
| 318 | .is_some_and(|kind| self.directory.set_presence(user_id, kind)) |
| 319 | }) |
| 320 | .collect() |
| 321 | } |
| 322 | |
| 323 | pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) { |
| 324 | let now = Instant::now(); |
| 325 | let pushed = self.live == LiveState::Live; |
| 326 | let wanted = self.directory.stale_presence(user_ids, now, pushed); |
| 327 | if wanted.is_empty() { |
| 328 | return; |
| 329 | } |
| 330 | self.directory.mark_presence_pending(&wanted); |
| 331 | if let Some(engine) = self.engine.clone() { |
| 332 | self.directory.mark_presence_requested(&wanted, now); |
| 333 | drop(data::watch_presence(&engine, wanted.clone())); |
| 334 | let done = data::refresh_presence(&engine, wanted.clone()); |
| 335 | self.on_done(done, cx, move |state, cx| { |
| 336 | state.sync_presence(); |
| 337 | state.directory.save_presence(&state.store, &wanted); |
| 338 | state.directory.settle_presence(&wanted); |
| 339 | cx.emit(AppEvent::Directory); |
| 340 | cx.notify(); |
| 341 | }); |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | pub fn move_chat( |
| 346 | &mut self, |
| 347 | conversation_id: &str, |
| 348 | folder_id: Option<&str>, |
| 349 | cx: &mut Context<Self>, |
| 350 | ) { |
| 351 | if self.mode.read_only { |
| 352 | return; |
| 353 | } |
| 354 | let previous_folder = self |
| 355 | .directory |
| 356 | .folder_of(conversation_id) |
| 357 | .map(|folder| folder.id.clone()); |
| 358 | self.directory.assign(conversation_id, folder_id); |
| 359 | if let Some(engine) = self.engine.clone() { |
| 360 | let previous = previous_folder.clone(); |
| 361 | let done = match (folder_id, previous.as_deref()) { |
| 362 | (Some(folder_id), _) => { |
| 363 | Some(data::move_to_folder(&engine, conversation_id, folder_id)) |
| 364 | } |
| 365 | (None, Some(previous)) => { |
| 366 | Some(data::remove_from_folder(&engine, conversation_id, previous)) |
| 367 | } |
| 368 | (None, None) => None, |
| 369 | }; |
| 370 | if let Some(done) = done { |
| 371 | self.on_done(done, cx, |state, cx| { |
| 372 | state.reload_directory(); |
| 373 | cx.emit(AppEvent::Sidebar); |
| 374 | cx.notify(); |
| 375 | }); |
| 376 | } |
| 377 | } |
| 378 | cx.emit(AppEvent::Sidebar); |
| 379 | cx.notify(); |
| 380 | } |
| 381 | |
| 382 | pub fn pin_chat(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 383 | let favorites = self.directory.favorites().map(|folder| folder.id.clone()); |
| 384 | self.move_chat(conversation_id, favorites.as_deref(), cx); |
| 385 | } |
| 386 | |
| 387 | pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 388 | if self.keeps_unread(conversation_id) { |
| 389 | self.keep_unread = None; |
| 390 | } |
| 391 | if self.mode.demo { |
| 392 | if let Some(chat) = self |
| 393 | .sidebar |
| 394 | .chats |
| 395 | .iter() |
| 396 | .find(|chat| chat.id == conversation_id) |
| 397 | { |
| 398 | let mut read = chat.clone(); |
| 399 | read.unread = false; |
| 400 | let _ = self.store.upsert_chats(&[read]); |
| 401 | self.reload_sidebar(cx); |
| 402 | } |
| 403 | return; |
| 404 | } |
| 405 | if self.mode.read_only { |
| 406 | return; |
| 407 | } |
| 408 | if let Some(engine) = self.engine.clone() { |
| 409 | let _ = self |
| 410 | .store |
| 411 | .mark_chat_read(conversation_id, chrono::Utc::now()); |
| 412 | self.reload_sidebar(cx); |
| 413 | let conversation_id = conversation_id.to_owned(); |
| 414 | drop(crate::runtime::spawn(async move { |
| 415 | engine.mark_read(&conversation_id).await |
| 416 | })); |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | pub fn start_new_chat(&mut self, cx: &mut Context<Self>) { |
| 421 | self.new_chat = true; |
| 422 | cx.emit(AppEvent::Selection); |
| 423 | cx.notify(); |
| 424 | } |
| 425 | |
| 426 | pub fn close_new_chat(&mut self, cx: &mut Context<Self>) { |
| 427 | if !self.new_chat { |
| 428 | return; |
| 429 | } |
| 430 | self.new_chat = false; |
| 431 | cx.emit(AppEvent::Selection); |
| 432 | cx.notify(); |
| 433 | } |
| 434 | |
| 435 | pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) { |
| 436 | let was_drafting = std::mem::take(&mut self.new_chat); |
| 437 | if !was_drafting && self.selection.as_ref() == Some(&selection) { |
| 438 | return; |
| 439 | } |
| 440 | self.selection = Some(selection); |
| 441 | self.keep_unread = None; |
| 442 | cx.emit(AppEvent::Selection); |
| 443 | cx.notify(); |
| 444 | } |
| 445 | |
| 446 | pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) { |
| 447 | if let Ok(sidebar) = self.store.sidebar() { |
| 448 | self.sidebar = sidebar; |
| 449 | self.apply_bot_titles(); |
| 450 | } |
| 451 | if !self.mode.demo { |
| 452 | self.reload_directory(); |
| 453 | } |
| 454 | cx.emit(AppEvent::Sidebar); |
| 455 | cx.notify(); |
| 456 | } |
| 457 | |
| 458 | pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) { |
| 459 | match event { |
| 460 | BackendEvent::Connection(connection) => { |
| 461 | self.connection = connection; |
| 462 | cx.emit(AppEvent::Status); |
| 463 | } |
| 464 | BackendEvent::Engine(engine) => { |
| 465 | self.engine = Some(engine); |
| 466 | let waiting = self.directory.waiting_presence_ids(); |
| 467 | self.request_presence(waiting, cx); |
| 468 | cx.emit(AppEvent::Status); |
| 469 | } |
| 470 | BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx), |
| 471 | BackendEvent::Core( |
| 472 | CoreEvent::MessagesChanged { conversation_id } |
| 473 | | CoreEvent::ReceiptsChanged { conversation_id }, |
| 474 | ) => { |
| 475 | cx.emit(AppEvent::Messages(conversation_id)); |
| 476 | } |
| 477 | BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => { |
| 478 | if let Some(engine) = &self.engine { |
| 479 | for key in &keys { |
| 480 | let image = ImageRef { |
| 481 | id: String::new(), |
| 482 | url: key.clone(), |
| 483 | width: None, |
| 484 | height: None, |
| 485 | }; |
| 486 | if let Some(path) = engine.image_path(&image) { |
| 487 | self.directory.set_image(key, &path); |
| 488 | } |
| 489 | } |
| 490 | } |
| 491 | cx.emit(AppEvent::Images(keys)); |
| 492 | } |
| 493 | BackendEvent::Core(CoreEvent::PresenceChanged) => { |
| 494 | let changed = self.sync_presence(); |
| 495 | self.directory.save_presence(&self.store, &changed); |
| 496 | cx.emit(AppEvent::Directory); |
| 497 | cx.notify(); |
| 498 | } |
| 499 | BackendEvent::Core(_) => { |
| 500 | if !self.mode.demo { |
| 501 | self.reload_directory(); |
| 502 | } |
| 503 | cx.emit(AppEvent::Directory); |
| 504 | } |
| 505 | BackendEvent::Live(live) => { |
| 506 | self.live = live; |
| 507 | cx.emit(AppEvent::Status); |
| 508 | } |
| 509 | BackendEvent::Favorites(ids) => { |
| 510 | self.favorite_ids = ids; |
| 511 | if !self.mode.demo { |
| 512 | self.reload_directory(); |
| 513 | } |
| 514 | cx.emit(AppEvent::Sidebar); |
| 515 | } |
| 516 | BackendEvent::Synced(time) => { |
| 517 | self.last_sync = Some(time); |
| 518 | cx.emit(AppEvent::Status); |
| 519 | } |
| 520 | } |
| 521 | cx.notify(); |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | #[cfg(test)] |
| 526 | mod tests { |
| 527 | use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord}; |
| 528 | |
| 529 | use super::{Selection, chat_title, selection_title}; |
| 530 | use store::Sidebar; |
| 531 | |
| 532 | fn chat(id: &str, title: &str, unread: bool) -> ChatRecord { |
| 533 | ChatRecord { |
| 534 | id: id.into(), |
| 535 | kind: "group".into(), |
| 536 | title: title.into(), |
| 537 | member_summary: "Member".into(), |
| 538 | last_message_at: None, |
| 539 | last_read_at: None, |
| 540 | unread, |
| 541 | ..Default::default() |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | fn sidebar() -> Sidebar { |
| 546 | Sidebar { |
| 547 | chats: vec![chat("c1", "First", true), chat("c2", "", false)], |
| 548 | teams: vec![SidebarTeam { |
| 549 | team: TeamRecord { |
| 550 | id: "t".into(), |
| 551 | name: "Team".into(), |
| 552 | }, |
| 553 | channels: vec![ChannelRecord { |
| 554 | id: "ch".into(), |
| 555 | team_id: "t".into(), |
| 556 | name: "General".into(), |
| 557 | membership_type: None, |
| 558 | last_message_at: None, |
| 559 | unread: false, |
| 560 | }], |
| 561 | hidden: false, |
| 562 | hidden_channel_ids: Vec::new(), |
| 563 | }], |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | #[test] |
| 568 | fn empty_chat_title_falls_back_to_members() { |
| 569 | assert_eq!(chat_title(&sidebar().chats[1]), "Member"); |
| 570 | } |
| 571 | |
| 572 | #[test] |
| 573 | fn selection_titles() { |
| 574 | assert_eq!( |
| 575 | selection_title(&sidebar(), &Selection::Channel("ch".into())), |
| 576 | "Team / General" |
| 577 | ); |
| 578 | assert_eq!( |
| 579 | selection_title(&sidebar(), &Selection::Chat("c1".into())), |
| 580 | "First" |
| 581 | ); |
| 582 | } |
| 583 | } |