| 1 | use std::cell::RefCell; |
| 2 | use std::collections::HashMap; |
| 3 | use std::rc::Rc; |
| 4 | use std::time::{Duration, Instant}; |
| 5 | |
| 6 | use chrono::{DateTime, Local, Offset, Utc}; |
| 7 | use gpui_kit::assets::IconName; |
| 8 | use gpui_kit::component::{ |
| 9 | button::{Button, ButtonVariants as _}, |
| 10 | h_flex, |
| 11 | message_scroller::{MessageScroller, MessageScrollerState}, |
| 12 | v_flex, |
| 13 | }; |
| 14 | use gpui_kit::prelude::FluentBuilder as _; |
| 15 | use gpui_kit::*; |
| 16 | use store::MessageRecord; |
| 17 | use teams_core::ImageRef; |
| 18 | |
| 19 | use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence}; |
| 20 | use super::composer::{Composer, ComposerEvent, Outgoing, ReplyPreview}; |
| 21 | use super::message_row::{RowActions, render_message_row, render_skeleton_row}; |
| 22 | use super::widgets::icon; |
| 23 | use crate::app_state::{AppEvent, AppState, Selection, selection_title}; |
| 24 | use crate::data::{is_one_on_one, others}; |
| 25 | use crate::render::Block; |
| 26 | use crate::render::blocks::Inline; |
| 27 | use crate::rows::{ |
| 28 | Delivery, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series, |
| 29 | changed_indices, diff_keys, flat_rows, placeholder_rows, reply_excerpt, thread_list_rows, |
| 30 | thread_rows, trailing_skeleton, |
| 31 | }; |
| 32 | use crate::read_state::{ReadTrigger, plan_read}; |
| 33 | use crate::runtime; |
| 34 | use crate::sidebar_model::{AvatarSpec, Face}; |
| 35 | use crate::theme; |
| 36 | |
| 37 | const CHAT_OPEN_LIMIT: usize = 60; |
| 38 | const CHANNEL_OPEN_LIMIT: usize = 300; |
| 39 | const GROWTH_HEADROOM: usize = 20; |
| 40 | const META_USER_ID: &str = "me_user_id"; |
| 41 | const PENDING_KEY_PREFIX: &str = "pending-"; |
| 42 | const MAX_NOTICE_CHARS: usize = 140; |
| 43 | const JUMP_SCAN_LIMIT: usize = 5000; |
| 44 | const JUMP_CONTEXT_MESSAGES: usize = 12; |
| 45 | const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2); |
| 46 | const PROGRESS_DELAY: Duration = Duration::from_millis(400); |
| 47 | const SKELETON_DELAY: Duration = Duration::from_millis(1000); |
| 48 | const SLOW_AFTER: Duration = Duration::from_secs(8); |
| 49 | const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500); |
| 50 | const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400); |
| 51 | const PROGRESS_BAR_WIDTH: f32 = 0.35; |
| 52 | |
| 53 | actions!(teams, [ReplyToHovered]); |
| 54 | |
| 55 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 56 | enum ViewMode { |
| 57 | Flat, |
| 58 | ThreadList, |
| 59 | Thread(String), |
| 60 | } |
| 61 | |
| 62 | #[derive(Default)] |
| 63 | struct SyncProgress { |
| 64 | messages: bool, |
| 65 | receipts: bool, |
| 66 | empty_cache: bool, |
| 67 | newest_cached: Option<DateTime<Utc>>, |
| 68 | shown_at: Option<Instant>, |
| 69 | trailing_skeleton: bool, |
| 70 | slow: bool, |
| 71 | failed: bool, |
| 72 | } |
| 73 | |
| 74 | impl SyncProgress { |
| 75 | fn running(&self) -> bool { |
| 76 | self.messages || self.receipts |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | struct Current { |
| 81 | selection: Selection, |
| 82 | title: String, |
| 83 | mode: ViewMode, |
| 84 | loaded_limit: usize, |
| 85 | loaded_count: usize, |
| 86 | has_older: bool, |
| 87 | loading_older: bool, |
| 88 | older_blocked: bool, |
| 89 | fetched: bool, |
| 90 | first_unread: Option<String>, |
| 91 | sync: SyncProgress, |
| 92 | } |
| 93 | |
| 94 | pub struct ConversationView { |
| 95 | app: Entity<AppState>, |
| 96 | scroller: Entity<MessageScrollerState>, |
| 97 | composer: Entity<Composer>, |
| 98 | rows: Rc<RefCell<Vec<Row>>>, |
| 99 | current: Option<Current>, |
| 100 | pending: Vec<MessageRow>, |
| 101 | pending_counter: usize, |
| 102 | pending_outgoing: HashMap<String, Outgoing>, |
| 103 | hovered_message: Option<String>, |
| 104 | highlighted_message: Option<String>, |
| 105 | notice: Option<String>, |
| 106 | sync_generation: u64, |
| 107 | window_active: bool, |
| 108 | _subscriptions: Vec<Subscription>, |
| 109 | } |
| 110 | |
| 111 | fn open_limit(selection: &Selection) -> usize { |
| 112 | match selection { |
| 113 | Selection::Chat(_) => CHAT_OPEN_LIMIT, |
| 114 | Selection::Channel(_) => CHANNEL_OPEN_LIMIT, |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | fn short_error(error: &dyn std::fmt::Display) -> String { |
| 119 | error.to_string().chars().take(MAX_NOTICE_CHARS).collect() |
| 120 | } |
| 121 | |
| 122 | impl ConversationView { |
| 123 | pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self { |
| 124 | let scroller = cx.new(|cx| MessageScrollerState::new(0, cx)); |
| 125 | let composer = cx.new(|cx| Composer::new(app.clone(), window, cx)); |
| 126 | let subscriptions = vec![ |
| 127 | cx.subscribe_in(&app, window, Self::on_app_event), |
| 128 | cx.subscribe_in(&composer, window, Self::on_composer_event), |
| 129 | cx.observe_window_activation(window, Self::on_window_activation), |
| 130 | ]; |
| 131 | let mut view = ConversationView { |
| 132 | app, |
| 133 | scroller, |
| 134 | composer, |
| 135 | rows: Rc::new(RefCell::new(Vec::new())), |
| 136 | current: None, |
| 137 | pending: Vec::new(), |
| 138 | pending_counter: 0, |
| 139 | pending_outgoing: HashMap::new(), |
| 140 | hovered_message: None, |
| 141 | highlighted_message: None, |
| 142 | notice: None, |
| 143 | sync_generation: 0, |
| 144 | window_active: window.is_window_active(), |
| 145 | _subscriptions: subscriptions, |
| 146 | }; |
| 147 | if let Some(selection) = view.app.read(cx).selection.clone() { |
| 148 | view.open(selection, window, cx); |
| 149 | } |
| 150 | view |
| 151 | } |
| 152 | |
| 153 | #[cfg_attr(not(windows), allow(dead_code))] |
| 154 | pub fn composer_is_empty(&self, cx: &App) -> bool { |
| 155 | self.composer.read(cx).is_empty(cx) |
| 156 | } |
| 157 | |
| 158 | #[cfg_attr(not(windows), allow(dead_code))] |
| 159 | pub fn send_in_flight(&self) -> bool { |
| 160 | self.pending |
| 161 | .iter() |
| 162 | .any(|row| matches!(row.delivery, Delivery::Sending)) |
| 163 | } |
| 164 | |
| 165 | fn on_window_activation(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 166 | self.window_active = window.is_window_active(); |
| 167 | self.mark_read(ReadTrigger::Activation, cx); |
| 168 | } |
| 169 | |
| 170 | fn on_app_event( |
| 171 | &mut self, |
| 172 | _: &Entity<AppState>, |
| 173 | event: &AppEvent, |
| 174 | window: &mut Window, |
| 175 | cx: &mut Context<Self>, |
| 176 | ) { |
| 177 | match event { |
| 178 | AppEvent::Selection => { |
| 179 | if let Some(selection) = self.app.read(cx).selection.clone() { |
| 180 | self.open(selection, window, cx); |
| 181 | } |
| 182 | } |
| 183 | AppEvent::Messages(conversation_id) => { |
| 184 | let is_current = self |
| 185 | .current |
| 186 | .as_ref() |
| 187 | .is_some_and(|current| current.selection.conversation_id() == conversation_id); |
| 188 | if is_current { |
| 189 | self.rebuild(false, cx); |
| 190 | self.mark_read(ReadTrigger::Incoming, cx); |
| 191 | } |
| 192 | } |
| 193 | AppEvent::Images(keys) => self.remeasure_images(keys, cx), |
| 194 | AppEvent::Jump => self.apply_pending_jump(cx), |
| 195 | AppEvent::Status => { |
| 196 | if let Some(current) = self.current.as_mut() |
| 197 | && current.sync.failed |
| 198 | { |
| 199 | current.fetched = false; |
| 200 | } |
| 201 | self.start_fetch(cx) |
| 202 | } |
| 203 | AppEvent::Directory => cx.notify(), |
| 204 | AppEvent::Sidebar => { |
| 205 | self.mark_read(ReadTrigger::Incoming, cx); |
| 206 | if let Some(current) = self.current.as_mut() { |
| 207 | let title = selection_title(&self.app.read(cx).sidebar, ¤t.selection); |
| 208 | if current.title != title { |
| 209 | current.title = title.clone(); |
| 210 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 211 | self.composer.update(cx, |composer, cx| { |
| 212 | composer.set_conversation(&conversation_id, &title, window, cx) |
| 213 | }); |
| 214 | cx.notify(); |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | fn on_composer_event( |
| 222 | &mut self, |
| 223 | _: &Entity<Composer>, |
| 224 | event: &ComposerEvent, |
| 225 | window: &mut Window, |
| 226 | cx: &mut Context<Self>, |
| 227 | ) { |
| 228 | let ComposerEvent::Submit(outgoing) = event; |
| 229 | self.send(outgoing.clone(), window, cx); |
| 230 | } |
| 231 | |
| 232 | fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) { |
| 233 | let title = selection_title(&self.app.read(cx).sidebar, &selection); |
| 234 | let mode = match selection { |
| 235 | Selection::Chat(_) => ViewMode::Flat, |
| 236 | Selection::Channel(_) => ViewMode::ThreadList, |
| 237 | }; |
| 238 | let first_unread = self.first_unread_id(&selection, cx); |
| 239 | self.current = Some(Current { |
| 240 | loaded_limit: open_limit(&selection), |
| 241 | selection, |
| 242 | title, |
| 243 | mode, |
| 244 | loaded_count: 0, |
| 245 | has_older: false, |
| 246 | loading_older: false, |
| 247 | older_blocked: false, |
| 248 | fetched: false, |
| 249 | first_unread, |
| 250 | sync: SyncProgress::default(), |
| 251 | }); |
| 252 | self.sync_generation += 1; |
| 253 | self.pending.clear(); |
| 254 | self.notice = None; |
| 255 | self.rebuild(true, cx); |
| 256 | self.start_fetch(cx); |
| 257 | self.mark_read(ReadTrigger::Open, cx); |
| 258 | let target = self |
| 259 | .current |
| 260 | .as_ref() |
| 261 | .map(|current| { |
| 262 | ( |
| 263 | current.selection.conversation_id().to_owned(), |
| 264 | current.title.clone(), |
| 265 | ) |
| 266 | }) |
| 267 | .unwrap_or_default(); |
| 268 | self.composer.update(cx, |composer, cx| { |
| 269 | composer.set_conversation(&target.0, &target.1, window, cx); |
| 270 | composer.focus(window, cx); |
| 271 | }); |
| 272 | self.hovered_message = None; |
| 273 | self.apply_pending_jump(cx); |
| 274 | } |
| 275 | |
| 276 | fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) { |
| 277 | let indices: Vec<usize> = self |
| 278 | .rows |
| 279 | .borrow() |
| 280 | .iter() |
| 281 | .enumerate() |
| 282 | .filter_map(|(index, row)| match row { |
| 283 | Row::Message(message) |
| 284 | if message.images.iter().any(|image| keys.contains(&image.url)) => |
| 285 | { |
| 286 | Some(index) |
| 287 | } |
| 288 | _ => None, |
| 289 | }) |
| 290 | .collect(); |
| 291 | self.scroller.update(cx, |scroller, cx| { |
| 292 | for index in indices { |
| 293 | scroller.remeasure_items(index..index + 1, cx); |
| 294 | } |
| 295 | }); |
| 296 | cx.notify(); |
| 297 | } |
| 298 | |
| 299 | fn apply_pending_jump(&mut self, cx: &mut Context<Self>) { |
| 300 | let Some(conversation_id) = self |
| 301 | .current |
| 302 | .as_ref() |
| 303 | .map(|current| current.selection.conversation_id().to_owned()) |
| 304 | else { |
| 305 | return; |
| 306 | }; |
| 307 | let jump = self |
| 308 | .app |
| 309 | .update(cx, |state, _| match state.pending_jump.take() { |
| 310 | Some((target, message_id)) if target == conversation_id => Some(message_id), |
| 311 | other => { |
| 312 | state.pending_jump = other; |
| 313 | None |
| 314 | } |
| 315 | }); |
| 316 | if let Some(message_id) = jump { |
| 317 | self.jump_to_message(&conversation_id, &message_id, cx); |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) { |
| 322 | let store = self.app.read(cx).store.clone(); |
| 323 | let Some(record) = store |
| 324 | .messages_by_id(conversation_id, &[message_id.to_owned()]) |
| 325 | .ok() |
| 326 | .and_then(|mut found| found.remove(message_id)) |
| 327 | else { |
| 328 | return; |
| 329 | }; |
| 330 | let messages_from_target = store |
| 331 | .messages(conversation_id, None, JUMP_SCAN_LIMIT) |
| 332 | .ok() |
| 333 | .and_then(|all| { |
| 334 | all.iter() |
| 335 | .position(|candidate| candidate.message_id == message_id) |
| 336 | .map(|position| all.len() - position) |
| 337 | }) |
| 338 | .unwrap_or_default(); |
| 339 | let row_key = record |
| 340 | .reply_to_id |
| 341 | .clone() |
| 342 | .unwrap_or_else(|| message_id.to_owned()); |
| 343 | let Some(current) = self.current.as_mut() else { |
| 344 | return; |
| 345 | }; |
| 346 | current.loaded_limit = current |
| 347 | .loaded_limit |
| 348 | .max(messages_from_target + JUMP_CONTEXT_MESSAGES); |
| 349 | current.first_unread = None; |
| 350 | if matches!(current.selection, Selection::Channel(_)) { |
| 351 | current.mode = match record.reply_to_id { |
| 352 | Some(root_id) => ViewMode::Thread(root_id), |
| 353 | None => ViewMode::ThreadList, |
| 354 | }; |
| 355 | } |
| 356 | let target_key = if matches!(current.mode, ViewMode::Thread(_)) { |
| 357 | message_id.to_owned() |
| 358 | } else { |
| 359 | row_key |
| 360 | }; |
| 361 | self.pending.clear(); |
| 362 | self.rebuild(true, cx); |
| 363 | let index = self |
| 364 | .rows |
| 365 | .borrow() |
| 366 | .iter() |
| 367 | .position(|row| row.key() == target_key); |
| 368 | if let Some(index) = index { |
| 369 | self.scroller |
| 370 | .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx)); |
| 371 | self.highlight(target_key, cx); |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | fn highlight(&mut self, key: String, cx: &mut Context<Self>) { |
| 376 | self.highlighted_message = Some(key.clone()); |
| 377 | cx.notify(); |
| 378 | cx.spawn(async move |this, cx| { |
| 379 | cx.background_executor().timer(HIGHLIGHT_DURATION).await; |
| 380 | this.update(cx, |this, cx| { |
| 381 | if this.highlighted_message.as_deref() == Some(key.as_str()) { |
| 382 | this.highlighted_message = None; |
| 383 | cx.notify(); |
| 384 | } |
| 385 | }) |
| 386 | .ok(); |
| 387 | }) |
| 388 | .detach(); |
| 389 | } |
| 390 | |
| 391 | pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 392 | self.composer |
| 393 | .update(cx, |composer, cx| composer.set_text(text, window, cx)); |
| 394 | self.composer |
| 395 | .update(cx, |composer, cx| composer.focus(window, cx)); |
| 396 | } |
| 397 | |
| 398 | pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 399 | let key = self.rows.borrow().iter().rev().find_map(|row| match row { |
| 400 | Row::Message(message) if !message.own => Some(message.key.clone()), |
| 401 | _ => None, |
| 402 | }); |
| 403 | if let Some(key) = key { |
| 404 | self.begin_reply(&key, window, cx); |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 409 | if let Some(message_id) = self.hovered_message.clone() { |
| 410 | self.begin_reply(&message_id, window, cx); |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 415 | let Some(conversation_id) = self |
| 416 | .current |
| 417 | .as_ref() |
| 418 | .map(|current| current.selection.conversation_id().to_owned()) |
| 419 | else { |
| 420 | return; |
| 421 | }; |
| 422 | let store = self.app.read(cx).store.clone(); |
| 423 | let record = store |
| 424 | .messages_by_id(&conversation_id, &[message_id.to_owned()]) |
| 425 | .ok() |
| 426 | .and_then(|mut found| found.remove(message_id)) |
| 427 | .filter(|record| !record.deleted); |
| 428 | let Some(record) = record else { |
| 429 | return; |
| 430 | }; |
| 431 | let preview = ReplyPreview { |
| 432 | message_id: record.message_id.clone(), |
| 433 | author: record |
| 434 | .sender_name |
| 435 | .clone() |
| 436 | .unwrap_or_else(|| "Unknown".to_owned()), |
| 437 | excerpt: reply_excerpt(&record), |
| 438 | }; |
| 439 | self.composer.update(cx, |composer, cx| { |
| 440 | composer.set_reply(Some(preview), cx); |
| 441 | composer.focus(window, cx); |
| 442 | }); |
| 443 | } |
| 444 | |
| 445 | fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> { |
| 446 | let Selection::Chat(chat_id) = selection else { |
| 447 | return None; |
| 448 | }; |
| 449 | let state = self.app.read(cx); |
| 450 | if state.mode.demo { |
| 451 | return crate::demo::first_unread(chat_id); |
| 452 | } |
| 453 | state.engine.as_ref()?.first_unread_message_id(chat_id) |
| 454 | } |
| 455 | |
| 456 | fn row_context(&self, cx: &App) -> RowContext { |
| 457 | let now = Local::now(); |
| 458 | RowContext { |
| 459 | offset: now.offset().fix(), |
| 460 | today: now.date_naive(), |
| 461 | my_user_id: self.app.read(cx).store.meta(META_USER_ID).ok().flatten(), |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | fn start_info(&self, cx: &App) -> Option<StartInfo> { |
| 466 | let current = self.current.as_ref()?; |
| 467 | let app = self.app.read(cx); |
| 468 | let user_id = match ¤t.selection { |
| 469 | Selection::Chat(chat_id) => app |
| 470 | .sidebar |
| 471 | .chats |
| 472 | .iter() |
| 473 | .find(|chat| &chat.id == chat_id) |
| 474 | .filter(|chat| is_one_on_one(chat)) |
| 475 | .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next()) |
| 476 | .and_then(|(user_id, _)| user_id), |
| 477 | Selection::Channel(_) => None, |
| 478 | }; |
| 479 | Some(StartInfo { |
| 480 | title: current.title.clone(), |
| 481 | user_id, |
| 482 | }) |
| 483 | } |
| 484 | |
| 485 | fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) { |
| 486 | let Some(current) = self.current.as_ref() else { |
| 487 | self.apply_rows(Vec::new(), true, cx); |
| 488 | return; |
| 489 | }; |
| 490 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 491 | let limit = if reset { |
| 492 | current.loaded_limit |
| 493 | } else { |
| 494 | current |
| 495 | .loaded_limit |
| 496 | .max(current.loaded_count + GROWTH_HEADROOM) |
| 497 | }; |
| 498 | let store = self.app.read(cx).store.clone(); |
| 499 | let records: Vec<MessageRecord> = store |
| 500 | .messages(&conversation_id, None, limit) |
| 501 | .unwrap_or_default(); |
| 502 | let sync_has_more = store |
| 503 | .sync_state(&conversation_id) |
| 504 | .ok() |
| 505 | .flatten() |
| 506 | .is_none_or(|state| state.has_more); |
| 507 | let context = self.row_context(cx); |
| 508 | let can_load_older = self.app.read(cx).engine.is_some(); |
| 509 | let start = self.start_info(cx); |
| 510 | let current = self.current.as_mut().expect("checked above"); |
| 511 | let first_unread = current.first_unread.clone(); |
| 512 | current.loaded_limit = limit; |
| 513 | current.loaded_count = records.len(); |
| 514 | let has_older = sync_has_more && !current.older_blocked && can_load_older; |
| 515 | let placeholders = current.sync.messages |
| 516 | && records.is_empty() |
| 517 | && !matches!(current.mode, ViewMode::Thread(_)); |
| 518 | let trailing = current.sync.trailing_skeleton && current.mode == ViewMode::Flat; |
| 519 | let mut rows = match ¤t.mode { |
| 520 | _ if placeholders => { |
| 521 | current.has_older = false; |
| 522 | placeholder_rows() |
| 523 | } |
| 524 | ViewMode::Flat => { |
| 525 | current.has_older = has_older; |
| 526 | let mut rows = flat_rows(&records, &context, has_older); |
| 527 | if !has_older && let Some(start) = start { |
| 528 | rows.insert(0, Row::Start(start)); |
| 529 | } |
| 530 | rows |
| 531 | } |
| 532 | ViewMode::ThreadList => { |
| 533 | current.has_older = has_older; |
| 534 | thread_list_rows(&records, &context, has_older) |
| 535 | } |
| 536 | ViewMode::Thread(root_id) => { |
| 537 | current.has_older = false; |
| 538 | thread_rows(&records, root_id, &context) |
| 539 | } |
| 540 | }; |
| 541 | if trailing && !placeholders { |
| 542 | rows.push(trailing_skeleton()); |
| 543 | } |
| 544 | rows.extend( |
| 545 | self.pending |
| 546 | .iter() |
| 547 | .cloned() |
| 548 | .map(|row| Row::Message(Box::new(row))), |
| 549 | ); |
| 550 | let receipts = self.receipts(&records, cx); |
| 551 | for row in rows.iter_mut() { |
| 552 | if let Row::Message(message) = row |
| 553 | && message.own |
| 554 | { |
| 555 | message.receipt = receipts.get(&message.key).copied().unwrap_or_default(); |
| 556 | } |
| 557 | } |
| 558 | if let Some(unread_id) = &first_unread { |
| 559 | for row in rows.iter_mut() { |
| 560 | if let Row::Message(message) = row |
| 561 | && &message.key == unread_id |
| 562 | { |
| 563 | message.new_marker = true; |
| 564 | } |
| 565 | } |
| 566 | } |
| 567 | assign_series(&mut rows); |
| 568 | self.apply_rows(rows, reset, cx); |
| 569 | } |
| 570 | |
| 571 | fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) { |
| 572 | let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows); |
| 573 | let new_len = self.rows.borrow().len(); |
| 574 | if reset { |
| 575 | let marker_index = self |
| 576 | .rows |
| 577 | .borrow() |
| 578 | .iter() |
| 579 | .position(|row| matches!(row, Row::Message(message) if message.new_marker)); |
| 580 | self.scroller.update(cx, |scroller, cx| { |
| 581 | scroller.reset(new_len, cx); |
| 582 | match marker_index { |
| 583 | Some(index) if !scroller.scroll_to_item(index, cx) => { |
| 584 | scroller.scroll_to_end(cx) |
| 585 | } |
| 586 | Some(_) => {} |
| 587 | None => scroller.scroll_to_end(cx), |
| 588 | } |
| 589 | }); |
| 590 | cx.notify(); |
| 591 | return; |
| 592 | } |
| 593 | let (splice, changed) = { |
| 594 | let new_rows = self.rows.borrow(); |
| 595 | let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect(); |
| 596 | let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect(); |
| 597 | ( |
| 598 | diff_keys(&old_keys, &new_keys), |
| 599 | changed_indices(&old_rows, &new_rows), |
| 600 | ) |
| 601 | }; |
| 602 | self.scroller.update(cx, |scroller, cx| { |
| 603 | if let Some(splice) = splice |
| 604 | && !scroller.splice(splice.range, splice.count, cx) |
| 605 | { |
| 606 | scroller.reset(new_len, cx); |
| 607 | } |
| 608 | for index in changed { |
| 609 | scroller.remeasure_items(index..index + 1, cx); |
| 610 | } |
| 611 | }); |
| 612 | cx.notify(); |
| 613 | } |
| 614 | |
| 615 | fn start_fetch(&mut self, cx: &mut Context<Self>) { |
| 616 | let state = self.app.read(cx); |
| 617 | let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync); |
| 618 | if engine.is_none() && demo_sync.is_none() { |
| 619 | return; |
| 620 | } |
| 621 | let Some(current) = self.current.as_mut() else { |
| 622 | return; |
| 623 | }; |
| 624 | if current.fetched { |
| 625 | return; |
| 626 | } |
| 627 | current.fetched = true; |
| 628 | let is_chat = matches!(current.selection, Selection::Chat(_)); |
| 629 | let newest_cached = self.rows.borrow().iter().rev().find_map(|row| match row { |
| 630 | Row::Message(message) if !message.key.starts_with(PENDING_KEY_PREFIX) => { |
| 631 | Some(message.created_at) |
| 632 | } |
| 633 | _ => None, |
| 634 | }); |
| 635 | let current = self.current.as_mut().expect("checked above"); |
| 636 | if current.sync.failed { |
| 637 | self.notice = None; |
| 638 | } |
| 639 | current.sync = SyncProgress { |
| 640 | messages: true, |
| 641 | receipts: is_chat, |
| 642 | empty_cache: newest_cached.is_none(), |
| 643 | newest_cached, |
| 644 | ..SyncProgress::default() |
| 645 | }; |
| 646 | self.sync_generation += 1; |
| 647 | let generation = self.sync_generation; |
| 648 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 649 | match (engine, demo_sync) { |
| 650 | (Some(engine), _) => { |
| 651 | let receiver = |
| 652 | runtime::spawn(async move { engine.fetch_newer(&conversation_id).await }); |
| 653 | cx.spawn(async move |this, cx| { |
| 654 | let result = receiver.await; |
| 655 | this.update(cx, |this, cx| this.finish_fetch(generation, result, cx)) |
| 656 | .ok(); |
| 657 | }) |
| 658 | .detach(); |
| 659 | } |
| 660 | (None, Some(delay)) => self.simulate_sync(generation, delay, cx), |
| 661 | (None, None) => {} |
| 662 | } |
| 663 | self.schedule_progress(generation, cx); |
| 664 | self.rebuild(false, cx); |
| 665 | self.mark_read(ReadTrigger::Incoming, cx); |
| 666 | self.refresh_receipts(generation, cx); |
| 667 | } |
| 668 | |
| 669 | fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) { |
| 670 | cx.spawn(async move |this, cx| { |
| 671 | cx.background_executor().timer(delay).await; |
| 672 | this.update(cx, |this, cx| { |
| 673 | if let Some(sync) = this.sync_of(generation) { |
| 674 | sync.receipts = false; |
| 675 | } |
| 676 | this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx) |
| 677 | }) |
| 678 | .ok(); |
| 679 | }) |
| 680 | .detach(); |
| 681 | } |
| 682 | |
| 683 | fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> { |
| 684 | if generation != self.sync_generation { |
| 685 | return None; |
| 686 | } |
| 687 | self.current.as_mut().map(|current| &mut current.sync) |
| 688 | } |
| 689 | |
| 690 | fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) { |
| 691 | cx.spawn(async move |this, cx| { |
| 692 | let stages = [ |
| 693 | (PROGRESS_DELAY, Duration::ZERO), |
| 694 | (SKELETON_DELAY, PROGRESS_DELAY), |
| 695 | (SLOW_AFTER, SKELETON_DELAY), |
| 696 | ]; |
| 697 | for (stage, (at, previous)) in stages.into_iter().enumerate() { |
| 698 | cx.background_executor().timer(at - previous).await; |
| 699 | let running = this |
| 700 | .update(cx, |this, cx| this.advance_progress(generation, stage, cx)) |
| 701 | .unwrap_or(false); |
| 702 | if !running { |
| 703 | return; |
| 704 | } |
| 705 | } |
| 706 | }) |
| 707 | .detach(); |
| 708 | } |
| 709 | |
| 710 | fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool { |
| 711 | let Some(sync) = self.sync_of(generation) else { |
| 712 | return false; |
| 713 | }; |
| 714 | if !sync.running() { |
| 715 | return false; |
| 716 | } |
| 717 | match stage { |
| 718 | 0 => sync.shown_at = Some(Instant::now()), |
| 719 | 1 if sync.messages => { |
| 720 | sync.trailing_skeleton = true; |
| 721 | self.rebuild(false, cx); |
| 722 | } |
| 723 | 1 => {} |
| 724 | _ => sync.slow = true, |
| 725 | } |
| 726 | cx.notify(); |
| 727 | true |
| 728 | } |
| 729 | |
| 730 | fn finish_fetch( |
| 731 | &mut self, |
| 732 | generation: u64, |
| 733 | result: Result< |
| 734 | teams_core::Result<teams_core::Delta>, |
| 735 | tokio::sync::oneshot::error::RecvError, |
| 736 | >, |
| 737 | cx: &mut Context<Self>, |
| 738 | ) { |
| 739 | let Some(sync) = self.sync_of(generation) else { |
| 740 | return; |
| 741 | }; |
| 742 | sync.messages = false; |
| 743 | sync.trailing_skeleton = false; |
| 744 | let newest_cached = sync.newest_cached; |
| 745 | match result { |
| 746 | Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx), |
| 747 | Ok(Err(error)) => self.fail_sync(generation, short_error(&error)), |
| 748 | Err(error) => self.fail_sync(generation, short_error(&error)), |
| 749 | } |
| 750 | self.rebuild(false, cx); |
| 751 | self.settle_progress(generation, cx); |
| 752 | } |
| 753 | |
| 754 | fn fail_sync(&mut self, generation: u64, error: String) { |
| 755 | if let Some(sync) = self.sync_of(generation) { |
| 756 | sync.failed = true; |
| 757 | sync.receipts = false; |
| 758 | } |
| 759 | self.notice = Some(format!("Could not refresh: {error}")); |
| 760 | } |
| 761 | |
| 762 | fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) { |
| 763 | let Some(newest_cached) = newest_cached else { |
| 764 | return; |
| 765 | }; |
| 766 | let Some(my_user_id) = self.row_context(cx).my_user_id else { |
| 767 | return; |
| 768 | }; |
| 769 | let store = self.app.read(cx).store.clone(); |
| 770 | let Some(current) = self.current.as_mut() else { |
| 771 | return; |
| 772 | }; |
| 773 | if current.first_unread.is_some() || current.mode != ViewMode::Flat { |
| 774 | return; |
| 775 | } |
| 776 | let limit = current |
| 777 | .loaded_limit |
| 778 | .max(current.loaded_count + GROWTH_HEADROOM); |
| 779 | current.first_unread = store |
| 780 | .messages(current.selection.conversation_id(), None, limit) |
| 781 | .unwrap_or_default() |
| 782 | .into_iter() |
| 783 | .find(|record| { |
| 784 | record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id) |
| 785 | }) |
| 786 | .map(|record| record.message_id); |
| 787 | } |
| 788 | |
| 789 | fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) { |
| 790 | let Some(sync) = self.sync_of(generation) else { |
| 791 | return; |
| 792 | }; |
| 793 | if sync.running() { |
| 794 | return; |
| 795 | } |
| 796 | let remaining = sync |
| 797 | .shown_at |
| 798 | .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed())) |
| 799 | .unwrap_or_default(); |
| 800 | if remaining.is_zero() { |
| 801 | sync.shown_at = None; |
| 802 | sync.slow = false; |
| 803 | cx.notify(); |
| 804 | return; |
| 805 | } |
| 806 | cx.spawn(async move |this, cx| { |
| 807 | cx.background_executor().timer(remaining).await; |
| 808 | this.update(cx, |this, cx| { |
| 809 | if let Some(sync) = this.sync_of(generation) { |
| 810 | sync.shown_at = None; |
| 811 | sync.slow = false; |
| 812 | cx.notify(); |
| 813 | } |
| 814 | }) |
| 815 | .ok(); |
| 816 | }) |
| 817 | .detach(); |
| 818 | } |
| 819 | |
| 820 | fn retry_fetch(&mut self, cx: &mut Context<Self>) { |
| 821 | if let Some(current) = self.current.as_mut() { |
| 822 | current.fetched = false; |
| 823 | } |
| 824 | self.start_fetch(cx); |
| 825 | } |
| 826 | |
| 827 | fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> { |
| 828 | let state = self.app.read(cx); |
| 829 | let receipts_syncing = self |
| 830 | .current |
| 831 | .as_ref() |
| 832 | .is_some_and(|current| current.sync.receipts); |
| 833 | if state.mode.demo { |
| 834 | let read_ids = crate::demo::read_message_ids(records); |
| 835 | return records |
| 836 | .iter() |
| 837 | .map(|record| { |
| 838 | let receipt = if receipts_syncing { |
| 839 | Receipt::Pending |
| 840 | } else if read_ids.contains(&record.message_id) { |
| 841 | Receipt::Read |
| 842 | } else { |
| 843 | Receipt::Sent |
| 844 | }; |
| 845 | (record.message_id.clone(), receipt) |
| 846 | }) |
| 847 | .collect(); |
| 848 | } |
| 849 | let Some(engine) = state.engine.as_ref() else { |
| 850 | return HashMap::new(); |
| 851 | }; |
| 852 | let unknown = if receipts_syncing { |
| 853 | Receipt::Pending |
| 854 | } else { |
| 855 | Receipt::Hidden |
| 856 | }; |
| 857 | records |
| 858 | .iter() |
| 859 | .map(|record| { |
| 860 | let receipt = match engine.receipt_state_for(record) { |
| 861 | teams_core::ReceiptState::Read { .. } => Receipt::Read, |
| 862 | teams_core::ReceiptState::Sent => Receipt::Sent, |
| 863 | teams_core::ReceiptState::Unknown => unknown, |
| 864 | }; |
| 865 | (record.message_id.clone(), receipt) |
| 866 | }) |
| 867 | .collect() |
| 868 | } |
| 869 | |
| 870 | fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) { |
| 871 | let state = self.app.read(cx); |
| 872 | let (Some(engine), Some(Selection::Chat(chat_id))) = ( |
| 873 | state.engine.clone(), |
| 874 | self.current.as_ref().map(|c| c.selection.clone()), |
| 875 | ) else { |
| 876 | return; |
| 877 | }; |
| 878 | let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await }); |
| 879 | cx.spawn(async move |this, cx| { |
| 880 | receiver.await.ok(); |
| 881 | this.update(cx, |this, cx| { |
| 882 | let Some(sync) = this.sync_of(generation) else { |
| 883 | return; |
| 884 | }; |
| 885 | sync.receipts = false; |
| 886 | this.rebuild(false, cx); |
| 887 | this.settle_progress(generation, cx); |
| 888 | }) |
| 889 | .ok(); |
| 890 | }) |
| 891 | .detach(); |
| 892 | } |
| 893 | |
| 894 | fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) { |
| 895 | let state = self.app.read(cx); |
| 896 | let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone()) |
| 897 | else { |
| 898 | return; |
| 899 | }; |
| 900 | if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only { |
| 901 | return; |
| 902 | } |
| 903 | let unread = state |
| 904 | .sidebar |
| 905 | .chats |
| 906 | .iter() |
| 907 | .any(|chat| chat.id == chat_id && chat.unread); |
| 908 | let Some(plan) = plan_read(self.window_active, unread, trigger) else { |
| 909 | return; |
| 910 | }; |
| 911 | self.app |
| 912 | .update(cx, |state, cx| state.mark_chat_read(&chat_id, cx)); |
| 913 | if plan.clear_divider |
| 914 | && let Some(current) = self.current.as_mut() |
| 915 | && current.first_unread.take().is_some() |
| 916 | { |
| 917 | self.rebuild(false, cx); |
| 918 | } |
| 919 | } |
| 920 | |
| 921 | fn request_older(&mut self, cx: &mut Context<Self>) { |
| 922 | let Some(engine) = self.app.read(cx).engine.clone() else { |
| 923 | return; |
| 924 | }; |
| 925 | let Some(current) = self.current.as_mut() else { |
| 926 | return; |
| 927 | }; |
| 928 | if current.loading_older || current.older_blocked || !current.has_older { |
| 929 | return; |
| 930 | } |
| 931 | current.loading_older = true; |
| 932 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 933 | let task_id = conversation_id.clone(); |
| 934 | let receiver = runtime::spawn(async move { engine.load_older(&task_id).await }); |
| 935 | cx.spawn(async move |this, cx| { |
| 936 | let result = receiver.await; |
| 937 | this.update(cx, |this, cx| { |
| 938 | this.finish_older(&conversation_id, result, cx) |
| 939 | }) |
| 940 | .ok(); |
| 941 | }) |
| 942 | .detach(); |
| 943 | } |
| 944 | |
| 945 | fn finish_older( |
| 946 | &mut self, |
| 947 | conversation_id: &str, |
| 948 | result: Result< |
| 949 | teams_core::Result<Vec<MessageRecord>>, |
| 950 | tokio::sync::oneshot::error::RecvError, |
| 951 | >, |
| 952 | cx: &mut Context<Self>, |
| 953 | ) { |
| 954 | let Some(current) = self.current.as_mut() else { |
| 955 | return; |
| 956 | }; |
| 957 | if current.selection.conversation_id() != conversation_id { |
| 958 | return; |
| 959 | } |
| 960 | current.loading_older = false; |
| 961 | match result { |
| 962 | Ok(Ok(records)) if !records.is_empty() => { |
| 963 | current.loaded_limit = current.loaded_count + records.len(); |
| 964 | } |
| 965 | Ok(Ok(_)) => current.older_blocked = true, |
| 966 | Ok(Err(error)) => { |
| 967 | current.older_blocked = true; |
| 968 | self.notice = Some(format!( |
| 969 | "Could not load older messages: {}", |
| 970 | short_error(&error) |
| 971 | )); |
| 972 | } |
| 973 | Err(_) => current.older_blocked = true, |
| 974 | } |
| 975 | self.rebuild(false, cx); |
| 976 | } |
| 977 | |
| 978 | fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) { |
| 979 | if let Some(current) = self.current.as_mut() { |
| 980 | current.mode = ViewMode::Thread(root_id); |
| 981 | } |
| 982 | self.pending.clear(); |
| 983 | self.rebuild(true, cx); |
| 984 | } |
| 985 | |
| 986 | fn back_to_threads(&mut self, cx: &mut Context<Self>) { |
| 987 | if let Some(current) = self.current.as_mut() { |
| 988 | current.mode = ViewMode::ThreadList; |
| 989 | } |
| 990 | self.pending.clear(); |
| 991 | self.rebuild(true, cx); |
| 992 | } |
| 993 | |
| 994 | fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) { |
| 995 | let state = self.app.read(cx); |
| 996 | let (mode, engine) = (state.mode, state.engine.clone()); |
| 997 | let Some(current) = self.current.as_ref() else { |
| 998 | return; |
| 999 | }; |
| 1000 | let restore = |
| 1001 | |this: &mut Self, message: &str, window: &mut Window, cx: &mut Context<Self>| { |
| 1002 | this.notice = Some(message.to_owned()); |
| 1003 | this.composer |
| 1004 | .update(cx, |composer, cx| composer.restore(&outgoing, window, cx)); |
| 1005 | cx.notify(); |
| 1006 | }; |
| 1007 | if mode.read_only || mode.demo { |
| 1008 | restore(self, "Read-only mode: nothing was sent", window, cx); |
| 1009 | return; |
| 1010 | } |
| 1011 | let Some(engine) = engine else { |
| 1012 | restore(self, "Not connected yet: nothing was sent", window, cx); |
| 1013 | return; |
| 1014 | }; |
| 1015 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 1016 | let view_mode = current.mode.clone(); |
| 1017 | self.pending_counter += 1; |
| 1018 | let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter); |
| 1019 | let my_user_id = self.row_context(cx).my_user_id; |
| 1020 | self.pending_outgoing.insert(key.clone(), outgoing.clone()); |
| 1021 | self.pending.push(MessageRow { |
| 1022 | key: key.clone(), |
| 1023 | author: "You".to_owned(), |
| 1024 | sender_id: my_user_id, |
| 1025 | created_at: Utc::now(), |
| 1026 | series: Series::default(), |
| 1027 | card: false, |
| 1028 | time: chrono::Local::now().format("%H:%M").to_string(), |
| 1029 | day_header: None, |
| 1030 | blocks: vec![Block::Paragraph(Inline::plain(&outgoing.text))], |
| 1031 | edited: false, |
| 1032 | deleted: false, |
| 1033 | reactions: Vec::new(), |
| 1034 | images: Vec::new(), |
| 1035 | files: Vec::new(), |
| 1036 | reply_count: None, |
| 1037 | new_marker: false, |
| 1038 | reply_faces: Vec::new(), |
| 1039 | last_reply_time: None, |
| 1040 | open_thread: None, |
| 1041 | is_reply: false, |
| 1042 | delivery: Delivery::Sending, |
| 1043 | receipt: Receipt::Hidden, |
| 1044 | own: true, |
| 1045 | }); |
| 1046 | self.notice = None; |
| 1047 | self.rebuild(false, cx); |
| 1048 | self.scroller |
| 1049 | .update(cx, |scroller, cx| scroller.scroll_to_end(cx)); |
| 1050 | |
| 1051 | let sent = outgoing.clone(); |
| 1052 | let receiver = runtime::spawn(async move { |
| 1053 | let Outgoing { |
| 1054 | text, |
| 1055 | mentions, |
| 1056 | reply, |
| 1057 | } = &sent; |
| 1058 | match (&view_mode, reply) { |
| 1059 | (_, Some(reply)) => { |
| 1060 | engine |
| 1061 | .reply_to_with_mentions(&conversation_id, &reply.message_id, text, mentions) |
| 1062 | .await |
| 1063 | } |
| 1064 | (ViewMode::Flat, None) => { |
| 1065 | engine |
| 1066 | .send_message_with_mentions(&conversation_id, text, None, mentions) |
| 1067 | .await |
| 1068 | } |
| 1069 | (ViewMode::ThreadList, None) => { |
| 1070 | engine |
| 1071 | .post_to_channel_with_mentions(&conversation_id, text, None, mentions) |
| 1072 | .await |
| 1073 | } |
| 1074 | (ViewMode::Thread(root_id), None) => { |
| 1075 | engine |
| 1076 | .send_message_with_mentions(&conversation_id, text, Some(root_id), mentions) |
| 1077 | .await |
| 1078 | } |
| 1079 | } |
| 1080 | .map(|_| ()) |
| 1081 | }); |
| 1082 | cx.spawn_in(window, async move |this, cx| { |
| 1083 | let result = receiver.await; |
| 1084 | this.update_in(cx, |this, window, cx| { |
| 1085 | this.finish_send(&key, result, window, cx) |
| 1086 | }) |
| 1087 | .ok(); |
| 1088 | }) |
| 1089 | .detach(); |
| 1090 | } |
| 1091 | |
| 1092 | fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 1093 | let Some(outgoing) = self.pending_outgoing.remove(key) else { |
| 1094 | return; |
| 1095 | }; |
| 1096 | self.pending.retain(|row| row.key != key); |
| 1097 | self.send(outgoing, window, cx); |
| 1098 | } |
| 1099 | |
| 1100 | fn finish_send( |
| 1101 | &mut self, |
| 1102 | key: &str, |
| 1103 | result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>, |
| 1104 | window: &mut Window, |
| 1105 | cx: &mut Context<Self>, |
| 1106 | ) { |
| 1107 | let failure = match result { |
| 1108 | Ok(Ok(())) => None, |
| 1109 | Ok(Err(error)) => Some(short_error(&error)), |
| 1110 | Err(error) => Some(short_error(&error)), |
| 1111 | }; |
| 1112 | match failure { |
| 1113 | None => { |
| 1114 | self.pending.retain(|row| row.key != key); |
| 1115 | self.pending_outgoing.remove(key); |
| 1116 | } |
| 1117 | Some(error) => { |
| 1118 | if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) { |
| 1119 | row.delivery = Delivery::Failed(error.clone()); |
| 1120 | } |
| 1121 | self.notice = Some(format!("Not sent: {error}")); |
| 1122 | if self.composer.read(cx).is_empty(cx) |
| 1123 | && let Some(outgoing) = self.pending_outgoing.get(key).cloned() |
| 1124 | { |
| 1125 | self.composer |
| 1126 | .update(cx, |composer, cx| composer.restore(&outgoing, window, cx)); |
| 1127 | } |
| 1128 | } |
| 1129 | } |
| 1130 | self.rebuild(false, cx); |
| 1131 | } |
| 1132 | |
| 1133 | fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement { |
| 1134 | let app = self.app.read(cx); |
| 1135 | let directory = &app.directory; |
| 1136 | let me = directory.me.as_ref(); |
| 1137 | let mut lead: Option<AnyElement> = None; |
| 1138 | let mut subline = String::new(); |
| 1139 | let mut stack: Option<Div> = None; |
| 1140 | match ¤t.selection { |
| 1141 | Selection::Chat(chat_id) => { |
| 1142 | if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) { |
| 1143 | let faces = others(chat, me); |
| 1144 | let face = |(user_id, name): (Option<String>, String)| Face { user_id, name }; |
| 1145 | let first = faces.first().cloned().map(face); |
| 1146 | if is_one_on_one(chat) || faces.len() < 2 { |
| 1147 | let name = first |
| 1148 | .as_ref() |
| 1149 | .map_or(current.title.as_str(), |face| face.name.as_str()); |
| 1150 | let user_id = first.as_ref().and_then(|face| face.user_id.as_deref()); |
| 1151 | let avatar = person_avatar(directory, user_id, name, 36.); |
| 1152 | let presence = user_id.map(|id| directory.presence_of(id)); |
| 1153 | lead = Some(match presence { |
| 1154 | Some(kind) => with_presence(avatar, kind, 36., theme::background()) |
| 1155 | .into_any_element(), |
| 1156 | None => avatar, |
| 1157 | }); |
| 1158 | subline = presence |
| 1159 | .map(|kind| kind.label().to_owned()) |
| 1160 | .unwrap_or_default(); |
| 1161 | } else { |
| 1162 | let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone())); |
| 1163 | lead = Some(spec_avatar(directory, &pair, 36., theme::background())); |
| 1164 | subline = format!("{} participants", chat.members.len()); |
| 1165 | let shown: Vec<Face> = faces.iter().cloned().map(face).collect(); |
| 1166 | stack = Some(member_stack(directory, &shown, shown.len())); |
| 1167 | } |
| 1168 | } |
| 1169 | } |
| 1170 | Selection::Channel(channel_id) => { |
| 1171 | let team = app.sidebar.teams.iter().find(|entry| { |
| 1172 | entry |
| 1173 | .channels |
| 1174 | .iter() |
| 1175 | .any(|channel| &channel.id == channel_id) |
| 1176 | }); |
| 1177 | let (name, key) = team |
| 1178 | .map_or((current.title.as_str(), current.title.as_str()), |entry| { |
| 1179 | (entry.team.name.as_str(), entry.team.id.as_str()) |
| 1180 | }); |
| 1181 | lead = Some(square_avatar(name, key, 36., 9.).into_any_element()); |
| 1182 | } |
| 1183 | } |
| 1184 | let mut header = h_flex() |
| 1185 | .w_full() |
| 1186 | .h(px(60.)) |
| 1187 | .flex_none() |
| 1188 | .px(px(20.)) |
| 1189 | .gap(px(12.)) |
| 1190 | .items_center() |
| 1191 | .border_b_1() |
| 1192 | .border_color(theme::border()); |
| 1193 | if matches!(current.mode, ViewMode::Thread(_)) { |
| 1194 | header = header.child( |
| 1195 | Button::new("back-to-threads") |
| 1196 | .ghost() |
| 1197 | .compact() |
| 1198 | .label("Threads") |
| 1199 | .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx))), |
| 1200 | ); |
| 1201 | } |
| 1202 | let channel_note = match current.mode { |
| 1203 | ViewMode::Flat => None, |
| 1204 | ViewMode::ThreadList => Some("Threads"), |
| 1205 | ViewMode::Thread(_) => Some("Thread"), |
| 1206 | }; |
| 1207 | if let Some(note) = channel_note { |
| 1208 | subline = note.to_owned(); |
| 1209 | } |
| 1210 | let sync = ¤t.sync; |
| 1211 | if sync.failed { |
| 1212 | subline = "Not up to date".to_owned(); |
| 1213 | } else if sync.shown_at.is_some() { |
| 1214 | subline = if sync.slow { |
| 1215 | "Taking longer than usual ..." |
| 1216 | } else if sync.empty_cache { |
| 1217 | "Loading messages ..." |
| 1218 | } else { |
| 1219 | "Updating ..." |
| 1220 | } |
| 1221 | .to_owned(); |
| 1222 | } |
| 1223 | header |
| 1224 | .relative() |
| 1225 | .when(sync.shown_at.is_some(), |header| { |
| 1226 | header.child(progress_bar()) |
| 1227 | }) |
| 1228 | .children(lead) |
| 1229 | .child( |
| 1230 | v_flex() |
| 1231 | .flex_1() |
| 1232 | .min_w_0() |
| 1233 | .overflow_hidden() |
| 1234 | .gap(px(1.)) |
| 1235 | .child( |
| 1236 | div() |
| 1237 | .truncate() |
| 1238 | .text_size(px(15.)) |
| 1239 | .font_weight(FontWeight::SEMIBOLD) |
| 1240 | .text_color(theme::text()) |
| 1241 | .child(current.title.clone()), |
| 1242 | ) |
| 1243 | .when(!subline.is_empty(), |column| { |
| 1244 | column.child( |
| 1245 | div() |
| 1246 | .text_size(px(12.)) |
| 1247 | .text_color(theme::text_muted()) |
| 1248 | .child(subline), |
| 1249 | ) |
| 1250 | }), |
| 1251 | ) |
| 1252 | .children(stack) |
| 1253 | } |
| 1254 | } |
| 1255 | |
| 1256 | impl Render for ConversationView { |
| 1257 | fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 1258 | let background = theme::background(); |
| 1259 | let mut root = v_flex().flex_1().min_w_0().h_full().bg(background); |
| 1260 | let Some(current) = self.current.as_ref() else { |
| 1261 | return root |
| 1262 | .items_center() |
| 1263 | .justify_center() |
| 1264 | .text_color(theme::text_muted()) |
| 1265 | .child("Select a chat or channel") |
| 1266 | .into_any_element(); |
| 1267 | }; |
| 1268 | let rows = self.rows.clone(); |
| 1269 | let view = cx.weak_entity(); |
| 1270 | let app = self.app.clone(); |
| 1271 | let highlighted = self.highlighted_message.clone(); |
| 1272 | let scroller = MessageScroller::new( |
| 1273 | "messages", |
| 1274 | self.scroller.clone(), |
| 1275 | move |index, window, cx| { |
| 1276 | let rows = rows.borrow(); |
| 1277 | match rows.get(index) { |
| 1278 | Some(Row::Message(message)) => { |
| 1279 | let open_thread = message.open_thread.clone().map(|root_id| { |
| 1280 | let view = view.clone(); |
| 1281 | Box::new(move |cx: &mut App| { |
| 1282 | let root_id = root_id.clone(); |
| 1283 | view.update(cx, |this, cx| this.open_thread(root_id, cx)) |
| 1284 | .ok(); |
| 1285 | }) as Box<dyn Fn(&mut App)> |
| 1286 | }); |
| 1287 | let retry = matches!(message.delivery, Delivery::Failed(_)).then(|| { |
| 1288 | let (view, key, handle) = |
| 1289 | (view.clone(), message.key.clone(), window.window_handle()); |
| 1290 | Box::new(move |cx: &mut App| { |
| 1291 | let (view, key) = (view.clone(), key.clone()); |
| 1292 | handle |
| 1293 | .update(cx, move |_, window, cx| { |
| 1294 | view.update(cx, |this, cx| this.retry(&key, window, cx)) |
| 1295 | .ok(); |
| 1296 | }) |
| 1297 | .ok(); |
| 1298 | }) as Box<dyn Fn(&mut App)> |
| 1299 | }); |
| 1300 | let sender = (!message.own && !message.series.has_prev) |
| 1301 | .then(|| message.sender_id.clone()) |
| 1302 | .flatten() |
| 1303 | .filter(|sender| app.read(cx).directory.avatar(sender).is_none()); |
| 1304 | if let Some(sender) = sender { |
| 1305 | let app = app.clone(); |
| 1306 | cx.defer(move |cx| { |
| 1307 | app.update(cx, |state, cx| state.request_avatars(vec![sender], cx)); |
| 1308 | }); |
| 1309 | } |
| 1310 | let missing_images: Vec<ImageRef> = message |
| 1311 | .images |
| 1312 | .iter() |
| 1313 | .filter(|image| app.read(cx).directory.image(&image.url).is_none()) |
| 1314 | .cloned() |
| 1315 | .collect(); |
| 1316 | if !missing_images.is_empty() { |
| 1317 | let app = app.clone(); |
| 1318 | cx.defer(move |cx| { |
| 1319 | app.update(cx, |state, cx| { |
| 1320 | state.request_images(missing_images, cx) |
| 1321 | }); |
| 1322 | }); |
| 1323 | } |
| 1324 | let is_real = !message.key.starts_with(PENDING_KEY_PREFIX); |
| 1325 | let hovered = is_real.then(|| { |
| 1326 | let (view, key) = (view.clone(), message.key.clone()); |
| 1327 | Box::new(move |cx: &mut App| { |
| 1328 | view.update(cx, |this, _| { |
| 1329 | this.hovered_message = Some(key.clone()); |
| 1330 | }) |
| 1331 | .ok(); |
| 1332 | }) as Box<dyn Fn(&mut App)> |
| 1333 | }); |
| 1334 | let reply = (is_real && !message.deleted).then(|| { |
| 1335 | let (view, key, handle) = |
| 1336 | (view.clone(), message.key.clone(), window.window_handle()); |
| 1337 | Box::new(move |cx: &mut App| { |
| 1338 | let (view, key) = (view.clone(), key.clone()); |
| 1339 | handle |
| 1340 | .update(cx, move |_, window, cx| { |
| 1341 | view.update(cx, |this, cx| { |
| 1342 | this.begin_reply(&key, window, cx) |
| 1343 | }) |
| 1344 | .ok(); |
| 1345 | }) |
| 1346 | .ok(); |
| 1347 | }) as Box<dyn Fn(&mut App)> |
| 1348 | }); |
| 1349 | let state = app.read(cx); |
| 1350 | render_message_row( |
| 1351 | message, |
| 1352 | index, |
| 1353 | RowActions { |
| 1354 | open_thread, |
| 1355 | retry, |
| 1356 | reply, |
| 1357 | hovered, |
| 1358 | highlighted: highlighted.as_deref() == Some(message.key.as_str()), |
| 1359 | }, |
| 1360 | &state.directory, |
| 1361 | cx, |
| 1362 | ) |
| 1363 | } |
| 1364 | Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index), |
| 1365 | Some(Row::LoadOlder) => { |
| 1366 | let view = view.clone(); |
| 1367 | cx.defer(move |cx| { |
| 1368 | view.update(cx, |this, cx| this.request_older(cx)).ok(); |
| 1369 | }); |
| 1370 | h_flex() |
| 1371 | .w_full() |
| 1372 | .py_2() |
| 1373 | .gap(px(6.)) |
| 1374 | .justify_center() |
| 1375 | .text_size(px(12.)) |
| 1376 | .text_color(theme::text_muted()) |
| 1377 | .child(icon(IconName::Loader, 12., theme::text_muted())) |
| 1378 | .child("Loading older messages") |
| 1379 | .into_any_element() |
| 1380 | } |
| 1381 | Some(Row::Start(start)) => { |
| 1382 | let state = app.read(cx); |
| 1383 | v_flex() |
| 1384 | .w_full() |
| 1385 | .items_center() |
| 1386 | .gap(px(8.)) |
| 1387 | .pt(px(32.)) |
| 1388 | .pb(px(16.)) |
| 1389 | .child(person_avatar( |
| 1390 | &state.directory, |
| 1391 | start.user_id.as_deref(), |
| 1392 | &start.title, |
| 1393 | 56., |
| 1394 | )) |
| 1395 | .child( |
| 1396 | div() |
| 1397 | .text_size(px(16.)) |
| 1398 | .font_weight(FontWeight::SEMIBOLD) |
| 1399 | .text_color(theme::text()) |
| 1400 | .child(start.title.clone()), |
| 1401 | ) |
| 1402 | .child( |
| 1403 | div() |
| 1404 | .text_size(px(12.)) |
| 1405 | .text_color(theme::text_muted()) |
| 1406 | .child("This is the beginning of the conversation"), |
| 1407 | ) |
| 1408 | .into_any_element() |
| 1409 | } |
| 1410 | None => div().into_any_element(), |
| 1411 | } |
| 1412 | }, |
| 1413 | ) |
| 1414 | .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.))) |
| 1415 | .with_bottom_fade(background); |
| 1416 | |
| 1417 | root = root.child(self.render_header(current, cx)); |
| 1418 | if let Some(notice) = &self.notice { |
| 1419 | root = root.child( |
| 1420 | h_flex() |
| 1421 | .px_4() |
| 1422 | .py_1() |
| 1423 | .gap(px(8.)) |
| 1424 | .items_center() |
| 1425 | .text_xs() |
| 1426 | .bg(theme::amber().opacity(0.15)) |
| 1427 | .text_color(theme::amber()) |
| 1428 | .child(div().flex_1().min_w_0().child(notice.clone())) |
| 1429 | .when(current.sync.failed, |bar| { |
| 1430 | bar.child( |
| 1431 | Button::new("retry-fetch") |
| 1432 | .ghost() |
| 1433 | .compact() |
| 1434 | .label("Retry") |
| 1435 | .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))), |
| 1436 | ) |
| 1437 | }), |
| 1438 | ); |
| 1439 | } |
| 1440 | let empty_channel = current.mode == ViewMode::ThreadList && self.rows.borrow().is_empty(); |
| 1441 | let body = if empty_channel { |
| 1442 | div() |
| 1443 | .size_full() |
| 1444 | .flex() |
| 1445 | .items_center() |
| 1446 | .justify_center() |
| 1447 | .text_size(px(13.)) |
| 1448 | .text_color(theme::text_muted()) |
| 1449 | .child("No posts in this channel yet") |
| 1450 | .into_any_element() |
| 1451 | } else { |
| 1452 | scroller.into_any_element() |
| 1453 | }; |
| 1454 | root.child(div().flex_1().min_h_0().child(body)) |
| 1455 | .child(self.composer.clone()) |
| 1456 | .into_any_element() |
| 1457 | } |
| 1458 | } |
| 1459 | |
| 1460 | fn progress_bar() -> impl IntoElement { |
| 1461 | div() |
| 1462 | .absolute() |
| 1463 | .left_0() |
| 1464 | .right_0() |
| 1465 | .bottom(px(-1.)) |
| 1466 | .h(px(2.)) |
| 1467 | .overflow_hidden() |
| 1468 | .bg(theme::border()) |
| 1469 | .child( |
| 1470 | div() |
| 1471 | .absolute() |
| 1472 | .top_0() |
| 1473 | .h_full() |
| 1474 | .w(relative(PROGRESS_BAR_WIDTH)) |
| 1475 | .bg(theme::own_read()) |
| 1476 | .with_animation( |
| 1477 | "sync-progress", |
| 1478 | Animation::new(PROGRESS_BAR_PERIOD).repeat(), |
| 1479 | |bar, delta| { |
| 1480 | let travel = 1. + PROGRESS_BAR_WIDTH; |
| 1481 | // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0). |
| 1482 | bar.left(relative( |
| 1483 | (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH, |
| 1484 | )) |
| 1485 | }, |
| 1486 | ), |
| 1487 | ) |
| 1488 | } |