| 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 | input::Escape, |
| 12 | message_scroller::{MessageScroller, MessageScrollerState}, |
| 13 | v_flex, |
| 14 | }; |
| 15 | use gpui_kit::prelude::FluentBuilder as _; |
| 16 | use gpui_kit::*; |
| 17 | use store::MessageRecord; |
| 18 | use teams_core::{FileCard, ImageRef, MentionInput}; |
| 19 | |
| 20 | use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence}; |
| 21 | use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview}; |
| 22 | use super::message_actions::{Action, MessageMenu}; |
| 23 | use super::message_row::{RowActions, render_message_row, render_skeleton_row}; |
| 24 | use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one}; |
| 25 | use super::reaction_picker::{PickHandler, ReactionPicker}; |
| 26 | use super::widgets::{icon, symbol}; |
| 27 | use crate::app_state::{AppEvent, AppState, Selection, selection_title}; |
| 28 | use crate::data::{is_one_on_one, others}; |
| 29 | use crate::read_state::{ReadTrigger, plan_read}; |
| 30 | use crate::render::Block; |
| 31 | use crate::render::blocks::Inline; |
| 32 | use crate::rows::{ |
| 33 | Delivery, LocalImage, MessageRow, Receipt, Row, RowContext, Series, StartInfo, api_reaction, |
| 34 | assign_series, changed_indices, diff_keys, flat_rows, message_text, placeholder_rows, |
| 35 | reaction_glyph, reaction_type_for, reply_excerpt, thread_list_rows, thread_rows, |
| 36 | trailing_skeleton, |
| 37 | }; |
| 38 | use crate::runtime; |
| 39 | use crate::sidebar_model::{AvatarSpec, Face}; |
| 40 | use crate::theme; |
| 41 | |
| 42 | const CHAT_OPEN_LIMIT: usize = 60; |
| 43 | const CHANNEL_OPEN_LIMIT: usize = 300; |
| 44 | const GROWTH_HEADROOM: usize = 20; |
| 45 | const META_USER_ID: &str = "me_user_id"; |
| 46 | const PENDING_KEY_PREFIX: &str = "pending-"; |
| 47 | const MAX_NOTICE_CHARS: usize = 140; |
| 48 | const JUMP_SCAN_LIMIT: usize = 5000; |
| 49 | const JUMP_CONTEXT_MESSAGES: usize = 12; |
| 50 | const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2); |
| 51 | const PROGRESS_DELAY: Duration = Duration::from_millis(400); |
| 52 | const SKELETON_DELAY: Duration = Duration::from_millis(1000); |
| 53 | const SLOW_AFTER: Duration = Duration::from_secs(8); |
| 54 | const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500); |
| 55 | const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400); |
| 56 | const PROGRESS_BAR_WIDTH: f32 = 0.35; |
| 57 | |
| 58 | actions!(teams, [ReplyToHovered]); |
| 59 | |
| 60 | #[derive(Clone, Copy)] |
| 61 | enum HoverSlot { |
| 62 | Row, |
| 63 | Toolbar, |
| 64 | } |
| 65 | |
| 66 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 67 | enum ViewMode { |
| 68 | Flat, |
| 69 | ThreadList, |
| 70 | Thread(String), |
| 71 | } |
| 72 | |
| 73 | #[derive(Default)] |
| 74 | struct SyncProgress { |
| 75 | messages: bool, |
| 76 | receipts: bool, |
| 77 | empty_cache: bool, |
| 78 | newest_cached: Option<DateTime<Utc>>, |
| 79 | shown_at: Option<Instant>, |
| 80 | trailing_skeleton: bool, |
| 81 | slow: bool, |
| 82 | failed: bool, |
| 83 | } |
| 84 | |
| 85 | impl SyncProgress { |
| 86 | fn running(&self) -> bool { |
| 87 | self.messages || self.receipts |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | struct Current { |
| 92 | selection: Selection, |
| 93 | title: String, |
| 94 | mode: ViewMode, |
| 95 | loaded_limit: usize, |
| 96 | loaded_count: usize, |
| 97 | has_older: bool, |
| 98 | loading_older: bool, |
| 99 | older_blocked: bool, |
| 100 | fetched: bool, |
| 101 | first_unread: Option<String>, |
| 102 | sync: SyncProgress, |
| 103 | } |
| 104 | |
| 105 | pub struct ConversationView { |
| 106 | app: Entity<AppState>, |
| 107 | scroller: Entity<MessageScrollerState>, |
| 108 | composer: Entity<Composer>, |
| 109 | draft: Entity<NewChatDraft>, |
| 110 | draft_active: bool, |
| 111 | draft_created: Option<(Vec<String>, String)>, |
| 112 | draft_error: Option<String>, |
| 113 | rows: Rc<RefCell<Vec<Row>>>, |
| 114 | current: Option<Current>, |
| 115 | pending: Vec<MessageRow>, |
| 116 | pending_counter: usize, |
| 117 | pending_outgoing: HashMap<String, Outgoing>, |
| 118 | hovered_message: Option<String>, |
| 119 | toolbar_hovered: Option<String>, |
| 120 | toolbar_pinned: Option<String>, |
| 121 | picker: Entity<ReactionPicker>, |
| 122 | highlighted_message: Option<String>, |
| 123 | notice: Option<String>, |
| 124 | drag_file_count: usize, |
| 125 | sync_generation: u64, |
| 126 | window_active: bool, |
| 127 | _subscriptions: Vec<Subscription>, |
| 128 | } |
| 129 | |
| 130 | fn open_limit(selection: &Selection) -> usize { |
| 131 | match selection { |
| 132 | Selection::Chat(_) => CHAT_OPEN_LIMIT, |
| 133 | Selection::Channel(_) => CHANNEL_OPEN_LIMIT, |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 138 | enum DropTarget { |
| 139 | Chat, |
| 140 | Channel, |
| 141 | NewChat, |
| 142 | } |
| 143 | |
| 144 | fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) { |
| 145 | let files = if count == 1 { |
| 146 | "1 file".to_owned() |
| 147 | } else { |
| 148 | format!("{count} files") |
| 149 | }; |
| 150 | match target { |
| 151 | DropTarget::Chat => ( |
| 152 | format!("Drop to attach to {title}"), |
| 153 | format!("{files}. Images go into the message, other files to your OneDrive."), |
| 154 | ), |
| 155 | DropTarget::Channel => ( |
| 156 | format!("Drop to attach to {title}"), |
| 157 | format!("{files}. Images go into the message, other files to the channel's Files."), |
| 158 | ), |
| 159 | DropTarget::NewChat => ( |
| 160 | "Drop to attach to the new chat".to_owned(), |
| 161 | format!( |
| 162 | "{files}. Images go into the message. Files can be added once the chat exists." |
| 163 | ), |
| 164 | ), |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | fn short_error(error: &dyn std::fmt::Display) -> String { |
| 169 | error.to_string().chars().take(MAX_NOTICE_CHARS).collect() |
| 170 | } |
| 171 | |
| 172 | impl ConversationView { |
| 173 | pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self { |
| 174 | let scroller = cx.new(|cx| MessageScrollerState::new(0, cx)); |
| 175 | let composer = cx.new(|cx| Composer::new(app.clone(), window, cx)); |
| 176 | let picker = cx.new(|cx| ReactionPicker::new(app.clone(), window, cx)); |
| 177 | let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx)); |
| 178 | let subscriptions = vec![ |
| 179 | cx.subscribe_in(&app, window, Self::on_app_event), |
| 180 | cx.subscribe_in(&composer, window, Self::on_composer_event), |
| 181 | cx.subscribe_in(&draft, window, Self::on_draft_event), |
| 182 | cx.observe_window_activation(window, Self::on_window_activation), |
| 183 | ]; |
| 184 | let mut view = ConversationView { |
| 185 | app, |
| 186 | scroller, |
| 187 | composer, |
| 188 | draft, |
| 189 | draft_active: false, |
| 190 | draft_created: None, |
| 191 | draft_error: None, |
| 192 | rows: Rc::new(RefCell::new(Vec::new())), |
| 193 | current: None, |
| 194 | pending: Vec::new(), |
| 195 | pending_counter: 0, |
| 196 | pending_outgoing: HashMap::new(), |
| 197 | hovered_message: None, |
| 198 | toolbar_hovered: None, |
| 199 | toolbar_pinned: None, |
| 200 | picker, |
| 201 | highlighted_message: None, |
| 202 | notice: None, |
| 203 | drag_file_count: 0, |
| 204 | sync_generation: 0, |
| 205 | window_active: window.is_window_active(), |
| 206 | _subscriptions: subscriptions, |
| 207 | }; |
| 208 | if let Some(selection) = view.app.read(cx).selection.clone() { |
| 209 | view.open(selection, window, cx); |
| 210 | } |
| 211 | view |
| 212 | } |
| 213 | |
| 214 | #[cfg_attr(not(windows), allow(dead_code))] |
| 215 | pub fn composer_is_empty(&self, cx: &App) -> bool { |
| 216 | self.composer.read(cx).is_empty(cx) |
| 217 | } |
| 218 | |
| 219 | #[cfg_attr(not(windows), allow(dead_code))] |
| 220 | pub fn send_in_flight(&self) -> bool { |
| 221 | self.pending |
| 222 | .iter() |
| 223 | .any(|row| matches!(row.delivery, Delivery::Sending)) |
| 224 | } |
| 225 | |
| 226 | fn on_window_activation(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 227 | self.window_active = window.is_window_active(); |
| 228 | self.mark_read(ReadTrigger::Activation, cx); |
| 229 | } |
| 230 | |
| 231 | fn on_app_event( |
| 232 | &mut self, |
| 233 | _: &Entity<AppState>, |
| 234 | event: &AppEvent, |
| 235 | window: &mut Window, |
| 236 | cx: &mut Context<Self>, |
| 237 | ) { |
| 238 | match event { |
| 239 | AppEvent::Selection => { |
| 240 | let (new_chat, selection) = { |
| 241 | let state = self.app.read(cx); |
| 242 | (state.new_chat, state.selection.clone()) |
| 243 | }; |
| 244 | if new_chat { |
| 245 | self.enter_draft(window, cx); |
| 246 | return; |
| 247 | } |
| 248 | if self.draft_active { |
| 249 | let created = self |
| 250 | .draft_created |
| 251 | .as_ref() |
| 252 | .map(|(_, chat_id)| chat_id.clone()); |
| 253 | if let Some(chat_id) = created { |
| 254 | self.composer |
| 255 | .update(cx, |composer, _| composer.carry_images_into(chat_id)); |
| 256 | } |
| 257 | self.leave_draft(window, cx); |
| 258 | } |
| 259 | match selection { |
| 260 | Some(selection) => self.open(selection, window, cx), |
| 261 | None => { |
| 262 | self.current = None; |
| 263 | self.rebuild(true, cx); |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | AppEvent::Messages(conversation_id) => { |
| 268 | let is_current = self |
| 269 | .current |
| 270 | .as_ref() |
| 271 | .is_some_and(|current| current.selection.conversation_id() == conversation_id); |
| 272 | if is_current { |
| 273 | self.rebuild(false, cx); |
| 274 | self.mark_read(ReadTrigger::Incoming, cx); |
| 275 | } |
| 276 | } |
| 277 | AppEvent::Images(keys) => self.remeasure_images(keys, cx), |
| 278 | AppEvent::Jump => self.apply_pending_jump(cx), |
| 279 | AppEvent::Status => { |
| 280 | if let Some(current) = self.current.as_mut() |
| 281 | && current.sync.failed |
| 282 | { |
| 283 | current.fetched = false; |
| 284 | } |
| 285 | self.start_fetch(cx) |
| 286 | } |
| 287 | AppEvent::Directory => cx.notify(), |
| 288 | AppEvent::Sidebar => { |
| 289 | self.mark_read(ReadTrigger::Incoming, cx); |
| 290 | if self.draft_active { |
| 291 | self.on_draft_changed(window, cx); |
| 292 | } else if let Some(current) = self.current.as_mut() { |
| 293 | let title = selection_title(&self.app.read(cx).sidebar, ¤t.selection); |
| 294 | if current.title != title { |
| 295 | current.title = title.clone(); |
| 296 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 297 | self.composer.update(cx, |composer, cx| { |
| 298 | composer.set_conversation(&conversation_id, &title, window, cx) |
| 299 | }); |
| 300 | cx.notify(); |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | fn on_composer_event( |
| 308 | &mut self, |
| 309 | _: &Entity<Composer>, |
| 310 | event: &ComposerEvent, |
| 311 | window: &mut Window, |
| 312 | cx: &mut Context<Self>, |
| 313 | ) { |
| 314 | match event { |
| 315 | ComposerEvent::Submit(outgoing) if self.draft_active => { |
| 316 | self.send_new_chat((**outgoing).clone(), window, cx) |
| 317 | } |
| 318 | ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => { |
| 319 | self.send_edit((**outgoing).clone(), window, cx) |
| 320 | } |
| 321 | ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx), |
| 322 | ComposerEvent::EditLast => self.edit_last_own(window, cx), |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) { |
| 327 | self.toolbar_hovered = None; |
| 328 | self.toolbar_pinned = None; |
| 329 | let title = selection_title(&self.app.read(cx).sidebar, &selection); |
| 330 | let mode = match selection { |
| 331 | Selection::Chat(_) => ViewMode::Flat, |
| 332 | Selection::Channel(_) => ViewMode::ThreadList, |
| 333 | }; |
| 334 | let first_unread = self.first_unread_id(&selection, cx); |
| 335 | self.current = Some(Current { |
| 336 | loaded_limit: open_limit(&selection), |
| 337 | selection, |
| 338 | title, |
| 339 | mode, |
| 340 | loaded_count: 0, |
| 341 | has_older: false, |
| 342 | loading_older: false, |
| 343 | older_blocked: false, |
| 344 | fetched: false, |
| 345 | first_unread, |
| 346 | sync: SyncProgress::default(), |
| 347 | }); |
| 348 | self.sync_generation += 1; |
| 349 | self.clear_pending(); |
| 350 | self.notice = None; |
| 351 | self.rebuild(true, cx); |
| 352 | self.start_fetch(cx); |
| 353 | self.mark_read(ReadTrigger::Open, cx); |
| 354 | let target = self |
| 355 | .current |
| 356 | .as_ref() |
| 357 | .map(|current| { |
| 358 | ( |
| 359 | current.selection.conversation_id().to_owned(), |
| 360 | current.title.clone(), |
| 361 | ) |
| 362 | }) |
| 363 | .unwrap_or_default(); |
| 364 | self.composer.update(cx, |composer, cx| { |
| 365 | composer.set_conversation(&target.0, &target.1, window, cx); |
| 366 | }); |
| 367 | if !self.draft_active { |
| 368 | self.composer |
| 369 | .update(cx, |composer, cx| composer.focus(window, cx)); |
| 370 | } |
| 371 | self.hovered_message = None; |
| 372 | self.apply_pending_jump(cx); |
| 373 | } |
| 374 | |
| 375 | fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 376 | if !self.draft_active { |
| 377 | self.draft_active = true; |
| 378 | self.current = None; |
| 379 | self.clear_pending(); |
| 380 | self.notice = None; |
| 381 | self.draft_created = None; |
| 382 | self.draft_error = None; |
| 383 | self.toolbar_hovered = None; |
| 384 | self.toolbar_pinned = None; |
| 385 | self.hovered_message = None; |
| 386 | self.sync_generation += 1; |
| 387 | self.draft.update(cx, |draft, cx| draft.reset(window, cx)); |
| 388 | self.composer.update(cx, |composer, cx| { |
| 389 | composer.set_conversation("", "", window, cx) |
| 390 | }); |
| 391 | self.on_draft_changed(window, cx); |
| 392 | self.rebuild(true, cx); |
| 393 | } |
| 394 | self.draft |
| 395 | .update(cx, |draft, cx| draft.focus_query(window, cx)); |
| 396 | cx.notify(); |
| 397 | } |
| 398 | |
| 399 | fn leave_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 400 | self.draft_active = false; |
| 401 | self.draft_created = None; |
| 402 | self.draft_error = None; |
| 403 | self.clear_pending(); |
| 404 | self.draft.update(cx, |draft, cx| draft.reset(window, cx)); |
| 405 | } |
| 406 | |
| 407 | fn on_draft_event( |
| 408 | &mut self, |
| 409 | _: &Entity<NewChatDraft>, |
| 410 | event: &NewChatEvent, |
| 411 | window: &mut Window, |
| 412 | cx: &mut Context<Self>, |
| 413 | ) { |
| 414 | match event { |
| 415 | NewChatEvent::Changed => self.on_draft_changed(window, cx), |
| 416 | NewChatEvent::FocusComposer => self |
| 417 | .composer |
| 418 | .update(cx, |composer, cx| composer.focus(window, cx)), |
| 419 | NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)), |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | fn draft_target_chat(&self, cx: &App) -> Option<String> { |
| 424 | let chips = self.draft.read(cx).chips(); |
| 425 | let [chip] = chips else { |
| 426 | return None; |
| 427 | }; |
| 428 | let state = self.app.read(cx); |
| 429 | existing_one_on_one( |
| 430 | &state.sidebar.chats, |
| 431 | state.directory.me.as_ref(), |
| 432 | &chip.user_id, |
| 433 | ) |
| 434 | .map(|chat| chat.id.clone()) |
| 435 | } |
| 436 | |
| 437 | fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 438 | if !self.draft_active { |
| 439 | return; |
| 440 | } |
| 441 | let target = self.draft_target_chat(cx); |
| 442 | if target != self.conversation_id() { |
| 443 | match target { |
| 444 | Some(chat_id) => { |
| 445 | self.composer.update(cx, |composer, _| { |
| 446 | composer.carry_images_into(chat_id.clone()) |
| 447 | }); |
| 448 | self.open(Selection::Chat(chat_id), window, cx) |
| 449 | } |
| 450 | None => { |
| 451 | self.composer.update(cx, |composer, cx| { |
| 452 | composer.carry_images_into(String::new()); |
| 453 | composer.set_conversation("", "", window, cx); |
| 454 | }); |
| 455 | self.current = None; |
| 456 | self.sync_generation += 1; |
| 457 | self.rebuild(true, cx); |
| 458 | } |
| 459 | } |
| 460 | } |
| 461 | let placeholder = { |
| 462 | let draft = self.draft.read(cx); |
| 463 | composer_placeholder(draft.chips(), &draft.group_name(cx)) |
| 464 | }; |
| 465 | self.composer.update(cx, |composer, cx| { |
| 466 | composer.set_placeholder(&placeholder, window, cx) |
| 467 | }); |
| 468 | cx.notify(); |
| 469 | } |
| 470 | |
| 471 | fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) { |
| 472 | let indices: Vec<usize> = self |
| 473 | .rows |
| 474 | .borrow() |
| 475 | .iter() |
| 476 | .enumerate() |
| 477 | .filter_map(|(index, row)| match row { |
| 478 | Row::Message(message) |
| 479 | if message.images.iter().any(|image| keys.contains(&image.url)) => |
| 480 | { |
| 481 | Some(index) |
| 482 | } |
| 483 | _ => None, |
| 484 | }) |
| 485 | .collect(); |
| 486 | self.scroller.update(cx, |scroller, cx| { |
| 487 | for index in indices { |
| 488 | scroller.remeasure_items(index..index + 1, cx); |
| 489 | } |
| 490 | }); |
| 491 | cx.notify(); |
| 492 | } |
| 493 | |
| 494 | fn apply_pending_jump(&mut self, cx: &mut Context<Self>) { |
| 495 | let Some(conversation_id) = self |
| 496 | .current |
| 497 | .as_ref() |
| 498 | .map(|current| current.selection.conversation_id().to_owned()) |
| 499 | else { |
| 500 | return; |
| 501 | }; |
| 502 | let jump = self |
| 503 | .app |
| 504 | .update(cx, |state, _| match state.pending_jump.take() { |
| 505 | Some((target, message_id)) if target == conversation_id => Some(message_id), |
| 506 | other => { |
| 507 | state.pending_jump = other; |
| 508 | None |
| 509 | } |
| 510 | }); |
| 511 | if let Some(message_id) = jump { |
| 512 | self.jump_to_message(&conversation_id, &message_id, cx); |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) { |
| 517 | let store = self.app.read(cx).store.clone(); |
| 518 | let Some(record) = store |
| 519 | .messages_by_id(conversation_id, &[message_id.to_owned()]) |
| 520 | .ok() |
| 521 | .and_then(|mut found| found.remove(message_id)) |
| 522 | else { |
| 523 | return; |
| 524 | }; |
| 525 | let messages_from_target = store |
| 526 | .messages(conversation_id, None, JUMP_SCAN_LIMIT) |
| 527 | .ok() |
| 528 | .and_then(|all| { |
| 529 | all.iter() |
| 530 | .position(|candidate| candidate.message_id == message_id) |
| 531 | .map(|position| all.len() - position) |
| 532 | }) |
| 533 | .unwrap_or_default(); |
| 534 | let row_key = record |
| 535 | .reply_to_id |
| 536 | .clone() |
| 537 | .unwrap_or_else(|| message_id.to_owned()); |
| 538 | let Some(current) = self.current.as_mut() else { |
| 539 | return; |
| 540 | }; |
| 541 | current.loaded_limit = current |
| 542 | .loaded_limit |
| 543 | .max(messages_from_target + JUMP_CONTEXT_MESSAGES); |
| 544 | current.first_unread = None; |
| 545 | if matches!(current.selection, Selection::Channel(_)) { |
| 546 | current.mode = match record.reply_to_id { |
| 547 | Some(root_id) => ViewMode::Thread(root_id), |
| 548 | None => ViewMode::ThreadList, |
| 549 | }; |
| 550 | } |
| 551 | let target_key = if matches!(current.mode, ViewMode::Thread(_)) { |
| 552 | message_id.to_owned() |
| 553 | } else { |
| 554 | row_key |
| 555 | }; |
| 556 | self.clear_pending(); |
| 557 | self.rebuild(true, cx); |
| 558 | let index = self |
| 559 | .rows |
| 560 | .borrow() |
| 561 | .iter() |
| 562 | .position(|row| row.key() == target_key); |
| 563 | if let Some(index) = index { |
| 564 | self.scroller |
| 565 | .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx)); |
| 566 | self.highlight(target_key, cx); |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | fn highlight(&mut self, key: String, cx: &mut Context<Self>) { |
| 571 | self.highlighted_message = Some(key.clone()); |
| 572 | cx.notify(); |
| 573 | cx.spawn(async move |this, cx| { |
| 574 | cx.background_executor().timer(HIGHLIGHT_DURATION).await; |
| 575 | this.update(cx, |this, cx| { |
| 576 | if this.highlighted_message.as_deref() == Some(key.as_str()) { |
| 577 | this.highlighted_message = None; |
| 578 | cx.notify(); |
| 579 | } |
| 580 | }) |
| 581 | .ok(); |
| 582 | }) |
| 583 | .detach(); |
| 584 | } |
| 585 | |
| 586 | pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 587 | self.composer |
| 588 | .update(cx, |composer, cx| composer.set_text(text, window, cx)); |
| 589 | self.composer |
| 590 | .update(cx, |composer, cx| composer.focus(window, cx)); |
| 591 | } |
| 592 | |
| 593 | pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 594 | let key = self.rows.borrow().iter().rev().find_map(|row| match row { |
| 595 | Row::Message(message) if !message.own => Some(message.key.clone()), |
| 596 | _ => None, |
| 597 | }); |
| 598 | if let Some(key) = key { |
| 599 | self.begin_reply(&key, window, cx); |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 604 | if let Some(message_id) = self.hovered_message.clone() { |
| 605 | self.begin_reply(&message_id, window, cx); |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 610 | let Some(conversation_id) = self |
| 611 | .current |
| 612 | .as_ref() |
| 613 | .map(|current| current.selection.conversation_id().to_owned()) |
| 614 | else { |
| 615 | return; |
| 616 | }; |
| 617 | let store = self.app.read(cx).store.clone(); |
| 618 | let record = store |
| 619 | .messages_by_id(&conversation_id, &[message_id.to_owned()]) |
| 620 | .ok() |
| 621 | .and_then(|mut found| found.remove(message_id)) |
| 622 | .filter(|record| !record.deleted); |
| 623 | let Some(record) = record else { |
| 624 | return; |
| 625 | }; |
| 626 | let preview = ReplyPreview { |
| 627 | message_id: record.message_id.clone(), |
| 628 | author: record |
| 629 | .sender_name |
| 630 | .clone() |
| 631 | .unwrap_or_else(|| "Unknown".to_owned()), |
| 632 | excerpt: reply_excerpt(&record), |
| 633 | }; |
| 634 | self.composer.update(cx, |composer, cx| { |
| 635 | composer.set_reply(Some(preview), cx); |
| 636 | composer.focus(window, cx); |
| 637 | }); |
| 638 | } |
| 639 | |
| 640 | fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> { |
| 641 | let Selection::Chat(chat_id) = selection else { |
| 642 | return None; |
| 643 | }; |
| 644 | let state = self.app.read(cx); |
| 645 | if state.mode.demo { |
| 646 | return crate::demo::first_unread(chat_id); |
| 647 | } |
| 648 | state.engine.as_ref()?.first_unread_message_id(chat_id) |
| 649 | } |
| 650 | |
| 651 | fn row_context(&self, cx: &App) -> RowContext { |
| 652 | let now = Local::now(); |
| 653 | RowContext { |
| 654 | offset: now.offset().fix(), |
| 655 | today: now.date_naive(), |
| 656 | my_user_id: self.app.read(cx).store.meta(META_USER_ID).ok().flatten(), |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | fn start_info(&self, cx: &App) -> Option<StartInfo> { |
| 661 | let current = self.current.as_ref()?; |
| 662 | let app = self.app.read(cx); |
| 663 | let user_id = match ¤t.selection { |
| 664 | Selection::Chat(chat_id) => app |
| 665 | .sidebar |
| 666 | .chats |
| 667 | .iter() |
| 668 | .find(|chat| &chat.id == chat_id) |
| 669 | .filter(|chat| is_one_on_one(chat)) |
| 670 | .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next()) |
| 671 | .and_then(|(user_id, _)| user_id), |
| 672 | Selection::Channel(_) => None, |
| 673 | }; |
| 674 | Some(StartInfo { |
| 675 | title: current.title.clone(), |
| 676 | user_id, |
| 677 | }) |
| 678 | } |
| 679 | |
| 680 | fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) { |
| 681 | let Some(current) = self.current.as_ref() else { |
| 682 | let mut rows: Vec<Row> = self |
| 683 | .pending |
| 684 | .iter() |
| 685 | .cloned() |
| 686 | .map(|row| Row::Message(Box::new(row))) |
| 687 | .collect(); |
| 688 | assign_series(&mut rows); |
| 689 | self.apply_rows(rows, true, cx); |
| 690 | return; |
| 691 | }; |
| 692 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 693 | let limit = if reset { |
| 694 | current.loaded_limit |
| 695 | } else { |
| 696 | current |
| 697 | .loaded_limit |
| 698 | .max(current.loaded_count + GROWTH_HEADROOM) |
| 699 | }; |
| 700 | let store = self.app.read(cx).store.clone(); |
| 701 | let records: Vec<MessageRecord> = store |
| 702 | .messages(&conversation_id, None, limit) |
| 703 | .unwrap_or_default(); |
| 704 | let sync_has_more = store |
| 705 | .sync_state(&conversation_id) |
| 706 | .ok() |
| 707 | .flatten() |
| 708 | .is_none_or(|state| state.has_more); |
| 709 | let context = self.row_context(cx); |
| 710 | let can_load_older = self.app.read(cx).engine.is_some(); |
| 711 | let start = self.start_info(cx); |
| 712 | let current = self.current.as_mut().expect("checked above"); |
| 713 | let first_unread = current.first_unread.clone(); |
| 714 | current.loaded_limit = limit; |
| 715 | current.loaded_count = records.len(); |
| 716 | let has_older = sync_has_more && !current.older_blocked && can_load_older; |
| 717 | let placeholders = current.sync.messages |
| 718 | && records.is_empty() |
| 719 | && !matches!(current.mode, ViewMode::Thread(_)); |
| 720 | let trailing = current.sync.trailing_skeleton && current.mode == ViewMode::Flat; |
| 721 | let mut rows = match ¤t.mode { |
| 722 | _ if placeholders => { |
| 723 | current.has_older = false; |
| 724 | placeholder_rows() |
| 725 | } |
| 726 | ViewMode::Flat => { |
| 727 | current.has_older = has_older; |
| 728 | let mut rows = flat_rows(&records, &context, has_older); |
| 729 | if !has_older && let Some(start) = start { |
| 730 | rows.insert(0, Row::Start(start)); |
| 731 | } |
| 732 | rows |
| 733 | } |
| 734 | ViewMode::ThreadList => { |
| 735 | current.has_older = has_older; |
| 736 | thread_list_rows(&records, &context, has_older) |
| 737 | } |
| 738 | ViewMode::Thread(root_id) => { |
| 739 | current.has_older = false; |
| 740 | thread_rows(&records, root_id, &context) |
| 741 | } |
| 742 | }; |
| 743 | if trailing && !placeholders { |
| 744 | rows.push(trailing_skeleton()); |
| 745 | } |
| 746 | rows.extend( |
| 747 | self.pending |
| 748 | .iter() |
| 749 | .cloned() |
| 750 | .map(|row| Row::Message(Box::new(row))), |
| 751 | ); |
| 752 | let receipts = self.receipts(&records, cx); |
| 753 | for row in rows.iter_mut() { |
| 754 | if let Row::Message(message) = row |
| 755 | && message.own |
| 756 | { |
| 757 | message.receipt = receipts.get(&message.key).copied().unwrap_or_default(); |
| 758 | } |
| 759 | } |
| 760 | if let Some(unread_id) = &first_unread { |
| 761 | for row in rows.iter_mut() { |
| 762 | if let Row::Message(message) = row |
| 763 | && &message.key == unread_id |
| 764 | { |
| 765 | message.new_marker = true; |
| 766 | } |
| 767 | } |
| 768 | } |
| 769 | assign_series(&mut rows); |
| 770 | self.apply_rows(rows, reset, cx); |
| 771 | } |
| 772 | |
| 773 | fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) { |
| 774 | let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows); |
| 775 | let new_len = self.rows.borrow().len(); |
| 776 | if reset { |
| 777 | let marker_index = self |
| 778 | .rows |
| 779 | .borrow() |
| 780 | .iter() |
| 781 | .position(|row| matches!(row, Row::Message(message) if message.new_marker)); |
| 782 | self.scroller.update(cx, |scroller, cx| { |
| 783 | scroller.reset(new_len, cx); |
| 784 | match marker_index { |
| 785 | Some(index) if !scroller.scroll_to_item(index, cx) => { |
| 786 | scroller.scroll_to_end(cx) |
| 787 | } |
| 788 | Some(_) => {} |
| 789 | None => scroller.scroll_to_end(cx), |
| 790 | } |
| 791 | }); |
| 792 | cx.notify(); |
| 793 | return; |
| 794 | } |
| 795 | let (splice, changed) = { |
| 796 | let new_rows = self.rows.borrow(); |
| 797 | let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect(); |
| 798 | let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect(); |
| 799 | ( |
| 800 | diff_keys(&old_keys, &new_keys), |
| 801 | changed_indices(&old_rows, &new_rows), |
| 802 | ) |
| 803 | }; |
| 804 | self.scroller.update(cx, |scroller, cx| { |
| 805 | if let Some(splice) = splice |
| 806 | && !scroller.splice(splice.range, splice.count, cx) |
| 807 | { |
| 808 | scroller.reset(new_len, cx); |
| 809 | } |
| 810 | for index in changed { |
| 811 | scroller.remeasure_items(index..index + 1, cx); |
| 812 | } |
| 813 | }); |
| 814 | cx.notify(); |
| 815 | } |
| 816 | |
| 817 | fn start_fetch(&mut self, cx: &mut Context<Self>) { |
| 818 | let state = self.app.read(cx); |
| 819 | let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync); |
| 820 | if engine.is_none() && demo_sync.is_none() { |
| 821 | return; |
| 822 | } |
| 823 | let Some(current) = self.current.as_mut() else { |
| 824 | return; |
| 825 | }; |
| 826 | if current.fetched { |
| 827 | return; |
| 828 | } |
| 829 | current.fetched = true; |
| 830 | let is_chat = matches!(current.selection, Selection::Chat(_)); |
| 831 | let newest_cached = self.rows.borrow().iter().rev().find_map(|row| match row { |
| 832 | Row::Message(message) if !message.key.starts_with(PENDING_KEY_PREFIX) => { |
| 833 | Some(message.created_at) |
| 834 | } |
| 835 | _ => None, |
| 836 | }); |
| 837 | let current = self.current.as_mut().expect("checked above"); |
| 838 | if current.sync.failed { |
| 839 | self.notice = None; |
| 840 | } |
| 841 | current.sync = SyncProgress { |
| 842 | messages: true, |
| 843 | receipts: is_chat, |
| 844 | empty_cache: newest_cached.is_none(), |
| 845 | newest_cached, |
| 846 | ..SyncProgress::default() |
| 847 | }; |
| 848 | self.sync_generation += 1; |
| 849 | let generation = self.sync_generation; |
| 850 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 851 | match (engine, demo_sync) { |
| 852 | (Some(engine), _) => { |
| 853 | let receiver = |
| 854 | runtime::spawn(async move { engine.fetch_newer(&conversation_id).await }); |
| 855 | cx.spawn(async move |this, cx| { |
| 856 | let result = receiver.await; |
| 857 | this.update(cx, |this, cx| this.finish_fetch(generation, result, cx)) |
| 858 | .ok(); |
| 859 | }) |
| 860 | .detach(); |
| 861 | } |
| 862 | (None, Some(delay)) => self.simulate_sync(generation, delay, cx), |
| 863 | (None, None) => {} |
| 864 | } |
| 865 | self.schedule_progress(generation, cx); |
| 866 | self.rebuild(false, cx); |
| 867 | self.mark_read(ReadTrigger::Incoming, cx); |
| 868 | self.refresh_receipts(generation, cx); |
| 869 | } |
| 870 | |
| 871 | fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) { |
| 872 | cx.spawn(async move |this, cx| { |
| 873 | cx.background_executor().timer(delay).await; |
| 874 | this.update(cx, |this, cx| { |
| 875 | if let Some(sync) = this.sync_of(generation) { |
| 876 | sync.receipts = false; |
| 877 | } |
| 878 | this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx) |
| 879 | }) |
| 880 | .ok(); |
| 881 | }) |
| 882 | .detach(); |
| 883 | } |
| 884 | |
| 885 | fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> { |
| 886 | if generation != self.sync_generation { |
| 887 | return None; |
| 888 | } |
| 889 | self.current.as_mut().map(|current| &mut current.sync) |
| 890 | } |
| 891 | |
| 892 | fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) { |
| 893 | cx.spawn(async move |this, cx| { |
| 894 | let stages = [ |
| 895 | (PROGRESS_DELAY, Duration::ZERO), |
| 896 | (SKELETON_DELAY, PROGRESS_DELAY), |
| 897 | (SLOW_AFTER, SKELETON_DELAY), |
| 898 | ]; |
| 899 | for (stage, (at, previous)) in stages.into_iter().enumerate() { |
| 900 | cx.background_executor().timer(at - previous).await; |
| 901 | let running = this |
| 902 | .update(cx, |this, cx| this.advance_progress(generation, stage, cx)) |
| 903 | .unwrap_or(false); |
| 904 | if !running { |
| 905 | return; |
| 906 | } |
| 907 | } |
| 908 | }) |
| 909 | .detach(); |
| 910 | } |
| 911 | |
| 912 | fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool { |
| 913 | let Some(sync) = self.sync_of(generation) else { |
| 914 | return false; |
| 915 | }; |
| 916 | if !sync.running() { |
| 917 | return false; |
| 918 | } |
| 919 | match stage { |
| 920 | 0 => sync.shown_at = Some(Instant::now()), |
| 921 | 1 if sync.messages => { |
| 922 | sync.trailing_skeleton = true; |
| 923 | self.rebuild(false, cx); |
| 924 | } |
| 925 | 1 => {} |
| 926 | _ => sync.slow = true, |
| 927 | } |
| 928 | cx.notify(); |
| 929 | true |
| 930 | } |
| 931 | |
| 932 | fn finish_fetch( |
| 933 | &mut self, |
| 934 | generation: u64, |
| 935 | result: Result< |
| 936 | teams_core::Result<teams_core::Delta>, |
| 937 | tokio::sync::oneshot::error::RecvError, |
| 938 | >, |
| 939 | cx: &mut Context<Self>, |
| 940 | ) { |
| 941 | let Some(sync) = self.sync_of(generation) else { |
| 942 | return; |
| 943 | }; |
| 944 | sync.messages = false; |
| 945 | sync.trailing_skeleton = false; |
| 946 | let newest_cached = sync.newest_cached; |
| 947 | match result { |
| 948 | Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx), |
| 949 | Ok(Err(error)) => self.fail_sync(generation, short_error(&error)), |
| 950 | Err(error) => self.fail_sync(generation, short_error(&error)), |
| 951 | } |
| 952 | self.rebuild(false, cx); |
| 953 | self.settle_progress(generation, cx); |
| 954 | } |
| 955 | |
| 956 | fn fail_sync(&mut self, generation: u64, error: String) { |
| 957 | if let Some(sync) = self.sync_of(generation) { |
| 958 | sync.failed = true; |
| 959 | sync.receipts = false; |
| 960 | } |
| 961 | self.notice = Some(format!("Could not refresh: {error}")); |
| 962 | } |
| 963 | |
| 964 | fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) { |
| 965 | let Some(newest_cached) = newest_cached else { |
| 966 | return; |
| 967 | }; |
| 968 | let Some(my_user_id) = self.row_context(cx).my_user_id else { |
| 969 | return; |
| 970 | }; |
| 971 | let store = self.app.read(cx).store.clone(); |
| 972 | let Some(current) = self.current.as_mut() else { |
| 973 | return; |
| 974 | }; |
| 975 | if current.first_unread.is_some() || current.mode != ViewMode::Flat { |
| 976 | return; |
| 977 | } |
| 978 | let limit = current |
| 979 | .loaded_limit |
| 980 | .max(current.loaded_count + GROWTH_HEADROOM); |
| 981 | current.first_unread = store |
| 982 | .messages(current.selection.conversation_id(), None, limit) |
| 983 | .unwrap_or_default() |
| 984 | .into_iter() |
| 985 | .find(|record| { |
| 986 | record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id) |
| 987 | }) |
| 988 | .map(|record| record.message_id); |
| 989 | } |
| 990 | |
| 991 | fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) { |
| 992 | let Some(sync) = self.sync_of(generation) else { |
| 993 | return; |
| 994 | }; |
| 995 | if sync.running() { |
| 996 | return; |
| 997 | } |
| 998 | let remaining = sync |
| 999 | .shown_at |
| 1000 | .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed())) |
| 1001 | .unwrap_or_default(); |
| 1002 | if remaining.is_zero() { |
| 1003 | sync.shown_at = None; |
| 1004 | sync.slow = false; |
| 1005 | cx.notify(); |
| 1006 | return; |
| 1007 | } |
| 1008 | cx.spawn(async move |this, cx| { |
| 1009 | cx.background_executor().timer(remaining).await; |
| 1010 | this.update(cx, |this, cx| { |
| 1011 | if let Some(sync) = this.sync_of(generation) { |
| 1012 | sync.shown_at = None; |
| 1013 | sync.slow = false; |
| 1014 | cx.notify(); |
| 1015 | } |
| 1016 | }) |
| 1017 | .ok(); |
| 1018 | }) |
| 1019 | .detach(); |
| 1020 | } |
| 1021 | |
| 1022 | fn retry_fetch(&mut self, cx: &mut Context<Self>) { |
| 1023 | if let Some(current) = self.current.as_mut() { |
| 1024 | current.fetched = false; |
| 1025 | } |
| 1026 | self.start_fetch(cx); |
| 1027 | } |
| 1028 | |
| 1029 | fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> { |
| 1030 | let state = self.app.read(cx); |
| 1031 | let receipts_syncing = self |
| 1032 | .current |
| 1033 | .as_ref() |
| 1034 | .is_some_and(|current| current.sync.receipts); |
| 1035 | if state.mode.demo { |
| 1036 | let read_ids = crate::demo::read_message_ids(records); |
| 1037 | return records |
| 1038 | .iter() |
| 1039 | .map(|record| { |
| 1040 | let receipt = if receipts_syncing { |
| 1041 | Receipt::Pending |
| 1042 | } else if read_ids.contains(&record.message_id) { |
| 1043 | Receipt::Read |
| 1044 | } else { |
| 1045 | Receipt::Sent |
| 1046 | }; |
| 1047 | (record.message_id.clone(), receipt) |
| 1048 | }) |
| 1049 | .collect(); |
| 1050 | } |
| 1051 | let Some(engine) = state.engine.as_ref() else { |
| 1052 | return HashMap::new(); |
| 1053 | }; |
| 1054 | let unknown = if receipts_syncing { |
| 1055 | Receipt::Pending |
| 1056 | } else { |
| 1057 | Receipt::Hidden |
| 1058 | }; |
| 1059 | records |
| 1060 | .iter() |
| 1061 | .map(|record| { |
| 1062 | let receipt = match engine.receipt_state_for(record) { |
| 1063 | teams_core::ReceiptState::Read { .. } => Receipt::Read, |
| 1064 | teams_core::ReceiptState::Sent => Receipt::Sent, |
| 1065 | teams_core::ReceiptState::Unknown => unknown, |
| 1066 | }; |
| 1067 | (record.message_id.clone(), receipt) |
| 1068 | }) |
| 1069 | .collect() |
| 1070 | } |
| 1071 | |
| 1072 | fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) { |
| 1073 | let state = self.app.read(cx); |
| 1074 | let (Some(engine), Some(Selection::Chat(chat_id))) = ( |
| 1075 | state.engine.clone(), |
| 1076 | self.current.as_ref().map(|c| c.selection.clone()), |
| 1077 | ) else { |
| 1078 | return; |
| 1079 | }; |
| 1080 | let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await }); |
| 1081 | cx.spawn(async move |this, cx| { |
| 1082 | receiver.await.ok(); |
| 1083 | this.update(cx, |this, cx| { |
| 1084 | let Some(sync) = this.sync_of(generation) else { |
| 1085 | return; |
| 1086 | }; |
| 1087 | sync.receipts = false; |
| 1088 | this.rebuild(false, cx); |
| 1089 | this.settle_progress(generation, cx); |
| 1090 | }) |
| 1091 | .ok(); |
| 1092 | }) |
| 1093 | .detach(); |
| 1094 | } |
| 1095 | |
| 1096 | fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) { |
| 1097 | if self.draft_active { |
| 1098 | return; |
| 1099 | } |
| 1100 | let state = self.app.read(cx); |
| 1101 | let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone()) |
| 1102 | else { |
| 1103 | return; |
| 1104 | }; |
| 1105 | if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only { |
| 1106 | return; |
| 1107 | } |
| 1108 | let unread = state |
| 1109 | .sidebar |
| 1110 | .chats |
| 1111 | .iter() |
| 1112 | .any(|chat| chat.id == chat_id && chat.unread); |
| 1113 | let Some(plan) = plan_read(self.window_active, unread, trigger) else { |
| 1114 | return; |
| 1115 | }; |
| 1116 | self.app |
| 1117 | .update(cx, |state, cx| state.mark_chat_read(&chat_id, cx)); |
| 1118 | if plan.clear_divider |
| 1119 | && let Some(current) = self.current.as_mut() |
| 1120 | && current.first_unread.take().is_some() |
| 1121 | { |
| 1122 | self.rebuild(false, cx); |
| 1123 | } |
| 1124 | } |
| 1125 | |
| 1126 | fn request_older(&mut self, cx: &mut Context<Self>) { |
| 1127 | let Some(engine) = self.app.read(cx).engine.clone() else { |
| 1128 | return; |
| 1129 | }; |
| 1130 | let Some(current) = self.current.as_mut() else { |
| 1131 | return; |
| 1132 | }; |
| 1133 | if current.loading_older || current.older_blocked || !current.has_older { |
| 1134 | return; |
| 1135 | } |
| 1136 | current.loading_older = true; |
| 1137 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 1138 | let task_id = conversation_id.clone(); |
| 1139 | let receiver = runtime::spawn(async move { engine.load_older(&task_id).await }); |
| 1140 | cx.spawn(async move |this, cx| { |
| 1141 | let result = receiver.await; |
| 1142 | this.update(cx, |this, cx| { |
| 1143 | this.finish_older(&conversation_id, result, cx) |
| 1144 | }) |
| 1145 | .ok(); |
| 1146 | }) |
| 1147 | .detach(); |
| 1148 | } |
| 1149 | |
| 1150 | fn finish_older( |
| 1151 | &mut self, |
| 1152 | conversation_id: &str, |
| 1153 | result: Result< |
| 1154 | teams_core::Result<Vec<MessageRecord>>, |
| 1155 | tokio::sync::oneshot::error::RecvError, |
| 1156 | >, |
| 1157 | cx: &mut Context<Self>, |
| 1158 | ) { |
| 1159 | let Some(current) = self.current.as_mut() else { |
| 1160 | return; |
| 1161 | }; |
| 1162 | if current.selection.conversation_id() != conversation_id { |
| 1163 | return; |
| 1164 | } |
| 1165 | current.loading_older = false; |
| 1166 | match result { |
| 1167 | Ok(Ok(records)) if !records.is_empty() => { |
| 1168 | current.loaded_limit = current.loaded_count + records.len(); |
| 1169 | } |
| 1170 | Ok(Ok(_)) => current.older_blocked = true, |
| 1171 | Ok(Err(error)) => { |
| 1172 | current.older_blocked = true; |
| 1173 | self.notice = Some(format!( |
| 1174 | "Could not load older messages: {}", |
| 1175 | short_error(&error) |
| 1176 | )); |
| 1177 | } |
| 1178 | Err(_) => current.older_blocked = true, |
| 1179 | } |
| 1180 | self.rebuild(false, cx); |
| 1181 | } |
| 1182 | |
| 1183 | fn clear_pending(&mut self) { |
| 1184 | self.pending.clear(); |
| 1185 | self.pending_outgoing.clear(); |
| 1186 | } |
| 1187 | |
| 1188 | fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) { |
| 1189 | if let Some(current) = self.current.as_mut() { |
| 1190 | current.mode = ViewMode::Thread(root_id); |
| 1191 | } |
| 1192 | self.clear_pending(); |
| 1193 | self.rebuild(true, cx); |
| 1194 | } |
| 1195 | |
| 1196 | fn back_to_threads(&mut self, cx: &mut Context<Self>) { |
| 1197 | if let Some(current) = self.current.as_mut() { |
| 1198 | current.mode = ViewMode::ThreadList; |
| 1199 | } |
| 1200 | self.clear_pending(); |
| 1201 | self.rebuild(true, cx); |
| 1202 | } |
| 1203 | |
| 1204 | fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) { |
| 1205 | let state = self.app.read(cx); |
| 1206 | let (mode, engine) = (state.mode, state.engine.clone()); |
| 1207 | let Some(current) = self.current.as_ref() else { |
| 1208 | return; |
| 1209 | }; |
| 1210 | if mode.read_only || mode.demo { |
| 1211 | self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx); |
| 1212 | return; |
| 1213 | } |
| 1214 | let Some(engine) = engine else { |
| 1215 | self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx); |
| 1216 | return; |
| 1217 | }; |
| 1218 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 1219 | let view_mode = current.mode.clone(); |
| 1220 | let key = self.push_pending(&outgoing, cx); |
| 1221 | self.notice = None; |
| 1222 | self.rebuild(false, cx); |
| 1223 | self.scroller |
| 1224 | .update(cx, |scroller, cx| scroller.scroll_to_end(cx)); |
| 1225 | |
| 1226 | let sent = outgoing.clone(); |
| 1227 | let receiver = runtime::spawn(async move { |
| 1228 | let extras = sent.extras(); |
| 1229 | let Outgoing { |
| 1230 | text, |
| 1231 | mentions, |
| 1232 | reply, |
| 1233 | .. |
| 1234 | } = &sent; |
| 1235 | match (&view_mode, reply) { |
| 1236 | (_, Some(reply)) => { |
| 1237 | engine |
| 1238 | .reply_to_with_extras( |
| 1239 | &conversation_id, |
| 1240 | &reply.message_id, |
| 1241 | text, |
| 1242 | mentions, |
| 1243 | &extras, |
| 1244 | ) |
| 1245 | .await |
| 1246 | } |
| 1247 | (ViewMode::Flat, None) => { |
| 1248 | engine |
| 1249 | .send_message_with_extras(&conversation_id, text, None, mentions, &extras) |
| 1250 | .await |
| 1251 | } |
| 1252 | (ViewMode::ThreadList, None) => { |
| 1253 | engine |
| 1254 | .post_to_channel_with_extras( |
| 1255 | &conversation_id, |
| 1256 | text, |
| 1257 | None, |
| 1258 | mentions, |
| 1259 | &extras, |
| 1260 | ) |
| 1261 | .await |
| 1262 | } |
| 1263 | (ViewMode::Thread(root_id), None) => { |
| 1264 | engine |
| 1265 | .send_message_with_extras( |
| 1266 | &conversation_id, |
| 1267 | text, |
| 1268 | Some(root_id), |
| 1269 | mentions, |
| 1270 | &extras, |
| 1271 | ) |
| 1272 | .await |
| 1273 | } |
| 1274 | } |
| 1275 | .map(|_| ()) |
| 1276 | }); |
| 1277 | cx.spawn_in(window, async move |this, cx| { |
| 1278 | let result = receiver.await; |
| 1279 | this.update(cx, |this, cx| this.finish_send(&key, result, cx)) |
| 1280 | .ok(); |
| 1281 | }) |
| 1282 | .detach(); |
| 1283 | } |
| 1284 | |
| 1285 | fn restore_unsent( |
| 1286 | &mut self, |
| 1287 | message: &str, |
| 1288 | outgoing: &Outgoing, |
| 1289 | window: &mut Window, |
| 1290 | cx: &mut Context<Self>, |
| 1291 | ) { |
| 1292 | self.notice = Some(message.to_owned()); |
| 1293 | self.composer |
| 1294 | .update(cx, |composer, cx| composer.restore(outgoing, window, cx)); |
| 1295 | cx.notify(); |
| 1296 | } |
| 1297 | |
| 1298 | fn push_pending(&mut self, outgoing: &Outgoing, cx: &App) -> String { |
| 1299 | self.pending_counter += 1; |
| 1300 | let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter); |
| 1301 | let my_user_id = self.row_context(cx).my_user_id; |
| 1302 | self.pending_outgoing.insert(key.clone(), outgoing.clone()); |
| 1303 | self.pending.push(MessageRow { |
| 1304 | key: key.clone(), |
| 1305 | author: "You".to_owned(), |
| 1306 | sender_id: my_user_id, |
| 1307 | created_at: Utc::now(), |
| 1308 | series: Series::default(), |
| 1309 | card: false, |
| 1310 | time: chrono::Local::now().format("%H:%M").to_string(), |
| 1311 | day_header: None, |
| 1312 | blocks: if outgoing.text.is_empty() { |
| 1313 | Vec::new() |
| 1314 | } else { |
| 1315 | vec![Block::Paragraph(Inline::plain(&outgoing.text))] |
| 1316 | }, |
| 1317 | edited: false, |
| 1318 | deleted: false, |
| 1319 | reactions: Vec::new(), |
| 1320 | images: Vec::new(), |
| 1321 | local_images: outgoing |
| 1322 | .images |
| 1323 | .iter() |
| 1324 | .map(|image| LocalImage { |
| 1325 | image: image.image.clone(), |
| 1326 | size: image.dimensions, |
| 1327 | }) |
| 1328 | .collect(), |
| 1329 | files: outgoing |
| 1330 | .files |
| 1331 | .iter() |
| 1332 | .map(|file| FileCard { |
| 1333 | name: file.name.clone(), |
| 1334 | kind: file.kind, |
| 1335 | content_type: None, |
| 1336 | size: Some(file.size), |
| 1337 | open_url: file.reference.content_url.clone(), |
| 1338 | }) |
| 1339 | .collect(), |
| 1340 | reply_count: None, |
| 1341 | new_marker: false, |
| 1342 | reply_faces: Vec::new(), |
| 1343 | last_reply_time: None, |
| 1344 | open_thread: None, |
| 1345 | is_reply: false, |
| 1346 | delivery: Delivery::Sending, |
| 1347 | receipt: Receipt::Hidden, |
| 1348 | own: true, |
| 1349 | }); |
| 1350 | key |
| 1351 | } |
| 1352 | |
| 1353 | fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) { |
| 1354 | let (recipients, topic) = { |
| 1355 | let draft = self.draft.read(cx); |
| 1356 | let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty()); |
| 1357 | (draft.chips().to_vec(), topic) |
| 1358 | }; |
| 1359 | if recipients.is_empty() { |
| 1360 | self.restore_unsent("Add at least one person first", &outgoing, window, cx); |
| 1361 | self.draft |
| 1362 | .update(cx, |draft, cx| draft.focus_query(window, cx)); |
| 1363 | return; |
| 1364 | } |
| 1365 | if self |
| 1366 | .pending |
| 1367 | .iter() |
| 1368 | .any(|row| matches!(row.delivery, Delivery::Sending)) |
| 1369 | { |
| 1370 | self.restore_unsent("Still creating the chat", &outgoing, window, cx); |
| 1371 | return; |
| 1372 | } |
| 1373 | let state = self.app.read(cx); |
| 1374 | let (mode, engine) = (state.mode, state.engine.clone()); |
| 1375 | if mode.read_only { |
| 1376 | self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx); |
| 1377 | return; |
| 1378 | } |
| 1379 | if mode.demo && outgoing.has_attachments() { |
| 1380 | self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx); |
| 1381 | return; |
| 1382 | } |
| 1383 | if mode.demo { |
| 1384 | self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx); |
| 1385 | return; |
| 1386 | } |
| 1387 | let Some(engine) = engine else { |
| 1388 | self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx); |
| 1389 | return; |
| 1390 | }; |
| 1391 | let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect(); |
| 1392 | let known_chat = self |
| 1393 | .draft_created |
| 1394 | .as_ref() |
| 1395 | .filter(|(created_for, _)| *created_for == user_ids) |
| 1396 | .map(|(_, chat_id)| chat_id.clone()) |
| 1397 | .or_else(|| self.draft_target_chat(cx)); |
| 1398 | self.pending.clear(); |
| 1399 | self.pending_outgoing.clear(); |
| 1400 | self.draft_error = None; |
| 1401 | self.notice = None; |
| 1402 | let key = self.push_pending(&outgoing, cx); |
| 1403 | self.rebuild(true, cx); |
| 1404 | let recipients_for_finish = user_ids.clone(); |
| 1405 | let receiver = runtime::spawn(async move { |
| 1406 | let chat_id = match known_chat { |
| 1407 | Some(chat_id) => chat_id, |
| 1408 | None => { |
| 1409 | let created = match user_ids.as_slice() { |
| 1410 | [user_id] => engine.create_one_on_one(user_id).await, |
| 1411 | _ => engine.create_group(&user_ids, topic.as_deref()).await, |
| 1412 | }; |
| 1413 | match created { |
| 1414 | Ok(chat_id) => chat_id, |
| 1415 | Err(error) => return (None, Some(short_error(&error))), |
| 1416 | } |
| 1417 | } |
| 1418 | }; |
| 1419 | let sent = engine |
| 1420 | .send_message_with_extras( |
| 1421 | &chat_id, |
| 1422 | &outgoing.text, |
| 1423 | None, |
| 1424 | &outgoing.mentions, |
| 1425 | &outgoing.extras(), |
| 1426 | ) |
| 1427 | .await; |
| 1428 | (Some(chat_id), sent.err().map(|error| short_error(&error))) |
| 1429 | }); |
| 1430 | cx.spawn_in(window, async move |this, cx| { |
| 1431 | let result = receiver.await; |
| 1432 | this.update_in(cx, |this, _, cx| { |
| 1433 | this.finish_new_chat(&key, recipients_for_finish, result, cx) |
| 1434 | }) |
| 1435 | .ok(); |
| 1436 | }) |
| 1437 | .detach(); |
| 1438 | } |
| 1439 | |
| 1440 | fn finish_new_chat( |
| 1441 | &mut self, |
| 1442 | key: &str, |
| 1443 | user_ids: Vec<String>, |
| 1444 | result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>, |
| 1445 | cx: &mut Context<Self>, |
| 1446 | ) { |
| 1447 | if !self.draft_active || !self.pending.iter().any(|row| row.key == key) { |
| 1448 | return; |
| 1449 | } |
| 1450 | let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned()))); |
| 1451 | self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id)); |
| 1452 | match (chat_id, error) { |
| 1453 | (Some(chat_id), None) => { |
| 1454 | self.app.update(cx, |state, cx| { |
| 1455 | state.reload_sidebar(cx); |
| 1456 | state.select(Selection::Chat(chat_id), cx); |
| 1457 | }); |
| 1458 | } |
| 1459 | (created, error) => { |
| 1460 | if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) { |
| 1461 | row.delivery = Delivery::Failed(error.unwrap_or_default()); |
| 1462 | } |
| 1463 | self.draft_error = Some( |
| 1464 | if created.is_some() { |
| 1465 | "Couldn't send the message." |
| 1466 | } else { |
| 1467 | "Couldn't create the chat." |
| 1468 | } |
| 1469 | .to_owned(), |
| 1470 | ); |
| 1471 | self.rebuild(false, cx); |
| 1472 | } |
| 1473 | } |
| 1474 | } |
| 1475 | |
| 1476 | fn send_demo_new_chat( |
| 1477 | &mut self, |
| 1478 | outgoing: &Outgoing, |
| 1479 | recipients: &[super::new_chat::Pick], |
| 1480 | topic: Option<&str>, |
| 1481 | cx: &mut Context<Self>, |
| 1482 | ) { |
| 1483 | let (store, chats) = { |
| 1484 | let state = self.app.read(cx); |
| 1485 | (state.store.clone(), state.sidebar.chats.clone()) |
| 1486 | }; |
| 1487 | let people: Vec<(String, String)> = recipients |
| 1488 | .iter() |
| 1489 | .map(|pick| (pick.user_id.clone(), pick.name.clone())) |
| 1490 | .collect(); |
| 1491 | let (chat, message) = match self.draft_target_chat(cx) { |
| 1492 | Some(chat_id) => { |
| 1493 | let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else { |
| 1494 | return; |
| 1495 | }; |
| 1496 | crate::demo::send_in_chat(chat, &outgoing.text, Utc::now()) |
| 1497 | } |
| 1498 | None => crate::demo::new_chat(&chats, &people, topic, &outgoing.text, Utc::now()), |
| 1499 | }; |
| 1500 | let _ = store.upsert_chats(std::slice::from_ref(&chat)); |
| 1501 | let _ = store.upsert_messages(std::slice::from_ref(&message)); |
| 1502 | self.app.update(cx, |state, cx| { |
| 1503 | state.reload_sidebar(cx); |
| 1504 | state.select(Selection::Chat(chat.id.clone()), cx); |
| 1505 | }); |
| 1506 | } |
| 1507 | |
| 1508 | fn conversation_id(&self) -> Option<String> { |
| 1509 | self.current |
| 1510 | .as_ref() |
| 1511 | .map(|current| current.selection.conversation_id().to_owned()) |
| 1512 | } |
| 1513 | |
| 1514 | fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> { |
| 1515 | let conversation_id = self.conversation_id()?; |
| 1516 | let my_user_id = self.row_context(cx).my_user_id?; |
| 1517 | self.app |
| 1518 | .read(cx) |
| 1519 | .store |
| 1520 | .messages_by_id(&conversation_id, &[message_id.to_owned()]) |
| 1521 | .ok()? |
| 1522 | .remove(message_id) |
| 1523 | .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id)) |
| 1524 | } |
| 1525 | |
| 1526 | fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) { |
| 1527 | let target = match slot { |
| 1528 | HoverSlot::Row => &mut self.hovered_message, |
| 1529 | HoverSlot::Toolbar => &mut self.toolbar_hovered, |
| 1530 | }; |
| 1531 | if hovered { |
| 1532 | *target = Some(key.to_owned()); |
| 1533 | } else if target.as_deref() == Some(key) { |
| 1534 | *target = None; |
| 1535 | } |
| 1536 | cx.notify(); |
| 1537 | } |
| 1538 | |
| 1539 | fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) { |
| 1540 | if open { |
| 1541 | self.toolbar_pinned = Some(key.to_owned()); |
| 1542 | } else if self.toolbar_pinned.as_deref() == Some(key) { |
| 1543 | self.toolbar_pinned = None; |
| 1544 | } |
| 1545 | cx.notify(); |
| 1546 | } |
| 1547 | |
| 1548 | fn toolbar_visible(&self, key: &str) -> bool { |
| 1549 | self.toolbar_pinned |
| 1550 | .as_deref() |
| 1551 | .or(self.toolbar_hovered.as_deref()) |
| 1552 | .or(self.hovered_message.as_deref()) |
| 1553 | == Some(key) |
| 1554 | } |
| 1555 | |
| 1556 | fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) { |
| 1557 | let Some(conversation_id) = self.conversation_id() else { |
| 1558 | return; |
| 1559 | }; |
| 1560 | let reaction_type = reaction_type_for(glyph); |
| 1561 | let wanted = reaction_glyph(glyph); |
| 1562 | let state = self.app.read(cx); |
| 1563 | let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone()); |
| 1564 | let my_user_id = self.row_context(cx).my_user_id; |
| 1565 | let Some(mut record) = store |
| 1566 | .messages_by_id(&conversation_id, &[message_id.to_owned()]) |
| 1567 | .ok() |
| 1568 | .and_then(|mut found| found.remove(message_id)) |
| 1569 | else { |
| 1570 | return; |
| 1571 | }; |
| 1572 | let mut reactions = teams_core::reactions(&record); |
| 1573 | let mine = |reaction: &teams_core::ReactionInfo| { |
| 1574 | reaction_glyph(&reaction.reaction_type) == wanted |
| 1575 | && my_user_id.is_some() |
| 1576 | && reaction.user_id == my_user_id |
| 1577 | }; |
| 1578 | let remove = reactions.iter().any(mine); |
| 1579 | if mode.demo { |
| 1580 | if remove { |
| 1581 | reactions.retain(|reaction| !mine(reaction)); |
| 1582 | } else { |
| 1583 | reactions.push(teams_core::ReactionInfo { |
| 1584 | reaction_type: reaction_type.clone(), |
| 1585 | user_id: my_user_id.clone(), |
| 1586 | user_name: Some("You".to_owned()), |
| 1587 | }); |
| 1588 | } |
| 1589 | record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default(); |
| 1590 | let _ = store.upsert_messages(std::slice::from_ref(&record)); |
| 1591 | self.rebuild(false, cx); |
| 1592 | return; |
| 1593 | } |
| 1594 | let Some(engine) = engine.filter(|_| !mode.read_only) else { |
| 1595 | self.show_notice("Read-only mode: reaction not sent", cx); |
| 1596 | return; |
| 1597 | }; |
| 1598 | let message_id = message_id.to_owned(); |
| 1599 | let reaction_type = api_reaction(&wanted); |
| 1600 | let receiver = runtime::spawn(async move { |
| 1601 | if remove { |
| 1602 | engine |
| 1603 | .unset_reaction(&conversation_id, &message_id, &reaction_type) |
| 1604 | .await |
| 1605 | } else { |
| 1606 | engine |
| 1607 | .set_reaction(&conversation_id, &message_id, &reaction_type) |
| 1608 | .await |
| 1609 | } |
| 1610 | }); |
| 1611 | self.report_failure(receiver, "Reaction failed", cx); |
| 1612 | } |
| 1613 | |
| 1614 | fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 1615 | let Some(record) = self.own_record(message_id, cx) else { |
| 1616 | return; |
| 1617 | }; |
| 1618 | let edit = EditPreview { |
| 1619 | message_id: record.message_id.clone(), |
| 1620 | excerpt: reply_excerpt(&record), |
| 1621 | }; |
| 1622 | let in_chat = matches!( |
| 1623 | self.current.as_ref().map(|current| ¤t.selection), |
| 1624 | Some(Selection::Chat(_)) |
| 1625 | ); |
| 1626 | let mentions = if in_chat { |
| 1627 | teams_core::mentions(&record) |
| 1628 | .into_iter() |
| 1629 | .filter_map(|mention| { |
| 1630 | let user_id = mention.user_id?; |
| 1631 | Some(MentionInput::user(&user_id, &mention.name)) |
| 1632 | }) |
| 1633 | .collect() |
| 1634 | } else { |
| 1635 | Vec::new() |
| 1636 | }; |
| 1637 | let draft = Outgoing { |
| 1638 | text: message_text(&record), |
| 1639 | mentions, |
| 1640 | reply: None, |
| 1641 | edit: Some(edit), |
| 1642 | images: Vec::new(), |
| 1643 | files: Vec::new(), |
| 1644 | }; |
| 1645 | self.composer |
| 1646 | .update(cx, |composer, cx| composer.begin_edit(draft, window, cx)); |
| 1647 | } |
| 1648 | |
| 1649 | fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1650 | if self.draft_active { |
| 1651 | return; |
| 1652 | } |
| 1653 | let key = self.rows.borrow().iter().rev().find_map(|row| match row { |
| 1654 | Row::Message(message) |
| 1655 | if message.own |
| 1656 | && !message.deleted |
| 1657 | && !message.key.starts_with(PENDING_KEY_PREFIX) => |
| 1658 | { |
| 1659 | Some(message.key.clone()) |
| 1660 | } |
| 1661 | _ => None, |
| 1662 | }); |
| 1663 | if let Some(key) = key { |
| 1664 | self.begin_edit(&key, window, cx); |
| 1665 | } |
| 1666 | } |
| 1667 | |
| 1668 | fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) { |
| 1669 | let Some(edit) = outgoing.edit.clone() else { |
| 1670 | return; |
| 1671 | }; |
| 1672 | let Some(conversation_id) = self.conversation_id() else { |
| 1673 | return; |
| 1674 | }; |
| 1675 | let state = self.app.read(cx); |
| 1676 | let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone()); |
| 1677 | if mode.demo { |
| 1678 | if let Some(mut record) = self.own_record(&edit.message_id, cx) { |
| 1679 | record.body_html = teams_core::markdown_to_html(&outgoing.text); |
| 1680 | record.edited_at = Some(Utc::now()); |
| 1681 | let _ = store.upsert_messages(std::slice::from_ref(&record)); |
| 1682 | self.rebuild(false, cx); |
| 1683 | } |
| 1684 | return; |
| 1685 | } |
| 1686 | let Some(engine) = engine.filter(|_| !mode.read_only) else { |
| 1687 | self.notice = Some("Read-only mode: edit not saved".to_owned()); |
| 1688 | self.composer |
| 1689 | .update(cx, |composer, cx| composer.restore(&outgoing, window, cx)); |
| 1690 | cx.notify(); |
| 1691 | return; |
| 1692 | }; |
| 1693 | let sent = outgoing.clone(); |
| 1694 | let receiver = runtime::spawn(async move { |
| 1695 | engine |
| 1696 | .edit_message_with_mentions( |
| 1697 | &conversation_id, |
| 1698 | &edit.message_id, |
| 1699 | &sent.text, |
| 1700 | &sent.mentions, |
| 1701 | ) |
| 1702 | .await |
| 1703 | }); |
| 1704 | cx.spawn_in(window, async move |this, cx| { |
| 1705 | let failed = !matches!(receiver.await, Ok(Ok(()))); |
| 1706 | this.update_in(cx, |this, window, cx| { |
| 1707 | if failed { |
| 1708 | if this.composer.read(cx).is_empty(cx) { |
| 1709 | this.notice = |
| 1710 | Some("Edit failed: your text is back in the composer".to_owned()); |
| 1711 | this.composer |
| 1712 | .update(cx, |composer, cx| composer.restore(&outgoing, window, cx)); |
| 1713 | } else { |
| 1714 | this.notice = Some("Edit failed".to_owned()); |
| 1715 | } |
| 1716 | cx.notify(); |
| 1717 | } |
| 1718 | }) |
| 1719 | .ok(); |
| 1720 | }) |
| 1721 | .detach(); |
| 1722 | } |
| 1723 | |
| 1724 | fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) { |
| 1725 | let Some(mut record) = self.own_record(message_id, cx) else { |
| 1726 | return; |
| 1727 | }; |
| 1728 | let state = self.app.read(cx); |
| 1729 | let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone()); |
| 1730 | if mode.demo { |
| 1731 | record.deleted = true; |
| 1732 | let _ = store.upsert_messages(std::slice::from_ref(&record)); |
| 1733 | self.rebuild(false, cx); |
| 1734 | return; |
| 1735 | } |
| 1736 | let Some(engine) = engine.filter(|_| !mode.read_only) else { |
| 1737 | self.show_notice("Read-only mode: message not deleted", cx); |
| 1738 | return; |
| 1739 | }; |
| 1740 | let conversation_id = record.conversation_id.clone(); |
| 1741 | let receiver = runtime::spawn(async move { |
| 1742 | engine |
| 1743 | .soft_delete_message(&conversation_id, &record.message_id) |
| 1744 | .await |
| 1745 | }); |
| 1746 | self.report_failure(receiver, "Delete failed", cx); |
| 1747 | } |
| 1748 | |
| 1749 | fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) { |
| 1750 | let Some(conversation_id) = self.conversation_id() else { |
| 1751 | return; |
| 1752 | }; |
| 1753 | let record = self |
| 1754 | .app |
| 1755 | .read(cx) |
| 1756 | .store |
| 1757 | .messages_by_id(&conversation_id, &[message_id.to_owned()]) |
| 1758 | .ok() |
| 1759 | .and_then(|mut found| found.remove(message_id)); |
| 1760 | if let Some(record) = record { |
| 1761 | cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record))); |
| 1762 | } |
| 1763 | } |
| 1764 | |
| 1765 | fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) { |
| 1766 | self.notice = Some(message.to_owned()); |
| 1767 | cx.notify(); |
| 1768 | } |
| 1769 | |
| 1770 | fn report_failure( |
| 1771 | &mut self, |
| 1772 | receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>, |
| 1773 | label: &'static str, |
| 1774 | cx: &mut Context<Self>, |
| 1775 | ) { |
| 1776 | cx.spawn(async move |this, cx| { |
| 1777 | let error = match receiver.await { |
| 1778 | Ok(Ok(())) => return, |
| 1779 | Ok(Err(error)) => short_error(&error), |
| 1780 | Err(_) => "cancelled".to_owned(), |
| 1781 | }; |
| 1782 | this.update(cx, |this, cx| { |
| 1783 | this.show_notice(&format!("{label}: {error}"), cx) |
| 1784 | }) |
| 1785 | .ok(); |
| 1786 | }) |
| 1787 | .detach(); |
| 1788 | } |
| 1789 | |
| 1790 | fn message_menu(&self, key: &str, own: bool, view: WeakEntity<Self>) -> MessageMenu { |
| 1791 | let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action { |
| 1792 | let (view, key) = (view.clone(), key.to_owned()); |
| 1793 | Rc::new(move |window, cx| { |
| 1794 | view.update(cx, |this, cx| run(this, &key, window, cx)).ok(); |
| 1795 | }) |
| 1796 | }; |
| 1797 | let react: PickHandler = { |
| 1798 | let (view, key) = (view.clone(), key.to_owned()); |
| 1799 | Rc::new(move |glyph, _, cx| { |
| 1800 | view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx)) |
| 1801 | .ok(); |
| 1802 | }) |
| 1803 | }; |
| 1804 | let hover = { |
| 1805 | let (view, key) = (view.clone(), key.to_owned()); |
| 1806 | Rc::new(move |hovered: bool, cx: &mut App| { |
| 1807 | view.update(cx, |this, cx| { |
| 1808 | this.set_hover(HoverSlot::Toolbar, &key, hovered, cx) |
| 1809 | }) |
| 1810 | .ok(); |
| 1811 | }) |
| 1812 | }; |
| 1813 | let pin = { |
| 1814 | let (view, key) = (view.clone(), key.to_owned()); |
| 1815 | Rc::new(move |open: bool, _: &mut Window, cx: &mut App| { |
| 1816 | view.update(cx, |this, cx| this.set_pinned(&key, open, cx)) |
| 1817 | .ok(); |
| 1818 | }) |
| 1819 | }; |
| 1820 | MessageMenu { |
| 1821 | key: key.to_owned(), |
| 1822 | react, |
| 1823 | reply: Some(action(|this, key, window, cx| { |
| 1824 | this.begin_reply(key, window, cx) |
| 1825 | })), |
| 1826 | copy: action(|this, key, _, cx| this.copy_text(key, cx)), |
| 1827 | edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))), |
| 1828 | delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))), |
| 1829 | pin, |
| 1830 | hover, |
| 1831 | picker: self.picker.clone(), |
| 1832 | } |
| 1833 | } |
| 1834 | |
| 1835 | fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 1836 | let Some(outgoing) = self.pending_outgoing.remove(key) else { |
| 1837 | return; |
| 1838 | }; |
| 1839 | self.pending.retain(|row| row.key != key); |
| 1840 | if self.draft_active { |
| 1841 | self.send_new_chat(outgoing, window, cx); |
| 1842 | } else { |
| 1843 | self.send(outgoing, window, cx); |
| 1844 | } |
| 1845 | } |
| 1846 | |
| 1847 | fn finish_send( |
| 1848 | &mut self, |
| 1849 | key: &str, |
| 1850 | result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>, |
| 1851 | cx: &mut Context<Self>, |
| 1852 | ) { |
| 1853 | let failure = match result { |
| 1854 | Ok(Ok(())) => None, |
| 1855 | Ok(Err(error)) => Some(short_error(&error)), |
| 1856 | Err(error) => Some(short_error(&error)), |
| 1857 | }; |
| 1858 | match failure { |
| 1859 | None => { |
| 1860 | self.pending.retain(|row| row.key != key); |
| 1861 | self.pending_outgoing.remove(key); |
| 1862 | } |
| 1863 | Some(error) => { |
| 1864 | if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) { |
| 1865 | row.delivery = Delivery::Failed(error.clone()); |
| 1866 | self.notice = Some(format!("Not sent: {error}")); |
| 1867 | } |
| 1868 | } |
| 1869 | } |
| 1870 | self.rebuild(false, cx); |
| 1871 | } |
| 1872 | |
| 1873 | fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement { |
| 1874 | let target = match self.current.as_ref().map(|current| ¤t.selection) { |
| 1875 | Some(Selection::Chat(_)) => DropTarget::Chat, |
| 1876 | Some(Selection::Channel(_)) => DropTarget::Channel, |
| 1877 | None => DropTarget::NewChat, |
| 1878 | }; |
| 1879 | let title = self |
| 1880 | .current |
| 1881 | .as_ref() |
| 1882 | .map(|current| current.title.as_str()) |
| 1883 | .unwrap_or_default(); |
| 1884 | let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1)); |
| 1885 | let composer = self.composer.clone(); |
| 1886 | div() |
| 1887 | .id("drop-overlay") |
| 1888 | .absolute() |
| 1889 | .top_0() |
| 1890 | .left_0() |
| 1891 | .size_full() |
| 1892 | .opacity(0.) |
| 1893 | .bg(theme::drop_background()) |
| 1894 | .drag_over::<ExternalPaths>(move |style, _, _, cx| { |
| 1895 | if composer.read(cx).is_editing() { |
| 1896 | style |
| 1897 | } else { |
| 1898 | style.opacity(1.) |
| 1899 | } |
| 1900 | }) |
| 1901 | .on_drag_move( |
| 1902 | cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| { |
| 1903 | let count = event.drag(cx).paths().len(); |
| 1904 | if this.drag_file_count != count { |
| 1905 | this.drag_file_count = count; |
| 1906 | cx.notify(); |
| 1907 | } |
| 1908 | }), |
| 1909 | ) |
| 1910 | .on_drop(cx.listener(|this, dropped: &ExternalPaths, _, cx| { |
| 1911 | let paths = dropped.paths().to_vec(); |
| 1912 | this.composer |
| 1913 | .update(cx, |composer, cx| composer.add_paths(paths, cx)); |
| 1914 | })) |
| 1915 | .child( |
| 1916 | div() |
| 1917 | .absolute() |
| 1918 | .inset(px(12.)) |
| 1919 | .rounded(px(12.)) |
| 1920 | .border_2() |
| 1921 | .border_dashed() |
| 1922 | .border_color(theme::accent()) |
| 1923 | .flex() |
| 1924 | .items_center() |
| 1925 | .justify_center() |
| 1926 | .child( |
| 1927 | v_flex() |
| 1928 | .items_center() |
| 1929 | .gap(px(6.)) |
| 1930 | .px(px(28.)) |
| 1931 | .py(px(18.)) |
| 1932 | .rounded(px(12.)) |
| 1933 | .bg(black().opacity(0.55)) |
| 1934 | .child(symbol("upload", 28., theme::accent_text())) |
| 1935 | .child( |
| 1936 | div() |
| 1937 | .text_size(px(15.)) |
| 1938 | .font_weight(FontWeight::SEMIBOLD) |
| 1939 | .text_color(theme::text_strong()) |
| 1940 | .child(heading), |
| 1941 | ) |
| 1942 | .child( |
| 1943 | div() |
| 1944 | .text_size(px(12.)) |
| 1945 | .text_color(theme::text_muted()) |
| 1946 | .child(detail), |
| 1947 | ), |
| 1948 | ), |
| 1949 | ) |
| 1950 | } |
| 1951 | |
| 1952 | fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> { |
| 1953 | let message = self.draft_error.clone()?; |
| 1954 | let failed_key = self |
| 1955 | .pending |
| 1956 | .iter() |
| 1957 | .find(|row| matches!(row.delivery, Delivery::Failed(_))) |
| 1958 | .map(|row| row.key.clone())?; |
| 1959 | Some( |
| 1960 | h_flex() |
| 1961 | .w_full() |
| 1962 | .flex_none() |
| 1963 | .px(px(24.)) |
| 1964 | .py(px(4.)) |
| 1965 | .gap(px(8.)) |
| 1966 | .items_center() |
| 1967 | .text_size(px(12.)) |
| 1968 | .text_color(theme::red_soft()) |
| 1969 | .child(message) |
| 1970 | .child( |
| 1971 | Button::new("retry-new-chat") |
| 1972 | .ghost() |
| 1973 | .compact() |
| 1974 | .label("Retry") |
| 1975 | .on_click(cx.listener(move |this, _, window, cx| { |
| 1976 | this.retry(&failed_key, window, cx) |
| 1977 | })), |
| 1978 | ), |
| 1979 | ) |
| 1980 | } |
| 1981 | |
| 1982 | fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement { |
| 1983 | let app = self.app.read(cx); |
| 1984 | let directory = &app.directory; |
| 1985 | let me = directory.me.as_ref(); |
| 1986 | let mut lead: Option<AnyElement> = None; |
| 1987 | let mut subline = String::new(); |
| 1988 | let mut stack: Option<Div> = None; |
| 1989 | match ¤t.selection { |
| 1990 | Selection::Chat(chat_id) => { |
| 1991 | if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) { |
| 1992 | let faces = others(chat, me); |
| 1993 | let face = |(user_id, name): (Option<String>, String)| Face { user_id, name }; |
| 1994 | let first = faces.first().cloned().map(face); |
| 1995 | if is_one_on_one(chat) || faces.len() < 2 { |
| 1996 | let name = first |
| 1997 | .as_ref() |
| 1998 | .map_or(current.title.as_str(), |face| face.name.as_str()); |
| 1999 | let user_id = first.as_ref().and_then(|face| face.user_id.as_deref()); |
| 2000 | let avatar = person_avatar(directory, user_id, name, 36.); |
| 2001 | let presence = user_id.map(|id| directory.presence_of(id)); |
| 2002 | lead = Some(match presence { |
| 2003 | Some(kind) => with_presence(avatar, kind, 36., theme::background()) |
| 2004 | .into_any_element(), |
| 2005 | None => avatar, |
| 2006 | }); |
| 2007 | subline = presence |
| 2008 | .map(|presence| presence.kind().label().to_owned()) |
| 2009 | .unwrap_or_default(); |
| 2010 | } else { |
| 2011 | let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone())); |
| 2012 | lead = Some(spec_avatar(directory, &pair, 36., theme::background())); |
| 2013 | subline = format!("{} participants", chat.members.len()); |
| 2014 | let shown: Vec<Face> = faces.iter().cloned().map(face).collect(); |
| 2015 | stack = Some(member_stack(directory, &shown, shown.len())); |
| 2016 | } |
| 2017 | } |
| 2018 | } |
| 2019 | Selection::Channel(channel_id) => { |
| 2020 | let team = app.sidebar.teams.iter().find(|entry| { |
| 2021 | entry |
| 2022 | .channels |
| 2023 | .iter() |
| 2024 | .any(|channel| &channel.id == channel_id) |
| 2025 | }); |
| 2026 | let (name, key) = team |
| 2027 | .map_or((current.title.as_str(), current.title.as_str()), |entry| { |
| 2028 | (entry.team.name.as_str(), entry.team.id.as_str()) |
| 2029 | }); |
| 2030 | lead = Some(square_avatar(name, key, 36., 9.).into_any_element()); |
| 2031 | } |
| 2032 | } |
| 2033 | let mut header = h_flex() |
| 2034 | .w_full() |
| 2035 | .h(px(60.)) |
| 2036 | .flex_none() |
| 2037 | .px(px(20.)) |
| 2038 | .gap(px(12.)) |
| 2039 | .items_center() |
| 2040 | .border_b_1() |
| 2041 | .border_color(theme::border()); |
| 2042 | if matches!(current.mode, ViewMode::Thread(_)) { |
| 2043 | header = header.child( |
| 2044 | Button::new("back-to-threads") |
| 2045 | .ghost() |
| 2046 | .compact() |
| 2047 | .label("Threads") |
| 2048 | .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx))), |
| 2049 | ); |
| 2050 | } |
| 2051 | let channel_note = match current.mode { |
| 2052 | ViewMode::Flat => None, |
| 2053 | ViewMode::ThreadList => Some("Threads"), |
| 2054 | ViewMode::Thread(_) => Some("Thread"), |
| 2055 | }; |
| 2056 | if let Some(note) = channel_note { |
| 2057 | subline = note.to_owned(); |
| 2058 | } |
| 2059 | let sync = ¤t.sync; |
| 2060 | if sync.failed { |
| 2061 | subline = "Not up to date".to_owned(); |
| 2062 | } else if sync.shown_at.is_some() { |
| 2063 | subline = if sync.slow { |
| 2064 | "Taking longer than usual ..." |
| 2065 | } else if sync.empty_cache { |
| 2066 | "Loading messages ..." |
| 2067 | } else { |
| 2068 | "Updating ..." |
| 2069 | } |
| 2070 | .to_owned(); |
| 2071 | } |
| 2072 | header |
| 2073 | .relative() |
| 2074 | .when(sync.shown_at.is_some(), |header| { |
| 2075 | header.child(progress_bar()) |
| 2076 | }) |
| 2077 | .children(lead) |
| 2078 | .child( |
| 2079 | v_flex() |
| 2080 | .flex_1() |
| 2081 | .min_w_0() |
| 2082 | .overflow_hidden() |
| 2083 | .gap(px(1.)) |
| 2084 | .child( |
| 2085 | div() |
| 2086 | .truncate() |
| 2087 | .text_size(px(15.)) |
| 2088 | .font_weight(FontWeight::SEMIBOLD) |
| 2089 | .text_color(theme::text()) |
| 2090 | .child(current.title.clone()), |
| 2091 | ) |
| 2092 | .when(!subline.is_empty(), |column| { |
| 2093 | column.child( |
| 2094 | div() |
| 2095 | .text_size(px(12.)) |
| 2096 | .text_color(theme::text_muted()) |
| 2097 | .child(subline), |
| 2098 | ) |
| 2099 | }), |
| 2100 | ) |
| 2101 | .children(stack) |
| 2102 | } |
| 2103 | } |
| 2104 | |
| 2105 | impl Render for ConversationView { |
| 2106 | fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 2107 | let background = theme::background(); |
| 2108 | let mut root = v_flex().flex_1().min_w_0().h_full().bg(background); |
| 2109 | let drafting = self.draft_active; |
| 2110 | if self.current.is_none() && !drafting { |
| 2111 | return root |
| 2112 | .items_center() |
| 2113 | .justify_center() |
| 2114 | .text_color(theme::text_muted()) |
| 2115 | .child("Select a chat or channel") |
| 2116 | .into_any_element(); |
| 2117 | } |
| 2118 | let rows = self.rows.clone(); |
| 2119 | let view = cx.weak_entity(); |
| 2120 | let app = self.app.clone(); |
| 2121 | let highlighted = self.highlighted_message.clone(); |
| 2122 | let scroller = MessageScroller::new( |
| 2123 | "messages", |
| 2124 | self.scroller.clone(), |
| 2125 | move |index, window, cx| { |
| 2126 | let rows = rows.borrow(); |
| 2127 | match rows.get(index) { |
| 2128 | Some(Row::Message(message)) => { |
| 2129 | let open_thread = message.open_thread.clone().map(|root_id| { |
| 2130 | let view = view.clone(); |
| 2131 | Box::new(move |cx: &mut App| { |
| 2132 | let root_id = root_id.clone(); |
| 2133 | view.update(cx, |this, cx| this.open_thread(root_id, cx)) |
| 2134 | .ok(); |
| 2135 | }) as Box<dyn Fn(&mut App)> |
| 2136 | }); |
| 2137 | let retry = matches!(message.delivery, Delivery::Failed(_)).then(|| { |
| 2138 | let (view, key, handle) = |
| 2139 | (view.clone(), message.key.clone(), window.window_handle()); |
| 2140 | Box::new(move |cx: &mut App| { |
| 2141 | let (view, key) = (view.clone(), key.clone()); |
| 2142 | handle |
| 2143 | .update(cx, move |_, window, cx| { |
| 2144 | view.update(cx, |this, cx| this.retry(&key, window, cx)) |
| 2145 | .ok(); |
| 2146 | }) |
| 2147 | .ok(); |
| 2148 | }) as Box<dyn Fn(&mut App)> |
| 2149 | }); |
| 2150 | let sender = (!message.own && !message.series.has_prev) |
| 2151 | .then(|| message.sender_id.clone()) |
| 2152 | .flatten() |
| 2153 | .filter(|sender| app.read(cx).directory.avatar(sender).is_none()); |
| 2154 | if let Some(sender) = sender { |
| 2155 | let app = app.clone(); |
| 2156 | cx.defer(move |cx| { |
| 2157 | app.update(cx, |state, cx| state.request_avatars(vec![sender], cx)); |
| 2158 | }); |
| 2159 | } |
| 2160 | let missing_images: Vec<ImageRef> = message |
| 2161 | .images |
| 2162 | .iter() |
| 2163 | .filter(|image| app.read(cx).directory.image(&image.url).is_none()) |
| 2164 | .cloned() |
| 2165 | .collect(); |
| 2166 | if !missing_images.is_empty() { |
| 2167 | let app = app.clone(); |
| 2168 | cx.defer(move |cx| { |
| 2169 | app.update(cx, |state, cx| { |
| 2170 | state.request_images(missing_images, cx) |
| 2171 | }); |
| 2172 | }); |
| 2173 | } |
| 2174 | let is_real = !drafting && !message.key.starts_with(PENDING_KEY_PREFIX); |
| 2175 | let hovered = is_real.then(|| { |
| 2176 | let (view, key) = (view.clone(), message.key.clone()); |
| 2177 | Rc::new(move |hovered: bool, cx: &mut App| { |
| 2178 | view.update(cx, |this, cx| { |
| 2179 | this.set_hover(HoverSlot::Row, &key, hovered, cx) |
| 2180 | }) |
| 2181 | .ok(); |
| 2182 | }) as Rc<dyn Fn(bool, &mut App)> |
| 2183 | }); |
| 2184 | let actionable = is_real && !message.deleted && !message.card; |
| 2185 | let (menu, react) = view |
| 2186 | .upgrade() |
| 2187 | .filter(|_| actionable) |
| 2188 | .map(|entity| { |
| 2189 | let this = entity.read(cx); |
| 2190 | let menu = |
| 2191 | this.message_menu(&message.key, message.own, view.clone()); |
| 2192 | let react = menu.react.clone(); |
| 2193 | let visible = this.toolbar_visible(&message.key); |
| 2194 | (visible.then_some(menu), Some(react)) |
| 2195 | }) |
| 2196 | .unwrap_or((None, None)); |
| 2197 | let reply = (is_real && !message.deleted).then(|| { |
| 2198 | let (view, key, handle) = |
| 2199 | (view.clone(), message.key.clone(), window.window_handle()); |
| 2200 | Box::new(move |cx: &mut App| { |
| 2201 | let (view, key) = (view.clone(), key.clone()); |
| 2202 | handle |
| 2203 | .update(cx, move |_, window, cx| { |
| 2204 | view.update(cx, |this, cx| { |
| 2205 | this.begin_reply(&key, window, cx) |
| 2206 | }) |
| 2207 | .ok(); |
| 2208 | }) |
| 2209 | .ok(); |
| 2210 | }) as Box<dyn Fn(&mut App)> |
| 2211 | }); |
| 2212 | let state = app.read(cx); |
| 2213 | render_message_row( |
| 2214 | message, |
| 2215 | index, |
| 2216 | RowActions { |
| 2217 | open_thread, |
| 2218 | retry, |
| 2219 | reply, |
| 2220 | hovered, |
| 2221 | menu, |
| 2222 | react, |
| 2223 | highlighted: highlighted.as_deref() == Some(message.key.as_str()), |
| 2224 | }, |
| 2225 | &state.directory, |
| 2226 | cx, |
| 2227 | ) |
| 2228 | } |
| 2229 | Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index), |
| 2230 | Some(Row::LoadOlder) => { |
| 2231 | let view = view.clone(); |
| 2232 | cx.defer(move |cx| { |
| 2233 | view.update(cx, |this, cx| this.request_older(cx)).ok(); |
| 2234 | }); |
| 2235 | h_flex() |
| 2236 | .w_full() |
| 2237 | .py_2() |
| 2238 | .gap(px(6.)) |
| 2239 | .justify_center() |
| 2240 | .text_size(px(12.)) |
| 2241 | .text_color(theme::text_muted()) |
| 2242 | .child(icon(IconName::Loader, 12., theme::text_muted())) |
| 2243 | .child("Loading older messages") |
| 2244 | .into_any_element() |
| 2245 | } |
| 2246 | Some(Row::Start(start)) => { |
| 2247 | let state = app.read(cx); |
| 2248 | v_flex() |
| 2249 | .w_full() |
| 2250 | .items_center() |
| 2251 | .gap(px(8.)) |
| 2252 | .pt(px(32.)) |
| 2253 | .pb(px(16.)) |
| 2254 | .child(person_avatar( |
| 2255 | &state.directory, |
| 2256 | start.user_id.as_deref(), |
| 2257 | &start.title, |
| 2258 | 56., |
| 2259 | )) |
| 2260 | .child( |
| 2261 | div() |
| 2262 | .text_size(px(16.)) |
| 2263 | .font_weight(FontWeight::SEMIBOLD) |
| 2264 | .text_color(theme::text()) |
| 2265 | .child(start.title.clone()), |
| 2266 | ) |
| 2267 | .child( |
| 2268 | div() |
| 2269 | .text_size(px(12.)) |
| 2270 | .text_color(theme::text_muted()) |
| 2271 | .child("This is the beginning of the conversation"), |
| 2272 | ) |
| 2273 | .into_any_element() |
| 2274 | } |
| 2275 | None => div().into_any_element(), |
| 2276 | } |
| 2277 | }, |
| 2278 | ) |
| 2279 | .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.))) |
| 2280 | .with_bottom_fade(background); |
| 2281 | |
| 2282 | root = match self.current.as_ref().filter(|_| !drafting) { |
| 2283 | Some(current) => root.child(self.render_header(current, cx)), |
| 2284 | None => root.child(self.draft.clone()), |
| 2285 | }; |
| 2286 | let sync_failed = self |
| 2287 | .current |
| 2288 | .as_ref() |
| 2289 | .is_some_and(|current| current.sync.failed); |
| 2290 | if let Some(notice) = &self.notice { |
| 2291 | root = root.child( |
| 2292 | h_flex() |
| 2293 | .px_4() |
| 2294 | .py_1() |
| 2295 | .gap(px(8.)) |
| 2296 | .items_center() |
| 2297 | .text_xs() |
| 2298 | .bg(theme::amber().opacity(0.15)) |
| 2299 | .text_color(theme::amber()) |
| 2300 | .child(div().flex_1().min_w_0().child(notice.clone())) |
| 2301 | .when(sync_failed, |bar| { |
| 2302 | bar.child( |
| 2303 | Button::new("retry-fetch") |
| 2304 | .ghost() |
| 2305 | .compact() |
| 2306 | .label("Retry") |
| 2307 | .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))), |
| 2308 | ) |
| 2309 | }), |
| 2310 | ); |
| 2311 | } |
| 2312 | let empty_channel = self |
| 2313 | .current |
| 2314 | .as_ref() |
| 2315 | .is_some_and(|current| current.mode == ViewMode::ThreadList) |
| 2316 | && self.rows.borrow().is_empty(); |
| 2317 | let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() { |
| 2318 | let draft = self.draft.read(cx); |
| 2319 | let group_name = draft.group_name(cx); |
| 2320 | draft.render_empty(&self.app.read(cx).directory, &group_name) |
| 2321 | } else if empty_channel { |
| 2322 | div() |
| 2323 | .size_full() |
| 2324 | .flex() |
| 2325 | .items_center() |
| 2326 | .justify_center() |
| 2327 | .text_size(px(13.)) |
| 2328 | .text_color(theme::text_muted()) |
| 2329 | .child("No posts in this channel yet") |
| 2330 | .into_any_element() |
| 2331 | } else { |
| 2332 | scroller.into_any_element() |
| 2333 | }; |
| 2334 | root.child( |
| 2335 | v_flex() |
| 2336 | .relative() |
| 2337 | .flex_1() |
| 2338 | .min_h_0() |
| 2339 | .child(div().flex_1().min_h_0().child(body)) |
| 2340 | .children(self.render_draft_error(cx)) |
| 2341 | .child(self.composer.clone()) |
| 2342 | .child(self.render_drop_overlay(cx)), |
| 2343 | ) |
| 2344 | .when(drafting, |root| { |
| 2345 | root.on_action(cx.listener(|this, _: &Escape, window, cx| { |
| 2346 | if this.draft.read(cx).has_focus(window, cx) { |
| 2347 | this.draft.update(cx, |draft, cx| draft.escape(cx)); |
| 2348 | } |
| 2349 | })) |
| 2350 | }) |
| 2351 | .into_any_element() |
| 2352 | } |
| 2353 | } |
| 2354 | |
| 2355 | fn progress_bar() -> impl IntoElement { |
| 2356 | div() |
| 2357 | .absolute() |
| 2358 | .left_0() |
| 2359 | .right_0() |
| 2360 | .bottom(px(-1.)) |
| 2361 | .h(px(2.)) |
| 2362 | .overflow_hidden() |
| 2363 | .bg(theme::border()) |
| 2364 | .child( |
| 2365 | div() |
| 2366 | .absolute() |
| 2367 | .top_0() |
| 2368 | .h_full() |
| 2369 | .w(relative(PROGRESS_BAR_WIDTH)) |
| 2370 | .bg(theme::own_read()) |
| 2371 | .with_animation( |
| 2372 | "sync-progress", |
| 2373 | Animation::new(PROGRESS_BAR_PERIOD).repeat(), |
| 2374 | |bar, delta| { |
| 2375 | let travel = 1. + PROGRESS_BAR_WIDTH; |
| 2376 | // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0). |
| 2377 | bar.left(relative( |
| 2378 | (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH, |
| 2379 | )) |
| 2380 | }, |
| 2381 | ), |
| 2382 | ) |
| 2383 | } |
| 2384 | |
| 2385 | #[cfg(test)] |
| 2386 | mod tests { |
| 2387 | use std::sync::Arc; |
| 2388 | |
| 2389 | use super::{DropTarget, drop_overlay_text}; |
| 2390 | |
| 2391 | use gpui_kit::test::TestWindowExt as _; |
| 2392 | use gpui_kit::{AppContext as _, TestAppContext, WindowOptions}; |
| 2393 | use store::Store; |
| 2394 | |
| 2395 | use super::ConversationView; |
| 2396 | use crate::app_state::{AppState, Mode, Selection}; |
| 2397 | |
| 2398 | #[test] |
| 2399 | fn chat_overlay_names_the_chat_and_the_onedrive() { |
| 2400 | assert_eq!( |
| 2401 | drop_overlay_text("Mara Lin", DropTarget::Chat, 3), |
| 2402 | ( |
| 2403 | "Drop to attach to Mara Lin".to_owned(), |
| 2404 | "3 files. Images go into the message, other files to your OneDrive.".to_owned() |
| 2405 | ) |
| 2406 | ); |
| 2407 | } |
| 2408 | |
| 2409 | #[test] |
| 2410 | fn channel_overlay_points_to_the_channel_files() { |
| 2411 | let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1); |
| 2412 | assert_eq!( |
| 2413 | detail, |
| 2414 | "1 file. Images go into the message, other files to the channel's Files." |
| 2415 | ); |
| 2416 | } |
| 2417 | |
| 2418 | #[test] |
| 2419 | fn new_chat_overlay_says_files_wait_for_the_chat() { |
| 2420 | let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2); |
| 2421 | assert_eq!(heading, "Drop to attach to the new chat"); |
| 2422 | assert_eq!( |
| 2423 | detail, |
| 2424 | "2 files. Images go into the message. Files can be added once the chat exists." |
| 2425 | ); |
| 2426 | } |
| 2427 | |
| 2428 | #[gpui_kit::test] |
| 2429 | fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) { |
| 2430 | cx.update(gpui_kit::init); |
| 2431 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 2432 | crate::demo::seed(&store); |
| 2433 | let mode = Mode { |
| 2434 | demo: true, |
| 2435 | read_only: false, |
| 2436 | demo_sync: None, |
| 2437 | }; |
| 2438 | let (handle, app, _view) = cx.update(|cx| { |
| 2439 | let app = cx.new(|_| { |
| 2440 | let mut state = AppState::new(store, mode); |
| 2441 | crate::demo::seed_directory(&mut state); |
| 2442 | state.selection = Some(crate::demo::first_selection()); |
| 2443 | state |
| 2444 | }); |
| 2445 | let shared = app.clone(); |
| 2446 | let (handle, view) = |
| 2447 | gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { |
| 2448 | cx.new(|cx| ConversationView::new(shared, window, cx)) |
| 2449 | }) |
| 2450 | .unwrap(); |
| 2451 | (handle, app, view) |
| 2452 | }); |
| 2453 | cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx))); |
| 2454 | let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| { |
| 2455 | cx.update_window(handle, move |_, window, cx| { |
| 2456 | run(window, cx); |
| 2457 | window.render_frame(cx); |
| 2458 | }) |
| 2459 | .unwrap(); |
| 2460 | }; |
| 2461 | step(cx, |window, cx| window.render_frame(cx)); |
| 2462 | step(cx, |window, cx| window.input("lea", cx)); |
| 2463 | step(cx, |window, cx| window.press("enter", cx)); |
| 2464 | step(cx, |window, cx| window.press("enter", cx)); |
| 2465 | step(cx, |window, cx| window.input("Hello Lea", cx)); |
| 2466 | step(cx, |window, cx| window.press("enter", cx)); |
| 2467 | cx.update(|cx| { |
| 2468 | let state = app.read(cx); |
| 2469 | assert!(!state.new_chat); |
| 2470 | assert_eq!( |
| 2471 | state.selection, |
| 2472 | Some(Selection::Chat("demo-chat-new-1".to_owned())) |
| 2473 | ); |
| 2474 | let chat = state |
| 2475 | .sidebar |
| 2476 | .chats |
| 2477 | .iter() |
| 2478 | .find(|chat| chat.id == "demo-chat-new-1") |
| 2479 | .expect("new chat in the sidebar"); |
| 2480 | assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea")); |
| 2481 | }); |
| 2482 | } |
| 2483 | |
| 2484 | #[gpui_kit::test] |
| 2485 | fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) { |
| 2486 | cx.update(gpui_kit::init); |
| 2487 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 2488 | crate::demo::seed(&store); |
| 2489 | let mode = Mode { |
| 2490 | demo: true, |
| 2491 | read_only: false, |
| 2492 | demo_sync: None, |
| 2493 | }; |
| 2494 | let (handle, app) = cx.update(|cx| { |
| 2495 | let app = cx.new(|_| { |
| 2496 | let mut state = AppState::new(store, mode); |
| 2497 | crate::demo::seed_directory(&mut state); |
| 2498 | state.selection = Some(crate::demo::first_selection()); |
| 2499 | state |
| 2500 | }); |
| 2501 | let shared = app.clone(); |
| 2502 | let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { |
| 2503 | cx.new(|cx| ConversationView::new(shared, window, cx)) |
| 2504 | }) |
| 2505 | .unwrap(); |
| 2506 | (handle, app) |
| 2507 | }); |
| 2508 | cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx))); |
| 2509 | cx.update_window(handle, |_, window, cx| { |
| 2510 | window.render_frame(cx); |
| 2511 | window.press("escape", cx); |
| 2512 | window.render_frame(cx); |
| 2513 | window.press("escape", cx); |
| 2514 | window.render_frame(cx); |
| 2515 | }) |
| 2516 | .unwrap(); |
| 2517 | cx.update(|cx| { |
| 2518 | let state = app.read(cx); |
| 2519 | assert!(!state.new_chat); |
| 2520 | assert_eq!(state.selection, Some(crate::demo::first_selection())); |
| 2521 | }); |
| 2522 | } |
| 2523 | } |