| 1 | use std::cell::{Cell, RefCell}; |
| 2 | use std::collections::{HashMap, HashSet}; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::rc::Rc; |
| 5 | use std::time::{Duration, Instant}; |
| 6 | |
| 7 | use chrono::{DateTime, Local, Offset, Utc}; |
| 8 | use gpui_kit::assets::IconName; |
| 9 | use gpui_kit::component::{ |
| 10 | button::{Button, ButtonVariants as _}, |
| 11 | h_flex, |
| 12 | input::{Escape, InputState}, |
| 13 | message_scroller::{MessageScroller, MessageScrollerState}, |
| 14 | tooltip::Tooltip, |
| 15 | v_flex, |
| 16 | }; |
| 17 | use gpui_kit::prelude::FluentBuilder as _; |
| 18 | use gpui_kit::*; |
| 19 | use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget}; |
| 20 | use teams_core::{ |
| 21 | ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands, |
| 22 | }; |
| 23 | |
| 24 | mod detached; |
| 25 | mod feed; |
| 26 | mod pins; |
| 27 | mod proposal; |
| 28 | mod recap; |
| 29 | mod render_env; |
| 30 | mod scheduled; |
| 31 | mod shared; |
| 32 | |
| 33 | use super::attachments::FileActions; |
| 34 | use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence}; |
| 35 | use super::call_controls::header_call_controls; |
| 36 | use super::channel_tabs::ChannelPane; |
| 37 | use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview}; |
| 38 | use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT}; |
| 39 | use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row}; |
| 40 | use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one}; |
| 41 | use super::post_card::render_post; |
| 42 | use super::profile_card::opens_profile; |
| 43 | use super::reaction_picker::{PickHandler, ReactionPicker}; |
| 44 | use super::reaction_pills::{ReactionControls, ReactionPopover}; |
| 45 | use super::toolbar_placement::{TimelineBounds, record_bounds}; |
| 46 | use super::widgets::{icon, symbol}; |
| 47 | use crate::agents::{AgentRun, StartRequest}; |
| 48 | use crate::app_state::{AppEvent, AppState, Selection, selection_title}; |
| 49 | use crate::backend::Engine; |
| 50 | use crate::card_state::CardScope; |
| 51 | use crate::channel_files::DownloadSource; |
| 52 | use crate::data::{is_one_on_one, others}; |
| 53 | use crate::demo_library::DemoLibrary; |
| 54 | use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget}; |
| 55 | use crate::emoji; |
| 56 | use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of}; |
| 57 | use crate::notice::short_error; |
| 58 | use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of}; |
| 59 | use crate::pending_rows::pending_row; |
| 60 | use crate::people::{local_names, resolve_names}; |
| 61 | use crate::reaction_model::UNKNOWN_REACTOR; |
| 62 | use crate::read_state::{ReadTrigger, plan_read}; |
| 63 | use crate::rows::{ |
| 64 | Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction, |
| 65 | apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows, |
| 66 | has_own_reaction, message_draft, message_text, place_local_rows, placeholder_rows, |
| 67 | reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows, |
| 68 | }; |
| 69 | use crate::runtime; |
| 70 | use crate::scheduled_rows::SCHEDULED_KEY_PREFIX; |
| 71 | use crate::sidebar_model::{AvatarSpec, Face}; |
| 72 | use crate::theme; |
| 73 | use crate::translation::TranslationLine; |
| 74 | use crate::typing::typing_tooltip; |
| 75 | use detached::DetachedWindow; |
| 76 | use feed::{FeedStash, subject_input}; |
| 77 | use mcp::ReactionProposal; |
| 78 | use render_env::RenderEnv; |
| 79 | use shared::SharedState; |
| 80 | |
| 81 | const CHAT_OPEN_LIMIT: usize = 60; |
| 82 | const CHANNEL_OPEN_LIMIT: usize = 300; |
| 83 | const GROWTH_HEADROOM: usize = 20; |
| 84 | const META_USER_ID: &str = "me_user_id"; |
| 85 | const PENDING_KEY_PREFIX: &str = "pending-"; |
| 86 | const DEMO_DOWNLOAD_STEPS: u8 = 10; |
| 87 | const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100); |
| 88 | const JUMP_SCAN_LIMIT: usize = 5000; |
| 89 | const JUMP_CONTEXT_MESSAGES: usize = 12; |
| 90 | const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2); |
| 91 | const PROGRESS_DELAY: Duration = Duration::from_millis(400); |
| 92 | const SLOW_AFTER: Duration = Duration::from_secs(8); |
| 93 | const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500); |
| 94 | const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400); |
| 95 | const PROGRESS_BAR_WIDTH: f32 = 0.35; |
| 96 | const TYPING_LINE_HEIGHT: f32 = 22.; |
| 97 | const TYPING_DOT_SIZE: f32 = 5.; |
| 98 | const TYPING_DOT_COUNT: usize = 3; |
| 99 | const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200); |
| 100 | |
| 101 | actions!(teams, [ReplyToHovered]); |
| 102 | |
| 103 | #[derive(Clone, Copy)] |
| 104 | enum HoverSlot { |
| 105 | Row, |
| 106 | Toolbar, |
| 107 | } |
| 108 | |
| 109 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 110 | enum ViewMode { |
| 111 | Flat, |
| 112 | ThreadList, |
| 113 | Thread(String), |
| 114 | } |
| 115 | |
| 116 | #[derive(Default)] |
| 117 | struct SyncProgress { |
| 118 | messages: bool, |
| 119 | receipts: bool, |
| 120 | empty_cache: bool, |
| 121 | newest_cached: Option<DateTime<Utc>>, |
| 122 | shown_at: Option<Instant>, |
| 123 | slow: bool, |
| 124 | failed: bool, |
| 125 | } |
| 126 | |
| 127 | impl SyncProgress { |
| 128 | fn running(&self) -> bool { |
| 129 | self.messages || self.receipts |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | struct Current { |
| 134 | selection: Selection, |
| 135 | title: String, |
| 136 | mode: ViewMode, |
| 137 | loaded_limit: usize, |
| 138 | loaded_count: usize, |
| 139 | has_older: bool, |
| 140 | loading_older: bool, |
| 141 | older_blocked: bool, |
| 142 | fetched: bool, |
| 143 | first_unread: Option<String>, |
| 144 | sync: SyncProgress, |
| 145 | detached: Option<DetachedWindow>, |
| 146 | window_request: Option<String>, |
| 147 | } |
| 148 | |
| 149 | struct ReactionDetails { |
| 150 | message_key: String, |
| 151 | anchor_glyph: String, |
| 152 | tab: Option<String>, |
| 153 | } |
| 154 | |
| 155 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 156 | enum ReactionAttempt { |
| 157 | Acted, |
| 158 | Started, |
| 159 | AlreadyThere, |
| 160 | MissingMessage, |
| 161 | Blocked, |
| 162 | } |
| 163 | |
| 164 | pub struct ConversationView { |
| 165 | app: Entity<AppState>, |
| 166 | pinned: bool, |
| 167 | scroller: Entity<MessageScrollerState>, |
| 168 | composer: Entity<Composer>, |
| 169 | subject: Entity<InputState>, |
| 170 | new_post_open: bool, |
| 171 | reply_composer: Option<Entity<Composer>>, |
| 172 | reply_root: Option<String>, |
| 173 | feed_stash: Option<FeedStash>, |
| 174 | feed_rows_seen: Rc<Cell<usize>>, |
| 175 | feed_at_top: bool, |
| 176 | draft: Entity<NewChatDraft>, |
| 177 | draft_active: bool, |
| 178 | draft_created: Option<(Vec<String>, String)>, |
| 179 | draft_error: Option<String>, |
| 180 | rows: Rc<RefCell<Vec<Row>>>, |
| 181 | current: Option<Current>, |
| 182 | pending: Vec<MessageRow>, |
| 183 | pending_counter: usize, |
| 184 | pending_outgoing: HashMap<String, Outgoing>, |
| 185 | pending_reactions: PendingReactions, |
| 186 | downloads: Downloads, |
| 187 | hovered_message: Option<String>, |
| 188 | toolbar_hovered: Option<String>, |
| 189 | timeline_bounds: TimelineBounds, |
| 190 | toolbar_pinned: Option<String>, |
| 191 | toolbar_suppressed: Option<String>, |
| 192 | recent: Entity<emoji::Recent>, |
| 193 | picker: Entity<ReactionPicker>, |
| 194 | reaction_details: Option<ReactionDetails>, |
| 195 | highlighted_message: Option<String>, |
| 196 | pin_index: usize, |
| 197 | pin_previews: HashMap<String, pins::PinPreview>, |
| 198 | pin_fetches: HashSet<String>, |
| 199 | notice: Option<String>, |
| 200 | scheduled_failure: Option<scheduled::ScheduledFailure>, |
| 201 | scheduled_in_flight: HashSet<String>, |
| 202 | drag_file_count: usize, |
| 203 | sync_generation: u64, |
| 204 | window_active: bool, |
| 205 | pane: ChannelPane, |
| 206 | recap: recap::RecapState, |
| 207 | recap_search: Entity<InputState>, |
| 208 | channel_tabs: Vec<ChannelTabRecord>, |
| 209 | tab_links: HashMap<String, String>, |
| 210 | focus_handle: FocusHandle, |
| 211 | shared: SharedState, |
| 212 | demo_library: DemoLibrary, |
| 213 | new_folder_input: Option<Entity<InputState>>, |
| 214 | agent_layouts: HashMap<String, (usize, bool)>, |
| 215 | agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>, |
| 216 | reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>, |
| 217 | _subscriptions: Vec<Subscription>, |
| 218 | } |
| 219 | |
| 220 | fn open_limit(selection: &Selection) -> usize { |
| 221 | match selection { |
| 222 | Selection::Chat(_) => CHAT_OPEN_LIMIT, |
| 223 | Selection::Channel(_) => CHANNEL_OPEN_LIMIT, |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 228 | enum DropTarget { |
| 229 | Chat, |
| 230 | Channel, |
| 231 | Library, |
| 232 | NewChat, |
| 233 | } |
| 234 | |
| 235 | fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) { |
| 236 | let files = if count == 1 { |
| 237 | "1 file".to_owned() |
| 238 | } else { |
| 239 | format!("{count} files") |
| 240 | }; |
| 241 | match target { |
| 242 | DropTarget::Chat => ( |
| 243 | format!("Drop to attach to {title}"), |
| 244 | format!("{files}. Images go into the message, other files to your OneDrive."), |
| 245 | ), |
| 246 | DropTarget::Channel => ( |
| 247 | format!("Drop to attach to {title}"), |
| 248 | format!("{files}. Images go into the message, other files to the channel's Files."), |
| 249 | ), |
| 250 | DropTarget::Library => ( |
| 251 | format!("Drop to upload to {title}"), |
| 252 | format!("{files}. Files go into the folder you have open."), |
| 253 | ), |
| 254 | DropTarget::NewChat => ( |
| 255 | "Drop to attach to the new chat".to_owned(), |
| 256 | format!( |
| 257 | "{files}. Images go into the message. Files can be added once the chat exists." |
| 258 | ), |
| 259 | ), |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | fn shown_in_view(mode: &ViewMode, record: &store::OutboxRecord) -> bool { |
| 264 | match mode { |
| 265 | ViewMode::Flat => record.target == OutboxTarget::Flat, |
| 266 | ViewMode::ThreadList => matches!(record.target, OutboxTarget::Post | OutboxTarget::Thread), |
| 267 | ViewMode::Thread(root_id) => { |
| 268 | record.target == OutboxTarget::Thread |
| 269 | && record.thread_root_id.as_deref() == Some(root_id.as_str()) |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | enum DownloadEvent { |
| 275 | Progress(u8), |
| 276 | Finished(Result<PathBuf, String>), |
| 277 | } |
| 278 | |
| 279 | async fn save_file( |
| 280 | engine: &Engine, |
| 281 | card: &FileCard, |
| 282 | source: &DownloadSource, |
| 283 | events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>, |
| 284 | ) -> Result<PathBuf, String> { |
| 285 | let mut part = PartFile::create(&downloads::downloads_directory(), &card.name) |
| 286 | .map_err(|error| short_error(&error))?; |
| 287 | let write = |bytes: &[u8]| part.write(bytes); |
| 288 | let progress = |percent| { |
| 289 | let _ = events.send(DownloadEvent::Progress(percent)); |
| 290 | }; |
| 291 | match source { |
| 292 | DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await, |
| 293 | DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await, |
| 294 | } |
| 295 | .map_err(|error| short_error(&error))?; |
| 296 | part.finish().map_err(|error| short_error(&error)) |
| 297 | } |
| 298 | |
| 299 | impl ConversationView { |
| 300 | fn file_actions( |
| 301 | &self, |
| 302 | message_key: &str, |
| 303 | files: &[FileCard], |
| 304 | view: WeakEntity<Self>, |
| 305 | ) -> FileActions { |
| 306 | let conversation_id = self.conversation_id().unwrap_or_default(); |
| 307 | let (key, cards) = (message_key.to_owned(), files.to_vec()); |
| 308 | let open_urls: Vec<&str> = files.iter().map(|card| card.open_url.as_str()).collect(); |
| 309 | FileActions { |
| 310 | states: self |
| 311 | .downloads |
| 312 | .states_for(&conversation_id, message_key, &open_urls), |
| 313 | activate: Rc::new(move |index, cx| { |
| 314 | let Some(card) = cards.get(index).cloned() else { |
| 315 | return; |
| 316 | }; |
| 317 | let key = key.clone(); |
| 318 | let conversation_id = conversation_id.clone(); |
| 319 | view.update(cx, |this, cx| { |
| 320 | this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx) |
| 321 | }) |
| 322 | .ok(); |
| 323 | }), |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context<Self>) { |
| 328 | let Some(current) = self.current.as_ref() else { |
| 329 | return; |
| 330 | }; |
| 331 | let now = Local::now(); |
| 332 | let items = collect_gallery(&self.rows.borrow(), now.date_naive(), now.offset().fix()); |
| 333 | let Some(index) = position_of(&items, message_key, url) else { |
| 334 | return; |
| 335 | }; |
| 336 | let request = ViewerRequest { |
| 337 | conversation_id: current.selection.conversation_id().to_owned(), |
| 338 | conversation_title: selection_title(&self.app.read(cx).sidebar, ¤t.selection), |
| 339 | items, |
| 340 | index, |
| 341 | }; |
| 342 | self.app |
| 343 | .update(cx, |state, cx| state.request_image_viewer(request, cx)); |
| 344 | } |
| 345 | |
| 346 | fn activate_file( |
| 347 | &mut self, |
| 348 | conversation_id: &str, |
| 349 | message_key: &str, |
| 350 | card: FileCard, |
| 351 | source: DownloadSource, |
| 352 | cx: &mut Context<Self>, |
| 353 | ) { |
| 354 | let key = DownloadKey::new(conversation_id, message_key, &card.open_url); |
| 355 | match downloads::click_action(self.downloads.state(&key)) { |
| 356 | ClickAction::Ignore => {} |
| 357 | ClickAction::Start => self.start_download(key, card, source, cx), |
| 358 | ClickAction::Reveal(path) => { |
| 359 | let folder = path |
| 360 | .parent() |
| 361 | .map(Path::to_path_buf) |
| 362 | .unwrap_or_else(downloads::downloads_directory); |
| 363 | match downloads::reveal_target(&path, path.exists(), folder) { |
| 364 | RevealTarget::File(path) => downloads::reveal_in_file_manager(&path), |
| 365 | RevealTarget::Folder(folder) => cx.open_with_system(&folder), |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | fn start_download( |
| 372 | &mut self, |
| 373 | key: DownloadKey, |
| 374 | card: FileCard, |
| 375 | source: DownloadSource, |
| 376 | cx: &mut Context<Self>, |
| 377 | ) { |
| 378 | if !self.downloads.begin(&key) { |
| 379 | return; |
| 380 | } |
| 381 | cx.notify(); |
| 382 | let state = self.app.read(cx); |
| 383 | let (demo, engine) = (state.mode.demo, state.engine.clone()); |
| 384 | let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<DownloadEvent>(); |
| 385 | if demo { |
| 386 | cx.spawn(async move |this, cx| { |
| 387 | for step in 1..=DEMO_DOWNLOAD_STEPS { |
| 388 | cx.background_executor().timer(DEMO_DOWNLOAD_STEP).await; |
| 389 | let percent = (u32::from(step) * 100 / u32::from(DEMO_DOWNLOAD_STEPS)) as u8; |
| 390 | let progressed = this.update(cx, |this, cx| { |
| 391 | this.downloads.set_progress(&key, percent); |
| 392 | cx.notify(); |
| 393 | }); |
| 394 | if progressed.is_err() { |
| 395 | return; |
| 396 | } |
| 397 | } |
| 398 | let outcome = |
| 399 | downloads::write_demo_file(&card.name).map_err(|error| short_error(&error)); |
| 400 | this.update(cx, |this, cx| { |
| 401 | this.downloads.finish(&key, outcome); |
| 402 | cx.notify(); |
| 403 | }) |
| 404 | .ok(); |
| 405 | }) |
| 406 | .detach(); |
| 407 | return; |
| 408 | } |
| 409 | let Some(engine) = engine else { |
| 410 | self.downloads.finish(&key, Err("not connected".to_owned())); |
| 411 | return; |
| 412 | }; |
| 413 | drop(runtime::spawn(async move { |
| 414 | let outcome = save_file(&engine, &card, &source, &sender).await; |
| 415 | let _ = sender.send(DownloadEvent::Finished(outcome)); |
| 416 | })); |
| 417 | cx.spawn(async move |this, cx| { |
| 418 | while let Some(event) = receiver.recv().await { |
| 419 | let updated = this.update(cx, |this, cx| { |
| 420 | match event { |
| 421 | DownloadEvent::Progress(percent) => { |
| 422 | this.downloads.set_progress(&key, percent) |
| 423 | } |
| 424 | DownloadEvent::Finished(outcome) => this.downloads.finish(&key, outcome), |
| 425 | } |
| 426 | cx.notify(); |
| 427 | }); |
| 428 | if updated.is_err() { |
| 429 | break; |
| 430 | } |
| 431 | } |
| 432 | }) |
| 433 | .detach(); |
| 434 | } |
| 435 | |
| 436 | pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self { |
| 437 | Self::build(app, None, window, cx) |
| 438 | } |
| 439 | |
| 440 | pub fn pinned_to( |
| 441 | app: Entity<AppState>, |
| 442 | selection: Selection, |
| 443 | window: &mut Window, |
| 444 | cx: &mut Context<Self>, |
| 445 | ) -> Self { |
| 446 | Self::build(app, Some(selection), window, cx) |
| 447 | } |
| 448 | |
| 449 | fn build( |
| 450 | app: Entity<AppState>, |
| 451 | pinned: Option<Selection>, |
| 452 | window: &mut Window, |
| 453 | cx: &mut Context<Self>, |
| 454 | ) -> Self { |
| 455 | let scroller = cx.new(|cx| MessageScrollerState::new(0, cx)); |
| 456 | let composer = cx.new(|cx| Composer::new(app.clone(), window, cx)); |
| 457 | let subject = subject_input(window, cx); |
| 458 | let recap_search = recap::search_input(window, cx); |
| 459 | let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store)); |
| 460 | let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx)); |
| 461 | let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx)); |
| 462 | let mut subscriptions = vec![ |
| 463 | cx.subscribe_in(&app, window, Self::on_app_event), |
| 464 | cx.observe(&app, |_, _, cx| cx.notify()), |
| 465 | cx.subscribe_in(&composer, window, Self::on_composer_event), |
| 466 | cx.subscribe_in(&draft, window, Self::on_draft_event), |
| 467 | cx.subscribe_in(&subject, window, Self::on_subject_event), |
| 468 | cx.subscribe_in(&recap_search, window, Self::on_recap_search_event), |
| 469 | cx.observe_window_activation(window, Self::on_window_activation), |
| 470 | cx.on_app_quit(|this, cx| { |
| 471 | this.composer |
| 472 | .update(cx, |composer, cx| composer.save_draft_now(cx)); |
| 473 | async {} |
| 474 | }), |
| 475 | cx.observe_keystrokes(|this, event, _, cx| { |
| 476 | if event.keystroke.key == "escape" { |
| 477 | this.close_reaction_details(cx); |
| 478 | } |
| 479 | }), |
| 480 | ]; |
| 481 | if let Some(runs) = crate::agents::runs_handle(cx) { |
| 482 | subscriptions.push(cx.observe(&runs, |this, _, cx| this.sync_agent_chips(cx))); |
| 483 | } |
| 484 | if let Some(api) = crate::agent_api::handle(cx) { |
| 485 | subscriptions.push(cx.observe(&api, |this, _, cx| this.sync_reaction_pills(cx))); |
| 486 | } |
| 487 | let mut view = ConversationView { |
| 488 | app, |
| 489 | pinned: pinned.is_some(), |
| 490 | scroller, |
| 491 | composer, |
| 492 | subject, |
| 493 | new_post_open: false, |
| 494 | reply_composer: None, |
| 495 | reply_root: None, |
| 496 | feed_stash: None, |
| 497 | feed_rows_seen: Rc::new(Cell::new(usize::MAX)), |
| 498 | feed_at_top: true, |
| 499 | draft, |
| 500 | draft_active: false, |
| 501 | draft_created: None, |
| 502 | draft_error: None, |
| 503 | rows: Rc::new(RefCell::new(Vec::new())), |
| 504 | current: None, |
| 505 | pending: Vec::new(), |
| 506 | pending_counter: 0, |
| 507 | pending_outgoing: HashMap::new(), |
| 508 | pending_reactions: HashMap::new(), |
| 509 | downloads: Downloads::default(), |
| 510 | hovered_message: None, |
| 511 | toolbar_hovered: None, |
| 512 | timeline_bounds: TimelineBounds::default(), |
| 513 | toolbar_pinned: None, |
| 514 | toolbar_suppressed: None, |
| 515 | recent, |
| 516 | picker, |
| 517 | reaction_details: None, |
| 518 | highlighted_message: None, |
| 519 | pin_index: 0, |
| 520 | pin_previews: HashMap::new(), |
| 521 | pin_fetches: HashSet::new(), |
| 522 | notice: None, |
| 523 | scheduled_failure: None, |
| 524 | scheduled_in_flight: HashSet::new(), |
| 525 | drag_file_count: 0, |
| 526 | sync_generation: 0, |
| 527 | window_active: window.is_window_active(), |
| 528 | pane: ChannelPane::Posts, |
| 529 | recap: recap::RecapState::default(), |
| 530 | recap_search, |
| 531 | channel_tabs: Vec::new(), |
| 532 | tab_links: HashMap::new(), |
| 533 | focus_handle: cx.focus_handle(), |
| 534 | shared: SharedState::default(), |
| 535 | demo_library: DemoLibrary::default(), |
| 536 | new_folder_input: None, |
| 537 | agent_layouts: HashMap::new(), |
| 538 | agent_runs: Rc::new(RefCell::new(HashMap::new())), |
| 539 | reaction_proposals: Rc::new(RefCell::new(HashMap::new())), |
| 540 | _subscriptions: subscriptions, |
| 541 | }; |
| 542 | if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) { |
| 543 | view.open(selection, window, cx); |
| 544 | } |
| 545 | view |
| 546 | } |
| 547 | |
| 548 | #[cfg_attr(not(windows), allow(dead_code))] |
| 549 | pub fn composer_is_empty(&self, cx: &App) -> bool { |
| 550 | self.composer.read(cx).is_empty(cx) |
| 551 | } |
| 552 | |
| 553 | #[cfg_attr(not(windows), allow(dead_code))] |
| 554 | pub fn send_in_flight(&self) -> bool { |
| 555 | self.pending |
| 556 | .iter() |
| 557 | .any(|row| matches!(row.delivery, Delivery::Sending)) |
| 558 | } |
| 559 | |
| 560 | fn on_window_activation(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 561 | self.window_active = window.is_window_active(); |
| 562 | self.mark_read(ReadTrigger::Activation, cx); |
| 563 | } |
| 564 | |
| 565 | fn on_app_event( |
| 566 | &mut self, |
| 567 | _: &Entity<AppState>, |
| 568 | event: &AppEvent, |
| 569 | window: &mut Window, |
| 570 | cx: &mut Context<Self>, |
| 571 | ) { |
| 572 | match event { |
| 573 | AppEvent::Selection if self.pinned => {} |
| 574 | AppEvent::Selection => { |
| 575 | self.reaction_details = None; |
| 576 | let (new_chat, selection) = { |
| 577 | let state = self.app.read(cx); |
| 578 | (state.new_chat, state.selection.clone()) |
| 579 | }; |
| 580 | if new_chat { |
| 581 | self.enter_draft(window, cx); |
| 582 | return; |
| 583 | } |
| 584 | if self.draft_active { |
| 585 | let created = self |
| 586 | .draft_created |
| 587 | .as_ref() |
| 588 | .map(|(_, chat_id)| chat_id.clone()); |
| 589 | if let Some(chat_id) = created { |
| 590 | self.composer |
| 591 | .update(cx, |composer, _| composer.carry_images_into(chat_id)); |
| 592 | } |
| 593 | self.leave_draft(window, cx); |
| 594 | } |
| 595 | match selection { |
| 596 | Some(selection) => self.open(selection, window, cx), |
| 597 | None => { |
| 598 | self.current = None; |
| 599 | self.rebuild(true, cx); |
| 600 | } |
| 601 | } |
| 602 | } |
| 603 | AppEvent::Messages(conversation_id) => { |
| 604 | let is_current = self |
| 605 | .current |
| 606 | .as_ref() |
| 607 | .is_some_and(|current| current.selection.conversation_id() == conversation_id); |
| 608 | if is_current { |
| 609 | if self.shared_active() || self.recap_active() { |
| 610 | self.refresh_shared_items(cx); |
| 611 | } |
| 612 | self.rebuild(false, cx); |
| 613 | self.mark_read(ReadTrigger::Incoming, cx); |
| 614 | self.on_pins_changed(conversation_id, cx); |
| 615 | } |
| 616 | } |
| 617 | AppEvent::Images(keys) => self.remeasure_images(keys, cx), |
| 618 | AppEvent::Cards(conversation_id) => self.refresh_cards(conversation_id, cx), |
| 619 | AppEvent::Jump => self.apply_pending_jump(cx), |
| 620 | AppEvent::Status => { |
| 621 | if let Some(current) = self.current.as_mut() |
| 622 | && current.sync.failed |
| 623 | { |
| 624 | current.fetched = false; |
| 625 | } |
| 626 | self.start_fetch(cx) |
| 627 | } |
| 628 | AppEvent::Directory => { |
| 629 | self.refresh_reactor_names(cx); |
| 630 | cx.notify(); |
| 631 | } |
| 632 | AppEvent::TaskDialog |
| 633 | | AppEvent::LocalPreviews |
| 634 | | AppEvent::Forward |
| 635 | | AppEvent::ImageViewer |
| 636 | | AppEvent::StatusMessage |
| 637 | | AppEvent::NotificationSettings |
| 638 | | AppEvent::Profile |
| 639 | | AppEvent::CallHistory |
| 640 | | AppEvent::Ring |
| 641 | | AppEvent::MissedCall(_) |
| 642 | | AppEvent::MeetingReminder |
| 643 | | AppEvent::Call => {} |
| 644 | AppEvent::LiveMeeting => cx.notify(), |
| 645 | AppEvent::Saved => cx.notify(), |
| 646 | AppEvent::Translation => self.rebuild(false, cx), |
| 647 | AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx), |
| 648 | AppEvent::Typing => cx.notify(), |
| 649 | AppEvent::Scheduled => self.rebuild(false, cx), |
| 650 | AppEvent::Outbox(conversation_id) => { |
| 651 | let is_current = self |
| 652 | .current |
| 653 | .as_ref() |
| 654 | .is_some_and(|current| current.selection.conversation_id() == conversation_id); |
| 655 | if is_current { |
| 656 | self.reload_pending(cx); |
| 657 | self.rebuild(false, cx); |
| 658 | } |
| 659 | } |
| 660 | AppEvent::Sidebar => { |
| 661 | self.reload_channel_tabs(cx); |
| 662 | self.mark_read(ReadTrigger::Incoming, cx); |
| 663 | self.refresh_reactor_names(cx); |
| 664 | if self.draft_active { |
| 665 | self.on_draft_changed(window, cx); |
| 666 | } else if let Some(current) = self.current.as_mut() { |
| 667 | let title = selection_title(&self.app.read(cx).sidebar, ¤t.selection); |
| 668 | if current.title != title { |
| 669 | current.title = title.clone(); |
| 670 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 671 | self.composer.update(cx, |composer, cx| { |
| 672 | composer.set_conversation(&conversation_id, &title, window, cx) |
| 673 | }); |
| 674 | cx.notify(); |
| 675 | } |
| 676 | } |
| 677 | } |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | fn on_composer_event( |
| 682 | &mut self, |
| 683 | _: &Entity<Composer>, |
| 684 | event: &ComposerEvent, |
| 685 | window: &mut Window, |
| 686 | cx: &mut Context<Self>, |
| 687 | ) { |
| 688 | self.report_composer_activity(event, cx); |
| 689 | match event { |
| 690 | ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx), |
| 691 | ComposerEvent::Schedule { outgoing, send_at } => { |
| 692 | self.schedule((**outgoing).clone(), *send_at, window, cx) |
| 693 | } |
| 694 | ComposerEvent::EditLast => self.edit_last_own(window, cx), |
| 695 | ComposerEvent::Typing(active) => self.send_typing(*active, cx), |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | fn submit_main(&mut self, mut outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) { |
| 700 | if self.draft_active { |
| 701 | return self.send_new_chat(outgoing, window, cx); |
| 702 | } |
| 703 | let in_feed = self.in_feed(); |
| 704 | if in_feed && outgoing.edit.is_none() { |
| 705 | outgoing.subject = self.take_subject(window, cx); |
| 706 | } |
| 707 | if in_feed { |
| 708 | self.close_new_post(cx); |
| 709 | } |
| 710 | match &outgoing.edit { |
| 711 | Some(edit) if edit.scheduled.is_some() => { |
| 712 | self.send_scheduled_edit(outgoing, window, cx) |
| 713 | } |
| 714 | Some(_) => self.send_edit(outgoing, window, cx), |
| 715 | None => self.send(outgoing, window, cx), |
| 716 | } |
| 717 | } |
| 718 | |
| 719 | fn typing_root(&self) -> Option<String> { |
| 720 | match self.current.as_ref().map(|current| ¤t.mode) { |
| 721 | Some(ViewMode::Thread(root_id)) => Some(root_id.clone()), |
| 722 | _ => None, |
| 723 | } |
| 724 | } |
| 725 | |
| 726 | fn send_typing(&self, active: bool, cx: &App) { |
| 727 | self.send_typing_in(self.typing_root(), active, cx); |
| 728 | } |
| 729 | |
| 730 | fn send_typing_in(&self, thread_root_id: Option<String>, active: bool, cx: &App) { |
| 731 | let state = self.app.read(cx); |
| 732 | if state.mode.demo || state.mode.read_only || self.draft_active { |
| 733 | return; |
| 734 | } |
| 735 | let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id()) |
| 736 | else { |
| 737 | return; |
| 738 | }; |
| 739 | drop(runtime::spawn(async move { |
| 740 | let sent = engine |
| 741 | .send_typing(&conversation_id, thread_root_id.as_deref(), active) |
| 742 | .await; |
| 743 | if let Err(error) = sent |
| 744 | && cfg!(debug_assertions) |
| 745 | { |
| 746 | crate::diagnostics::record(format!("typing indicator not sent: {error}")); |
| 747 | } |
| 748 | })); |
| 749 | } |
| 750 | |
| 751 | fn stop_typing(&mut self, cx: &mut Context<Self>) { |
| 752 | if self |
| 753 | .composer |
| 754 | .update(cx, |composer, _| composer.stop_typing()) |
| 755 | { |
| 756 | self.send_typing(false, cx); |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | fn render_typing_line(&self, cx: &App) -> impl IntoElement { |
| 761 | let app = self.app.read(cx); |
| 762 | let faces = self |
| 763 | .current |
| 764 | .as_ref() |
| 765 | .filter(|_| !self.draft_active) |
| 766 | .map(|current| app.typing.faces(current.selection.conversation_id())) |
| 767 | .unwrap_or_default(); |
| 768 | let tooltip_text = typing_tooltip( |
| 769 | &faces |
| 770 | .iter() |
| 771 | .map(|face| face.name.clone()) |
| 772 | .collect::<Vec<_>>(), |
| 773 | ); |
| 774 | let flat = matches!( |
| 775 | self.current.as_ref().map(|current| ¤t.mode), |
| 776 | Some(ViewMode::Flat) |
| 777 | ); |
| 778 | let faces_element = match faces.as_slice() { |
| 779 | [face] if flat => person_avatar( |
| 780 | &app.directory, |
| 781 | face.user_id.as_deref(), |
| 782 | &face.name, |
| 783 | AVATAR_SIZE, |
| 784 | ), |
| 785 | _ => member_stack(&app.directory, &faces, faces.len()).into_any_element(), |
| 786 | }; |
| 787 | h_flex() |
| 788 | .h(px(if flat { |
| 789 | AVATAR_SIZE + 4. |
| 790 | } else { |
| 791 | TYPING_LINE_HEIGHT |
| 792 | })) |
| 793 | .flex_none() |
| 794 | .px(px(20.)) |
| 795 | .gap(px(if flat { AVATAR_GAP } else { 6. })) |
| 796 | .items_center() |
| 797 | .when(!faces.is_empty(), |line| { |
| 798 | line.child( |
| 799 | div() |
| 800 | .id("typing-faces") |
| 801 | .tooltip(move |window, cx| { |
| 802 | Tooltip::new(tooltip_text.clone()).build(window, cx) |
| 803 | }) |
| 804 | .child(faces_element), |
| 805 | ) |
| 806 | .child(typing_dots()) |
| 807 | }) |
| 808 | } |
| 809 | |
| 810 | fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) { |
| 811 | self.stop_typing(cx); |
| 812 | self.stop_reply_typing(cx); |
| 813 | self.new_post_open = false; |
| 814 | self.feed_stash = None; |
| 815 | self.feed_at_top = true; |
| 816 | self.restore_subject(None, window, cx); |
| 817 | self.toolbar_hovered = None; |
| 818 | self.toolbar_pinned = None; |
| 819 | self.toolbar_suppressed = None; |
| 820 | self.agent_layouts.clear(); |
| 821 | self.agent_runs.borrow_mut().clear(); |
| 822 | self.reaction_proposals.borrow_mut().clear(); |
| 823 | let title = selection_title(&self.app.read(cx).sidebar, &selection); |
| 824 | let mode = match selection { |
| 825 | Selection::Chat(_) => ViewMode::Flat, |
| 826 | Selection::Channel(_) => ViewMode::ThreadList, |
| 827 | }; |
| 828 | let first_unread = self.first_unread_id(&selection, cx); |
| 829 | self.current = Some(Current { |
| 830 | loaded_limit: open_limit(&selection), |
| 831 | selection, |
| 832 | title, |
| 833 | mode, |
| 834 | loaded_count: 0, |
| 835 | has_older: false, |
| 836 | loading_older: false, |
| 837 | older_blocked: false, |
| 838 | fetched: false, |
| 839 | first_unread, |
| 840 | sync: SyncProgress::default(), |
| 841 | detached: None, |
| 842 | window_request: None, |
| 843 | }); |
| 844 | self.refresh_agent_runs(cx); |
| 845 | self.refresh_reaction_pills(cx); |
| 846 | self.sync_generation += 1; |
| 847 | self.reset_channel_tabs(cx); |
| 848 | self.reset_recap(cx); |
| 849 | self.reload_pending(cx); |
| 850 | self.notice = None; |
| 851 | self.scheduled_failure = None; |
| 852 | self.app.update(cx, |state, cx| state.refresh_scheduled(cx)); |
| 853 | self.rebuild(true, cx); |
| 854 | self.start_fetch(cx); |
| 855 | self.mark_read(ReadTrigger::Open, cx); |
| 856 | self.refresh_pin_previews(cx); |
| 857 | if let Some(chat_id) = self.chat_id() { |
| 858 | self.app |
| 859 | .update(cx, |state, cx| state.refresh_pins(&chat_id, cx)); |
| 860 | } |
| 861 | let target = self |
| 862 | .current |
| 863 | .as_ref() |
| 864 | .map(|current| { |
| 865 | ( |
| 866 | current.selection.conversation_id().to_owned(), |
| 867 | current.title.clone(), |
| 868 | ) |
| 869 | }) |
| 870 | .unwrap_or_default(); |
| 871 | self.composer.update(cx, |composer, cx| { |
| 872 | composer.set_conversation(&target.0, &target.1, window, cx); |
| 873 | }); |
| 874 | self.sync_reply_composer(window, cx); |
| 875 | if !self.draft_active && !self.in_feed() { |
| 876 | self.composer |
| 877 | .update(cx, |composer, cx| composer.focus(window, cx)); |
| 878 | } |
| 879 | self.hovered_message = None; |
| 880 | self.apply_pending_jump(cx); |
| 881 | } |
| 882 | |
| 883 | fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 884 | if !self.draft_active { |
| 885 | self.stop_typing(cx); |
| 886 | self.draft_active = true; |
| 887 | self.current = None; |
| 888 | self.clear_pending(); |
| 889 | self.notice = None; |
| 890 | self.draft_created = None; |
| 891 | self.draft_error = None; |
| 892 | self.toolbar_hovered = None; |
| 893 | self.toolbar_pinned = None; |
| 894 | self.toolbar_suppressed = None; |
| 895 | self.hovered_message = None; |
| 896 | self.sync_generation += 1; |
| 897 | self.draft.update(cx, |draft, cx| draft.reset(window, cx)); |
| 898 | self.composer.update(cx, |composer, cx| { |
| 899 | composer.set_conversation("", "", window, cx) |
| 900 | }); |
| 901 | self.on_draft_changed(window, cx); |
| 902 | self.rebuild(true, cx); |
| 903 | } |
| 904 | self.draft |
| 905 | .update(cx, |draft, cx| draft.focus_query(window, cx)); |
| 906 | cx.notify(); |
| 907 | } |
| 908 | |
| 909 | fn leave_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 910 | self.draft_active = false; |
| 911 | self.draft_created = None; |
| 912 | self.draft_error = None; |
| 913 | self.clear_pending(); |
| 914 | self.draft.update(cx, |draft, cx| draft.reset(window, cx)); |
| 915 | } |
| 916 | |
| 917 | fn on_draft_event( |
| 918 | &mut self, |
| 919 | _: &Entity<NewChatDraft>, |
| 920 | event: &NewChatEvent, |
| 921 | window: &mut Window, |
| 922 | cx: &mut Context<Self>, |
| 923 | ) { |
| 924 | match event { |
| 925 | NewChatEvent::Changed => self.on_draft_changed(window, cx), |
| 926 | NewChatEvent::FocusComposer => self |
| 927 | .composer |
| 928 | .update(cx, |composer, cx| composer.focus(window, cx)), |
| 929 | NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)), |
| 930 | } |
| 931 | } |
| 932 | |
| 933 | fn draft_target_chat(&self, cx: &App) -> Option<String> { |
| 934 | let chips = self.draft.read(cx).chips(); |
| 935 | let [chip] = chips else { |
| 936 | return None; |
| 937 | }; |
| 938 | let state = self.app.read(cx); |
| 939 | existing_one_on_one( |
| 940 | &state.sidebar.chats, |
| 941 | state.directory.me.as_ref(), |
| 942 | &chip.user_id, |
| 943 | ) |
| 944 | .map(|chat| chat.id.clone()) |
| 945 | } |
| 946 | |
| 947 | fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 948 | if !self.draft_active { |
| 949 | return; |
| 950 | } |
| 951 | let target = self.draft_target_chat(cx); |
| 952 | if target != self.conversation_id() { |
| 953 | match target { |
| 954 | Some(chat_id) => { |
| 955 | self.composer.update(cx, |composer, _| { |
| 956 | composer.carry_images_into(chat_id.clone()) |
| 957 | }); |
| 958 | self.open(Selection::Chat(chat_id), window, cx) |
| 959 | } |
| 960 | None => { |
| 961 | self.composer.update(cx, |composer, cx| { |
| 962 | composer.carry_images_into(String::new()); |
| 963 | composer.set_conversation("", "", window, cx); |
| 964 | }); |
| 965 | self.current = None; |
| 966 | self.sync_generation += 1; |
| 967 | self.rebuild(true, cx); |
| 968 | } |
| 969 | } |
| 970 | } |
| 971 | let placeholder = { |
| 972 | let draft = self.draft.read(cx); |
| 973 | composer_placeholder(draft.chips(), &draft.group_name(cx)) |
| 974 | }; |
| 975 | self.composer.update(cx, |composer, cx| { |
| 976 | composer.set_placeholder(&placeholder, window, cx) |
| 977 | }); |
| 978 | cx.notify(); |
| 979 | } |
| 980 | |
| 981 | fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) { |
| 982 | let indices: Vec<usize> = self |
| 983 | .rows |
| 984 | .borrow() |
| 985 | .iter() |
| 986 | .enumerate() |
| 987 | .filter(|(_, row)| { |
| 988 | row.messages().any(|message| { |
| 989 | message.images.iter().any(|image| keys.contains(&image.url)) |
| 990 | || message |
| 991 | .link_preview |
| 992 | .as_ref() |
| 993 | .and_then(LinkPreview::image) |
| 994 | .is_some_and(|image| keys.contains(&image.url)) |
| 995 | }) |
| 996 | }) |
| 997 | .map(|(index, _)| index) |
| 998 | .collect(); |
| 999 | self.scroller.update(cx, |scroller, cx| { |
| 1000 | for index in indices { |
| 1001 | scroller.remeasure_items(index..index + 1, cx); |
| 1002 | } |
| 1003 | }); |
| 1004 | cx.notify(); |
| 1005 | } |
| 1006 | |
| 1007 | fn refresh_cards(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 1008 | let is_current = self |
| 1009 | .current |
| 1010 | .as_ref() |
| 1011 | .is_some_and(|current| current.selection.conversation_id() == conversation_id); |
| 1012 | if !is_current { |
| 1013 | return; |
| 1014 | } |
| 1015 | self.rebuild(false, cx); |
| 1016 | let indices: Vec<usize> = self |
| 1017 | .rows |
| 1018 | .borrow() |
| 1019 | .iter() |
| 1020 | .enumerate() |
| 1021 | .filter(|(_, row)| { |
| 1022 | row.messages() |
| 1023 | .any(|message| !message.adaptive_cards.is_empty()) |
| 1024 | }) |
| 1025 | .map(|(index, _)| index) |
| 1026 | .collect(); |
| 1027 | self.scroller.update(cx, |scroller, cx| { |
| 1028 | for index in indices { |
| 1029 | scroller.remeasure_items(index..index + 1, cx); |
| 1030 | } |
| 1031 | }); |
| 1032 | cx.notify(); |
| 1033 | } |
| 1034 | |
| 1035 | fn apply_pending_jump(&mut self, cx: &mut Context<Self>) { |
| 1036 | let Some(conversation_id) = self |
| 1037 | .current |
| 1038 | .as_ref() |
| 1039 | .map(|current| current.selection.conversation_id().to_owned()) |
| 1040 | else { |
| 1041 | return; |
| 1042 | }; |
| 1043 | let jump = self |
| 1044 | .app |
| 1045 | .update(cx, |state, _| match state.pending_jump.take() { |
| 1046 | Some((target, message_id)) if target == conversation_id => Some(message_id), |
| 1047 | other => { |
| 1048 | state.pending_jump = other; |
| 1049 | None |
| 1050 | } |
| 1051 | }); |
| 1052 | if let Some(message_id) = jump { |
| 1053 | self.jump_to_message(&conversation_id, &message_id, cx); |
| 1054 | } |
| 1055 | } |
| 1056 | |
| 1057 | fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) { |
| 1058 | let store = self.app.read(cx).store.clone(); |
| 1059 | let record = store |
| 1060 | .messages_by_id(conversation_id, &[message_id.to_owned()]) |
| 1061 | .ok() |
| 1062 | .and_then(|mut found| found.remove(message_id)); |
| 1063 | if self.chat_id().as_deref() == Some(conversation_id) { |
| 1064 | let created_at = record.as_ref().map(|record| record.created_at); |
| 1065 | match self.jump_plan_for(conversation_id, created_at, cx) { |
| 1066 | JumpPlan::LoadWindow => { |
| 1067 | self.open_detached(conversation_id.to_owned(), message_id.to_owned(), cx); |
| 1068 | return; |
| 1069 | } |
| 1070 | plan => { |
| 1071 | if let Some(current) = self.current.as_mut() { |
| 1072 | current.window_request = None; |
| 1073 | if plan == JumpPlan::LeaveWindow { |
| 1074 | current.detached = None; |
| 1075 | } |
| 1076 | } |
| 1077 | } |
| 1078 | } |
| 1079 | } |
| 1080 | let Some(record) = record else { |
| 1081 | return; |
| 1082 | }; |
| 1083 | let messages_from_target = store |
| 1084 | .messages(conversation_id, None, JUMP_SCAN_LIMIT) |
| 1085 | .ok() |
| 1086 | .and_then(|all| { |
| 1087 | all.iter() |
| 1088 | .position(|candidate| candidate.message_id == message_id) |
| 1089 | .map(|position| all.len() - position) |
| 1090 | }) |
| 1091 | .unwrap_or_default(); |
| 1092 | let row_key = record |
| 1093 | .reply_to_id |
| 1094 | .clone() |
| 1095 | .unwrap_or_else(|| message_id.to_owned()); |
| 1096 | let Some(current) = self.current.as_mut() else { |
| 1097 | return; |
| 1098 | }; |
| 1099 | current.loaded_limit = current |
| 1100 | .loaded_limit |
| 1101 | .max(messages_from_target + JUMP_CONTEXT_MESSAGES); |
| 1102 | current.first_unread = None; |
| 1103 | let in_channel = matches!(current.selection, Selection::Channel(_)); |
| 1104 | if in_channel { |
| 1105 | self.pane = ChannelPane::Posts; |
| 1106 | match record.reply_to_id.clone() { |
| 1107 | Some(root_id) => { |
| 1108 | self.enter_thread_mode(root_id.clone(), cx); |
| 1109 | self.refresh_thread(root_id, cx); |
| 1110 | } |
| 1111 | None => { |
| 1112 | self.enter_feed_mode(); |
| 1113 | } |
| 1114 | } |
| 1115 | } |
| 1116 | let in_thread = self |
| 1117 | .current |
| 1118 | .as_ref() |
| 1119 | .is_some_and(|current| matches!(current.mode, ViewMode::Thread(_))); |
| 1120 | let target_key = if in_thread { |
| 1121 | message_id.to_owned() |
| 1122 | } else { |
| 1123 | row_key |
| 1124 | }; |
| 1125 | self.reload_pending(cx); |
| 1126 | self.rebuild(true, cx); |
| 1127 | self.reveal_row(target_key, cx); |
| 1128 | } |
| 1129 | |
| 1130 | fn reveal_row(&mut self, target_key: String, cx: &mut Context<Self>) { |
| 1131 | let index = self |
| 1132 | .rows |
| 1133 | .borrow() |
| 1134 | .iter() |
| 1135 | .position(|row| row.key() == target_key); |
| 1136 | if let Some(index) = index { |
| 1137 | self.scroller |
| 1138 | .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx)); |
| 1139 | self.highlight(target_key, cx); |
| 1140 | } |
| 1141 | } |
| 1142 | |
| 1143 | fn highlight(&mut self, key: String, cx: &mut Context<Self>) { |
| 1144 | self.highlighted_message = Some(key.clone()); |
| 1145 | cx.notify(); |
| 1146 | cx.spawn(async move |this, cx| { |
| 1147 | cx.background_executor().timer(HIGHLIGHT_DURATION).await; |
| 1148 | this.update(cx, |this, cx| { |
| 1149 | if this.highlighted_message.as_deref() == Some(key.as_str()) { |
| 1150 | this.highlighted_message = None; |
| 1151 | cx.notify(); |
| 1152 | } |
| 1153 | }) |
| 1154 | .ok(); |
| 1155 | }) |
| 1156 | .detach(); |
| 1157 | } |
| 1158 | |
| 1159 | pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 1160 | self.composer |
| 1161 | .update(cx, |composer, cx| composer.set_text(text, window, cx)); |
| 1162 | self.composer |
| 1163 | .update(cx, |composer, cx| composer.focus(window, cx)); |
| 1164 | } |
| 1165 | |
| 1166 | pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1167 | let key = self |
| 1168 | .rows |
| 1169 | .borrow() |
| 1170 | .iter() |
| 1171 | .rev() |
| 1172 | .flat_map(Row::messages) |
| 1173 | .find(|message| !message.own) |
| 1174 | .map(|message| message.key.clone()); |
| 1175 | if let Some(key) = key { |
| 1176 | self.begin_reply(&key, window, cx); |
| 1177 | } |
| 1178 | } |
| 1179 | |
| 1180 | pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1181 | if let Some(message_id) = self.hovered_message.clone() { |
| 1182 | self.begin_reply(&message_id, window, cx); |
| 1183 | } |
| 1184 | } |
| 1185 | |
| 1186 | fn reply_target(&self, message_id: &str, cx: &App) -> Option<(MessageRecord, ReplyPreview)> { |
| 1187 | let conversation_id = self.conversation_id()?; |
| 1188 | let record = self |
| 1189 | .app |
| 1190 | .read(cx) |
| 1191 | .store |
| 1192 | .messages_by_id(&conversation_id, &[message_id.to_owned()]) |
| 1193 | .ok() |
| 1194 | .and_then(|mut found| found.remove(message_id)) |
| 1195 | .filter(|record| !record.deleted)?; |
| 1196 | let preview = ReplyPreview { |
| 1197 | message_id: record.message_id.clone(), |
| 1198 | author: record |
| 1199 | .sender_name |
| 1200 | .clone() |
| 1201 | .unwrap_or_else(|| "Unknown".to_owned()), |
| 1202 | excerpt: reply_excerpt(&record), |
| 1203 | }; |
| 1204 | Some((record, preview)) |
| 1205 | } |
| 1206 | |
| 1207 | fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 1208 | let Some((record, preview)) = self.reply_target(message_id, cx) else { |
| 1209 | return; |
| 1210 | }; |
| 1211 | if self.in_feed() { |
| 1212 | let root_id = record |
| 1213 | .reply_to_id |
| 1214 | .clone() |
| 1215 | .unwrap_or_else(|| record.message_id.clone()); |
| 1216 | let quote = record.reply_to_id.is_some().then_some(preview); |
| 1217 | self.open_reply_editor(root_id, quote, window, cx); |
| 1218 | return; |
| 1219 | } |
| 1220 | self.composer.update(cx, |composer, cx| { |
| 1221 | composer.set_reply(Some(preview), cx); |
| 1222 | composer.focus(window, cx); |
| 1223 | }); |
| 1224 | } |
| 1225 | |
| 1226 | fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> { |
| 1227 | let Selection::Chat(chat_id) = selection else { |
| 1228 | return None; |
| 1229 | }; |
| 1230 | let state = self.app.read(cx); |
| 1231 | if state.mode.demo { |
| 1232 | return crate::demo::first_unread(chat_id); |
| 1233 | } |
| 1234 | state.engine.as_ref()?.first_unread_message_id(chat_id) |
| 1235 | } |
| 1236 | |
| 1237 | fn row_context(&self, cx: &App) -> RowContext { |
| 1238 | let now = Local::now(); |
| 1239 | let app = self.app.read(cx); |
| 1240 | let names = local_names(app); |
| 1241 | let card_overrides = self |
| 1242 | .current |
| 1243 | .as_ref() |
| 1244 | .map(|current| app.cards.overrides_for(current.selection.conversation_id())) |
| 1245 | .unwrap_or_default(); |
| 1246 | let translation = self |
| 1247 | .current |
| 1248 | .as_ref() |
| 1249 | .map(|current| { |
| 1250 | app.translation |
| 1251 | .context_for(current.selection.conversation_id()) |
| 1252 | }) |
| 1253 | .unwrap_or_default(); |
| 1254 | RowContext { |
| 1255 | offset: now.offset().fix(), |
| 1256 | today: now.date_naive(), |
| 1257 | my_user_id: app.store.meta(META_USER_ID).ok().flatten(), |
| 1258 | names, |
| 1259 | pending_reactions: self.pending_reactions.clone(), |
| 1260 | card_overrides, |
| 1261 | translation, |
| 1262 | } |
| 1263 | } |
| 1264 | |
| 1265 | fn unknown_reactor_ids(&self) -> Vec<String> { |
| 1266 | self.rows |
| 1267 | .borrow() |
| 1268 | .iter() |
| 1269 | .flat_map(Row::messages) |
| 1270 | .flat_map(|message| message.reactions.iter()) |
| 1271 | .flat_map(|chip| chip.reactors.iter()) |
| 1272 | .filter(|reactor| reactor.name == UNKNOWN_REACTOR) |
| 1273 | .filter_map(|reactor| reactor.user_id.clone()) |
| 1274 | .collect() |
| 1275 | } |
| 1276 | |
| 1277 | fn refresh_reactor_names(&mut self, cx: &mut Context<Self>) { |
| 1278 | if self.current.is_none() { |
| 1279 | return; |
| 1280 | } |
| 1281 | let unknown = self.unknown_reactor_ids(); |
| 1282 | if unknown.is_empty() { |
| 1283 | return; |
| 1284 | } |
| 1285 | let names = resolve_names(self.app.read(cx), &unknown); |
| 1286 | if !names.is_empty() { |
| 1287 | self.rebuild(false, cx); |
| 1288 | } |
| 1289 | } |
| 1290 | |
| 1291 | fn drop_stale_reaction_details(&mut self) { |
| 1292 | let Some(details) = self.reaction_details.as_ref() else { |
| 1293 | return; |
| 1294 | }; |
| 1295 | let present = self |
| 1296 | .rows |
| 1297 | .borrow() |
| 1298 | .iter() |
| 1299 | .flat_map(Row::messages) |
| 1300 | .any(|message| { |
| 1301 | message.key == details.message_key |
| 1302 | && message |
| 1303 | .reactions |
| 1304 | .iter() |
| 1305 | .any(|chip| chip.glyph() == details.anchor_glyph) |
| 1306 | }); |
| 1307 | if !present { |
| 1308 | self.reaction_details = None; |
| 1309 | } |
| 1310 | } |
| 1311 | |
| 1312 | fn open_reaction_details(&mut self, message_key: &str, glyph: &str, cx: &mut Context<Self>) { |
| 1313 | let multiple_kinds = self |
| 1314 | .rows |
| 1315 | .borrow() |
| 1316 | .iter() |
| 1317 | .flat_map(Row::messages) |
| 1318 | .any(|message| message.key == message_key && message.reactions.len() > 1); |
| 1319 | self.reaction_details = Some(ReactionDetails { |
| 1320 | message_key: message_key.to_owned(), |
| 1321 | anchor_glyph: glyph.to_owned(), |
| 1322 | tab: multiple_kinds.then(|| glyph.to_owned()), |
| 1323 | }); |
| 1324 | cx.notify(); |
| 1325 | } |
| 1326 | |
| 1327 | fn select_reaction_tab(&mut self, tab: Option<String>, cx: &mut Context<Self>) { |
| 1328 | if let Some(details) = self.reaction_details.as_mut() { |
| 1329 | details.tab = tab; |
| 1330 | cx.notify(); |
| 1331 | } |
| 1332 | } |
| 1333 | |
| 1334 | fn close_reaction_details(&mut self, cx: &mut Context<Self>) { |
| 1335 | if self.reaction_details.take().is_some() { |
| 1336 | cx.notify(); |
| 1337 | } |
| 1338 | } |
| 1339 | |
| 1340 | fn reaction_controls(&self, key: &str, view: WeakEntity<Self>) -> ReactionControls { |
| 1341 | let open = { |
| 1342 | let (view, key) = (view.clone(), key.to_owned()); |
| 1343 | Rc::new(move |glyph: &str, cx: &mut App| { |
| 1344 | view.update(cx, |this, cx| this.open_reaction_details(&key, glyph, cx)) |
| 1345 | .ok(); |
| 1346 | }) |
| 1347 | }; |
| 1348 | let select_tab = { |
| 1349 | let view = view.clone(); |
| 1350 | Rc::new(move |tab: Option<String>, cx: &mut App| { |
| 1351 | view.update(cx, |this, cx| this.select_reaction_tab(tab, cx)) |
| 1352 | .ok(); |
| 1353 | }) |
| 1354 | }; |
| 1355 | let close = Rc::new(move |cx: &mut App| { |
| 1356 | view.update(cx, |this, cx| this.close_reaction_details(cx)) |
| 1357 | .ok(); |
| 1358 | }); |
| 1359 | let popover = self |
| 1360 | .reaction_details |
| 1361 | .as_ref() |
| 1362 | .filter(|details| details.message_key == key) |
| 1363 | .map(|details| ReactionPopover { |
| 1364 | anchor_glyph: details.anchor_glyph.clone(), |
| 1365 | tab: details.tab.clone(), |
| 1366 | }); |
| 1367 | ReactionControls { |
| 1368 | open, |
| 1369 | select_tab, |
| 1370 | close, |
| 1371 | popover, |
| 1372 | } |
| 1373 | } |
| 1374 | |
| 1375 | fn start_info(&self, cx: &App) -> Option<StartInfo> { |
| 1376 | let current = self.current.as_ref()?; |
| 1377 | let app = self.app.read(cx); |
| 1378 | let user_id = match ¤t.selection { |
| 1379 | Selection::Chat(chat_id) => app |
| 1380 | .sidebar |
| 1381 | .chats |
| 1382 | .iter() |
| 1383 | .find(|chat| &chat.id == chat_id) |
| 1384 | .filter(|chat| is_one_on_one(chat)) |
| 1385 | .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next()) |
| 1386 | .and_then(|(user_id, _)| user_id), |
| 1387 | Selection::Channel(_) => None, |
| 1388 | }; |
| 1389 | Some(StartInfo { |
| 1390 | title: current.title.clone(), |
| 1391 | user_id, |
| 1392 | }) |
| 1393 | } |
| 1394 | |
| 1395 | fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) { |
| 1396 | let Some(current) = self.current.as_ref() else { |
| 1397 | let mut rows: Vec<Row> = self |
| 1398 | .pending |
| 1399 | .iter() |
| 1400 | .cloned() |
| 1401 | .map(|row| Row::Message(Box::new(row))) |
| 1402 | .collect(); |
| 1403 | assign_series(&mut rows); |
| 1404 | self.apply_rows(rows, true, cx); |
| 1405 | return; |
| 1406 | }; |
| 1407 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 1408 | let limit = if reset { |
| 1409 | current.loaded_limit |
| 1410 | } else { |
| 1411 | current |
| 1412 | .loaded_limit |
| 1413 | .max(current.loaded_count + GROWTH_HEADROOM) |
| 1414 | }; |
| 1415 | let store = self.app.read(cx).store.clone(); |
| 1416 | let thread_root = match ¤t.mode { |
| 1417 | ViewMode::Thread(root_id) => Some(root_id.clone()), |
| 1418 | ViewMode::Flat | ViewMode::ThreadList => None, |
| 1419 | }; |
| 1420 | let sync_state = store.sync_state(&conversation_id).ok().flatten(); |
| 1421 | let window = current.detached.as_ref().map(|detached| { |
| 1422 | ( |
| 1423 | detached.oldest, |
| 1424 | detached.newest, |
| 1425 | detached.older_cursor.is_some(), |
| 1426 | detached.newer_cursor.is_some(), |
| 1427 | ) |
| 1428 | }); |
| 1429 | let records: Vec<MessageRecord> = match (&thread_root, window) { |
| 1430 | (Some(root_id), _) => store |
| 1431 | .thread_messages(&conversation_id, root_id) |
| 1432 | .unwrap_or_default(), |
| 1433 | (None, Some((oldest, newest, _, _))) => store |
| 1434 | .messages_between(&conversation_id, oldest, newest) |
| 1435 | .unwrap_or_default(), |
| 1436 | (None, None) if matches!(current.selection, Selection::Chat(_)) => without_islands( |
| 1437 | store |
| 1438 | .messages(&conversation_id, None, limit) |
| 1439 | .unwrap_or_default(), |
| 1440 | sync_state.as_ref().and_then(|state| state.oldest_loaded), |
| 1441 | ), |
| 1442 | (None, None) => store |
| 1443 | .messages(&conversation_id, None, limit) |
| 1444 | .unwrap_or_default(), |
| 1445 | }; |
| 1446 | let sync_has_more = sync_state.as_ref().is_none_or(|state| state.has_more); |
| 1447 | let mut context = self.row_context(cx); |
| 1448 | let reactor_ids: Vec<String> = records |
| 1449 | .iter() |
| 1450 | .flat_map(teams_core::reactions) |
| 1451 | .filter(|reaction| reaction.user_name.is_none()) |
| 1452 | .filter_map(|reaction| reaction.user_id) |
| 1453 | .filter(|user_id| !context.names.contains_key(user_id)) |
| 1454 | .collect(); |
| 1455 | for (user_id, name) in resolve_names(self.app.read(cx), &reactor_ids) { |
| 1456 | context.names.entry(user_id).or_insert(name); |
| 1457 | } |
| 1458 | for record in &records { |
| 1459 | if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) { |
| 1460 | context |
| 1461 | .names |
| 1462 | .entry(user_id.clone()) |
| 1463 | .or_insert_with(|| name.clone()); |
| 1464 | } |
| 1465 | } |
| 1466 | let can_load_older = self.app.read(cx).engine.is_some(); |
| 1467 | let start = self.start_info(cx); |
| 1468 | let current = self.current.as_mut().expect("checked above"); |
| 1469 | let first_unread = current.first_unread.clone(); |
| 1470 | current.loaded_limit = limit; |
| 1471 | if thread_root.is_none() { |
| 1472 | current.loaded_count = records.len(); |
| 1473 | } |
| 1474 | let has_older = sync_has_more && !current.older_blocked && can_load_older; |
| 1475 | let placeholders = current.sync.messages |
| 1476 | && records.is_empty() |
| 1477 | && !matches!(current.mode, ViewMode::Thread(_)); |
| 1478 | let in_feed = current.mode == ViewMode::ThreadList; |
| 1479 | let mut rows = match ¤t.mode { |
| 1480 | _ if placeholders => { |
| 1481 | current.has_older = false; |
| 1482 | placeholder_rows() |
| 1483 | } |
| 1484 | ViewMode::Flat => match window { |
| 1485 | Some((_, _, has_older_window, has_newer_window)) => { |
| 1486 | current.has_older = has_older_window; |
| 1487 | let mut rows = flat_rows(&records, &context, has_older_window); |
| 1488 | if has_newer_window { |
| 1489 | rows.push(Row::LoadNewer); |
| 1490 | } |
| 1491 | rows |
| 1492 | } |
| 1493 | None => { |
| 1494 | current.has_older = has_older; |
| 1495 | let mut rows = flat_rows(&records, &context, has_older); |
| 1496 | if !has_older && let Some(start) = start { |
| 1497 | rows.insert(0, Row::Start(start)); |
| 1498 | } |
| 1499 | rows |
| 1500 | } |
| 1501 | }, |
| 1502 | ViewMode::ThreadList => { |
| 1503 | current.has_older = has_older; |
| 1504 | thread_list_rows(&records, &context, has_older) |
| 1505 | } |
| 1506 | ViewMode::Thread(root_id) => { |
| 1507 | current.has_older = false; |
| 1508 | thread_rows(&records, root_id, &context) |
| 1509 | } |
| 1510 | }; |
| 1511 | let local: Vec<MessageRow> = if window.is_some() { |
| 1512 | Vec::new() |
| 1513 | } else { |
| 1514 | self.pending |
| 1515 | .iter() |
| 1516 | .cloned() |
| 1517 | .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx)) |
| 1518 | .collect() |
| 1519 | }; |
| 1520 | if in_feed { |
| 1521 | place_local_rows(&mut rows, local); |
| 1522 | } else { |
| 1523 | rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row)))); |
| 1524 | } |
| 1525 | let receipts = self.receipts(&records, cx); |
| 1526 | for row in rows.iter_mut() { |
| 1527 | if let Row::Message(message) = row |
| 1528 | && message.own |
| 1529 | { |
| 1530 | message.receipt = receipts.get(&message.key).copied().unwrap_or_default(); |
| 1531 | } |
| 1532 | } |
| 1533 | if let Some(unread_id) = &first_unread { |
| 1534 | for row in rows.iter_mut() { |
| 1535 | if let Row::Message(message) = row |
| 1536 | && &message.key == unread_id |
| 1537 | { |
| 1538 | message.new_marker = true; |
| 1539 | } |
| 1540 | } |
| 1541 | } |
| 1542 | assign_series(&mut rows); |
| 1543 | self.apply_rows(rows, reset, cx); |
| 1544 | if self.is_detached() { |
| 1545 | self.scroller |
| 1546 | .update(cx, |scroller, _| scroller.stop_following()); |
| 1547 | } |
| 1548 | } |
| 1549 | |
| 1550 | fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) { |
| 1551 | let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows); |
| 1552 | self.drop_stale_reaction_details(); |
| 1553 | let new_len = self.rows.borrow().len(); |
| 1554 | let in_feed = self.in_feed(); |
| 1555 | if reset { |
| 1556 | let marker_index = self |
| 1557 | .rows |
| 1558 | .borrow() |
| 1559 | .iter() |
| 1560 | .position(|row| matches!(row, Row::Message(message) if message.new_marker)); |
| 1561 | self.feed_at_top = true; |
| 1562 | self.scroller.update(cx, |scroller, cx| { |
| 1563 | scroller.reset(new_len, cx); |
| 1564 | if in_feed { |
| 1565 | scroller.scroll_to_item(0, cx); |
| 1566 | return; |
| 1567 | } |
| 1568 | match marker_index { |
| 1569 | Some(index) if !scroller.scroll_to_item(index, cx) => { |
| 1570 | scroller.scroll_to_end(cx) |
| 1571 | } |
| 1572 | Some(_) => {} |
| 1573 | None => scroller.scroll_to_end(cx), |
| 1574 | } |
| 1575 | }); |
| 1576 | cx.notify(); |
| 1577 | return; |
| 1578 | } |
| 1579 | let (splice, changed) = { |
| 1580 | let new_rows = self.rows.borrow(); |
| 1581 | let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect(); |
| 1582 | let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect(); |
| 1583 | ( |
| 1584 | diff_keys(&old_keys, &new_keys), |
| 1585 | changed_indices(&old_rows, &new_rows), |
| 1586 | ) |
| 1587 | }; |
| 1588 | let top_changed = splice |
| 1589 | .as_ref() |
| 1590 | .is_some_and(|splice| splice.range.start == 0); |
| 1591 | let keep_top = in_feed && (old_rows.is_empty() || (self.feed_at_top && top_changed)); |
| 1592 | self.scroller.update(cx, |scroller, cx| { |
| 1593 | if let Some(splice) = splice |
| 1594 | && !scroller.splice(splice.range, splice.count, cx) |
| 1595 | { |
| 1596 | scroller.reset(new_len, cx); |
| 1597 | } |
| 1598 | if keep_top { |
| 1599 | scroller.scroll_to_item(0, cx); |
| 1600 | } |
| 1601 | for index in changed { |
| 1602 | scroller.remeasure_items(index..index + 1, cx); |
| 1603 | } |
| 1604 | }); |
| 1605 | cx.notify(); |
| 1606 | } |
| 1607 | |
| 1608 | fn start_fetch(&mut self, cx: &mut Context<Self>) { |
| 1609 | let state = self.app.read(cx); |
| 1610 | let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync); |
| 1611 | if engine.is_none() && demo_sync.is_none() { |
| 1612 | return; |
| 1613 | } |
| 1614 | let Some(current) = self.current.as_mut() else { |
| 1615 | return; |
| 1616 | }; |
| 1617 | if current.fetched { |
| 1618 | return; |
| 1619 | } |
| 1620 | current.fetched = true; |
| 1621 | let is_chat = matches!(current.selection, Selection::Chat(_)); |
| 1622 | let newest_cached = self |
| 1623 | .rows |
| 1624 | .borrow() |
| 1625 | .iter() |
| 1626 | .flat_map(Row::messages) |
| 1627 | .filter(|message| !message.key.starts_with(PENDING_KEY_PREFIX)) |
| 1628 | .map(|message| message.created_at) |
| 1629 | .max(); |
| 1630 | let current = self.current.as_mut().expect("checked above"); |
| 1631 | if current.sync.failed { |
| 1632 | self.notice = None; |
| 1633 | } |
| 1634 | current.sync = SyncProgress { |
| 1635 | messages: true, |
| 1636 | receipts: is_chat, |
| 1637 | empty_cache: newest_cached.is_none(), |
| 1638 | newest_cached, |
| 1639 | ..SyncProgress::default() |
| 1640 | }; |
| 1641 | self.sync_generation += 1; |
| 1642 | let generation = self.sync_generation; |
| 1643 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 1644 | match (engine, demo_sync) { |
| 1645 | (Some(engine), _) => { |
| 1646 | let receiver = |
| 1647 | runtime::spawn(async move { engine.fetch_newer(&conversation_id).await }); |
| 1648 | cx.spawn(async move |this, cx| { |
| 1649 | let result = receiver.await; |
| 1650 | this.update(cx, |this, cx| this.finish_fetch(generation, result, cx)) |
| 1651 | .ok(); |
| 1652 | }) |
| 1653 | .detach(); |
| 1654 | } |
| 1655 | (None, Some(delay)) => self.simulate_sync(generation, delay, cx), |
| 1656 | (None, None) => {} |
| 1657 | } |
| 1658 | self.schedule_progress(generation, cx); |
| 1659 | self.rebuild(false, cx); |
| 1660 | self.mark_read(ReadTrigger::Incoming, cx); |
| 1661 | self.refresh_receipts(generation, cx); |
| 1662 | } |
| 1663 | |
| 1664 | fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) { |
| 1665 | cx.spawn(async move |this, cx| { |
| 1666 | cx.background_executor().timer(delay).await; |
| 1667 | this.update(cx, |this, cx| { |
| 1668 | if let Some(sync) = this.sync_of(generation) { |
| 1669 | sync.receipts = false; |
| 1670 | } |
| 1671 | this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx) |
| 1672 | }) |
| 1673 | .ok(); |
| 1674 | }) |
| 1675 | .detach(); |
| 1676 | } |
| 1677 | |
| 1678 | fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> { |
| 1679 | if generation != self.sync_generation { |
| 1680 | return None; |
| 1681 | } |
| 1682 | self.current.as_mut().map(|current| &mut current.sync) |
| 1683 | } |
| 1684 | |
| 1685 | fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) { |
| 1686 | cx.spawn(async move |this, cx| { |
| 1687 | let stages = [ |
| 1688 | (PROGRESS_DELAY, Duration::ZERO), |
| 1689 | (SLOW_AFTER, PROGRESS_DELAY), |
| 1690 | ]; |
| 1691 | for (stage, (at, previous)) in stages.into_iter().enumerate() { |
| 1692 | cx.background_executor().timer(at - previous).await; |
| 1693 | let running = this |
| 1694 | .update(cx, |this, cx| this.advance_progress(generation, stage, cx)) |
| 1695 | .unwrap_or(false); |
| 1696 | if !running { |
| 1697 | return; |
| 1698 | } |
| 1699 | } |
| 1700 | }) |
| 1701 | .detach(); |
| 1702 | } |
| 1703 | |
| 1704 | fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool { |
| 1705 | let Some(sync) = self.sync_of(generation) else { |
| 1706 | return false; |
| 1707 | }; |
| 1708 | if !sync.running() { |
| 1709 | return false; |
| 1710 | } |
| 1711 | match stage { |
| 1712 | 0 => sync.shown_at = Some(Instant::now()), |
| 1713 | _ => sync.slow = true, |
| 1714 | } |
| 1715 | cx.notify(); |
| 1716 | true |
| 1717 | } |
| 1718 | |
| 1719 | fn finish_fetch( |
| 1720 | &mut self, |
| 1721 | generation: u64, |
| 1722 | result: Result< |
| 1723 | teams_core::Result<teams_core::Delta>, |
| 1724 | tokio::sync::oneshot::error::RecvError, |
| 1725 | >, |
| 1726 | cx: &mut Context<Self>, |
| 1727 | ) { |
| 1728 | let Some(sync) = self.sync_of(generation) else { |
| 1729 | return; |
| 1730 | }; |
| 1731 | sync.messages = false; |
| 1732 | let newest_cached = sync.newest_cached; |
| 1733 | match result { |
| 1734 | Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx), |
| 1735 | Ok(Err(error)) => self.fail_sync(generation, short_error(&error)), |
| 1736 | Err(error) => self.fail_sync(generation, short_error(&error)), |
| 1737 | } |
| 1738 | self.rebuild(false, cx); |
| 1739 | self.settle_progress(generation, cx); |
| 1740 | } |
| 1741 | |
| 1742 | fn fail_sync(&mut self, generation: u64, error: String) { |
| 1743 | if let Some(sync) = self.sync_of(generation) { |
| 1744 | sync.failed = true; |
| 1745 | sync.receipts = false; |
| 1746 | } |
| 1747 | self.notice = Some(format!("Could not refresh: {error}")); |
| 1748 | } |
| 1749 | |
| 1750 | fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) { |
| 1751 | let Some(newest_cached) = newest_cached else { |
| 1752 | return; |
| 1753 | }; |
| 1754 | let Some(my_user_id) = self.row_context(cx).my_user_id else { |
| 1755 | return; |
| 1756 | }; |
| 1757 | let store = self.app.read(cx).store.clone(); |
| 1758 | let Some(current) = self.current.as_mut() else { |
| 1759 | return; |
| 1760 | }; |
| 1761 | if current.first_unread.is_some() || current.mode != ViewMode::Flat { |
| 1762 | return; |
| 1763 | } |
| 1764 | let limit = current |
| 1765 | .loaded_limit |
| 1766 | .max(current.loaded_count + GROWTH_HEADROOM); |
| 1767 | current.first_unread = store |
| 1768 | .messages(current.selection.conversation_id(), None, limit) |
| 1769 | .unwrap_or_default() |
| 1770 | .into_iter() |
| 1771 | .find(|record| { |
| 1772 | record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id) |
| 1773 | }) |
| 1774 | .map(|record| record.message_id); |
| 1775 | } |
| 1776 | |
| 1777 | fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) { |
| 1778 | let Some(sync) = self.sync_of(generation) else { |
| 1779 | return; |
| 1780 | }; |
| 1781 | if sync.running() { |
| 1782 | return; |
| 1783 | } |
| 1784 | let remaining = sync |
| 1785 | .shown_at |
| 1786 | .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed())) |
| 1787 | .unwrap_or_default(); |
| 1788 | if remaining.is_zero() { |
| 1789 | sync.shown_at = None; |
| 1790 | sync.slow = false; |
| 1791 | cx.notify(); |
| 1792 | return; |
| 1793 | } |
| 1794 | cx.spawn(async move |this, cx| { |
| 1795 | cx.background_executor().timer(remaining).await; |
| 1796 | this.update(cx, |this, cx| { |
| 1797 | if let Some(sync) = this.sync_of(generation) { |
| 1798 | sync.shown_at = None; |
| 1799 | sync.slow = false; |
| 1800 | cx.notify(); |
| 1801 | } |
| 1802 | }) |
| 1803 | .ok(); |
| 1804 | }) |
| 1805 | .detach(); |
| 1806 | } |
| 1807 | |
| 1808 | fn retry_fetch(&mut self, cx: &mut Context<Self>) { |
| 1809 | if let Some(current) = self.current.as_mut() { |
| 1810 | current.fetched = false; |
| 1811 | } |
| 1812 | self.start_fetch(cx); |
| 1813 | } |
| 1814 | |
| 1815 | fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> { |
| 1816 | let state = self.app.read(cx); |
| 1817 | let receipts_syncing = self |
| 1818 | .current |
| 1819 | .as_ref() |
| 1820 | .is_some_and(|current| current.sync.receipts); |
| 1821 | if state.mode.demo { |
| 1822 | let read_ids = crate::demo::read_message_ids(records); |
| 1823 | return records |
| 1824 | .iter() |
| 1825 | .map(|record| { |
| 1826 | let receipt = if receipts_syncing { |
| 1827 | Receipt::Pending |
| 1828 | } else if read_ids.contains(&record.message_id) { |
| 1829 | Receipt::Read |
| 1830 | } else { |
| 1831 | Receipt::Sent |
| 1832 | }; |
| 1833 | (record.message_id.clone(), receipt) |
| 1834 | }) |
| 1835 | .collect(); |
| 1836 | } |
| 1837 | let Some(engine) = state.engine.as_ref() else { |
| 1838 | return HashMap::new(); |
| 1839 | }; |
| 1840 | let unknown = if receipts_syncing { |
| 1841 | Receipt::Pending |
| 1842 | } else { |
| 1843 | Receipt::Hidden |
| 1844 | }; |
| 1845 | records |
| 1846 | .iter() |
| 1847 | .map(|record| { |
| 1848 | let receipt = match engine.receipt_state_for(record) { |
| 1849 | teams_core::ReceiptState::Read { .. } => Receipt::Read, |
| 1850 | teams_core::ReceiptState::Sent => Receipt::Sent, |
| 1851 | teams_core::ReceiptState::Unknown => unknown, |
| 1852 | }; |
| 1853 | (record.message_id.clone(), receipt) |
| 1854 | }) |
| 1855 | .collect() |
| 1856 | } |
| 1857 | |
| 1858 | fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) { |
| 1859 | let state = self.app.read(cx); |
| 1860 | let (Some(engine), Some(Selection::Chat(chat_id))) = ( |
| 1861 | state.engine.clone(), |
| 1862 | self.current.as_ref().map(|c| c.selection.clone()), |
| 1863 | ) else { |
| 1864 | return; |
| 1865 | }; |
| 1866 | let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await }); |
| 1867 | cx.spawn(async move |this, cx| { |
| 1868 | receiver.await.ok(); |
| 1869 | this.update(cx, |this, cx| { |
| 1870 | let Some(sync) = this.sync_of(generation) else { |
| 1871 | return; |
| 1872 | }; |
| 1873 | sync.receipts = false; |
| 1874 | this.rebuild(false, cx); |
| 1875 | this.settle_progress(generation, cx); |
| 1876 | }) |
| 1877 | .ok(); |
| 1878 | }) |
| 1879 | .detach(); |
| 1880 | } |
| 1881 | |
| 1882 | fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) { |
| 1883 | if self.draft_active { |
| 1884 | return; |
| 1885 | } |
| 1886 | let state = self.app.read(cx); |
| 1887 | if state.viewing_call() && !self.pinned { |
| 1888 | return; |
| 1889 | } |
| 1890 | let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone()) |
| 1891 | else { |
| 1892 | return; |
| 1893 | }; |
| 1894 | if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only { |
| 1895 | return; |
| 1896 | } |
| 1897 | let unread = state |
| 1898 | .sidebar |
| 1899 | .chats |
| 1900 | .iter() |
| 1901 | .any(|chat| chat.id == chat_id && chat.unread) |
| 1902 | && !state.keeps_unread(&chat_id); |
| 1903 | let Some(plan) = plan_read(self.window_active, unread, trigger) else { |
| 1904 | return; |
| 1905 | }; |
| 1906 | self.app |
| 1907 | .update(cx, |state, cx| state.mark_chat_read(&chat_id, cx)); |
| 1908 | if plan.clear_divider |
| 1909 | && let Some(current) = self.current.as_mut() |
| 1910 | && current.first_unread.take().is_some() |
| 1911 | { |
| 1912 | self.rebuild(false, cx); |
| 1913 | } |
| 1914 | } |
| 1915 | |
| 1916 | fn request_older(&mut self, cx: &mut Context<Self>) { |
| 1917 | if self.is_detached() { |
| 1918 | return self.request_window_page(WindowDirection::Backward, cx); |
| 1919 | } |
| 1920 | let Some(engine) = self.app.read(cx).engine.clone() else { |
| 1921 | return; |
| 1922 | }; |
| 1923 | let Some(current) = self.current.as_mut() else { |
| 1924 | return; |
| 1925 | }; |
| 1926 | if current.loading_older || current.older_blocked || !current.has_older { |
| 1927 | return; |
| 1928 | } |
| 1929 | current.loading_older = true; |
| 1930 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 1931 | let task_id = conversation_id.clone(); |
| 1932 | let receiver = runtime::spawn(async move { engine.load_older(&task_id).await }); |
| 1933 | cx.spawn(async move |this, cx| { |
| 1934 | let result = receiver.await; |
| 1935 | this.update(cx, |this, cx| { |
| 1936 | this.finish_older(&conversation_id, result, cx) |
| 1937 | }) |
| 1938 | .ok(); |
| 1939 | }) |
| 1940 | .detach(); |
| 1941 | } |
| 1942 | |
| 1943 | fn finish_older( |
| 1944 | &mut self, |
| 1945 | conversation_id: &str, |
| 1946 | result: Result< |
| 1947 | teams_core::Result<Vec<MessageRecord>>, |
| 1948 | tokio::sync::oneshot::error::RecvError, |
| 1949 | >, |
| 1950 | cx: &mut Context<Self>, |
| 1951 | ) { |
| 1952 | let Some(current) = self.current.as_mut() else { |
| 1953 | return; |
| 1954 | }; |
| 1955 | if current.selection.conversation_id() != conversation_id { |
| 1956 | return; |
| 1957 | } |
| 1958 | current.loading_older = false; |
| 1959 | match result { |
| 1960 | Ok(Ok(records)) if !records.is_empty() => { |
| 1961 | current.loaded_limit = current.loaded_count + records.len(); |
| 1962 | } |
| 1963 | Ok(Ok(_)) => current.older_blocked = true, |
| 1964 | Ok(Err(error)) => { |
| 1965 | current.older_blocked = true; |
| 1966 | self.notice = Some(format!( |
| 1967 | "Could not load older messages: {}", |
| 1968 | short_error(&error) |
| 1969 | )); |
| 1970 | } |
| 1971 | Err(_) => current.older_blocked = true, |
| 1972 | } |
| 1973 | self.rebuild(false, cx); |
| 1974 | } |
| 1975 | |
| 1976 | fn clear_pending(&mut self) { |
| 1977 | self.pending.clear(); |
| 1978 | self.pending_outgoing.clear(); |
| 1979 | } |
| 1980 | |
| 1981 | fn outbox_route(&self, reply_root: Option<String>) -> (OutboxTarget, Option<String>) { |
| 1982 | if let Some(root_id) = reply_root { |
| 1983 | return (OutboxTarget::Thread, Some(root_id)); |
| 1984 | } |
| 1985 | match self.current.as_ref().map(|current| ¤t.mode) { |
| 1986 | Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())), |
| 1987 | Some(ViewMode::ThreadList) => (OutboxTarget::Post, None), |
| 1988 | _ => (OutboxTarget::Flat, None), |
| 1989 | } |
| 1990 | } |
| 1991 | |
| 1992 | fn reload_pending(&mut self, cx: &App) { |
| 1993 | self.clear_pending(); |
| 1994 | let state = self.app.read(cx); |
| 1995 | if state.mode.demo || state.mode.read_only { |
| 1996 | return; |
| 1997 | } |
| 1998 | let Some(current) = self.current.as_ref() else { |
| 1999 | return; |
| 2000 | }; |
| 2001 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 2002 | let Ok(records) = state.store.outbox_for_conversation(&conversation_id) else { |
| 2003 | return; |
| 2004 | }; |
| 2005 | let my_user_id = state.store.meta(META_USER_ID).ok().flatten(); |
| 2006 | let mut pending = Vec::new(); |
| 2007 | for record in records { |
| 2008 | if !shown_in_view(¤t.mode, &record) { |
| 2009 | continue; |
| 2010 | } |
| 2011 | let Some(outgoing) = outgoing_of(&record) else { |
| 2012 | continue; |
| 2013 | }; |
| 2014 | let delivery = match record.state { |
| 2015 | OutboxState::Sending => Delivery::Sending, |
| 2016 | OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()), |
| 2017 | }; |
| 2018 | let mut row = pending_row( |
| 2019 | record.id.clone(), |
| 2020 | conversation_id.clone(), |
| 2021 | my_user_id.clone(), |
| 2022 | record.created_at, |
| 2023 | &outgoing, |
| 2024 | delivery, |
| 2025 | ); |
| 2026 | row.reply_root = record.thread_root_id.clone(); |
| 2027 | pending.push((row, record.id, outgoing)); |
| 2028 | } |
| 2029 | for (row, id, outgoing) in pending { |
| 2030 | self.pending.push(row); |
| 2031 | self.pending_outgoing.insert(id, outgoing); |
| 2032 | } |
| 2033 | } |
| 2034 | |
| 2035 | fn discard_outbox_row(&self, id: &str, cx: &mut Context<Self>) { |
| 2036 | self.app.read(cx).store.delete_outbox(id).ok(); |
| 2037 | self.app |
| 2038 | .update(cx, |state, cx| state.refresh_local_previews(cx)); |
| 2039 | } |
| 2040 | |
| 2041 | fn delete_pending(&mut self, key: &str, cx: &mut Context<Self>) { |
| 2042 | self.pending.retain(|row| row.key != key); |
| 2043 | self.pending_outgoing.remove(key); |
| 2044 | self.discard_outbox_row(key, cx); |
| 2045 | self.rebuild(false, cx); |
| 2046 | } |
| 2047 | |
| 2048 | fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) { |
| 2049 | self.leave_detached(cx); |
| 2050 | self.send_as(new_outbox_id(), outgoing, None, window, cx); |
| 2051 | } |
| 2052 | |
| 2053 | fn send_in_thread( |
| 2054 | &mut self, |
| 2055 | root_id: String, |
| 2056 | outgoing: Outgoing, |
| 2057 | window: &mut Window, |
| 2058 | cx: &mut Context<Self>, |
| 2059 | ) { |
| 2060 | self.send_as(new_outbox_id(), outgoing, Some(root_id), window, cx); |
| 2061 | } |
| 2062 | |
| 2063 | fn send_as( |
| 2064 | &mut self, |
| 2065 | id: String, |
| 2066 | outgoing: Outgoing, |
| 2067 | reply_root: Option<String>, |
| 2068 | window: &mut Window, |
| 2069 | cx: &mut Context<Self>, |
| 2070 | ) { |
| 2071 | let state = self.app.read(cx); |
| 2072 | let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone()); |
| 2073 | let Some(current) = self.current.as_ref() else { |
| 2074 | return; |
| 2075 | }; |
| 2076 | if mode.read_only || mode.demo { |
| 2077 | self.restore_unsent( |
| 2078 | "Read-only mode: nothing was sent", |
| 2079 | &outgoing, |
| 2080 | reply_root.as_deref(), |
| 2081 | window, |
| 2082 | cx, |
| 2083 | ); |
| 2084 | return; |
| 2085 | } |
| 2086 | let Some(engine) = engine else { |
| 2087 | self.discard_outbox_row(&id, cx); |
| 2088 | self.restore_unsent( |
| 2089 | "Not connected yet: nothing was sent", |
| 2090 | &outgoing, |
| 2091 | reply_root.as_deref(), |
| 2092 | window, |
| 2093 | cx, |
| 2094 | ); |
| 2095 | return; |
| 2096 | }; |
| 2097 | let conversation_id = current.selection.conversation_id().to_owned(); |
| 2098 | let (target, thread_root_id) = self.outbox_route(reply_root); |
| 2099 | let created_at = Utc::now(); |
| 2100 | self.push_pending( |
| 2101 | id.clone(), |
| 2102 | created_at, |
| 2103 | &outgoing, |
| 2104 | thread_root_id.clone(), |
| 2105 | cx, |
| 2106 | ); |
| 2107 | if let Some(record) = outbox_record( |
| 2108 | &id, |
| 2109 | &conversation_id, |
| 2110 | target, |
| 2111 | thread_root_id.as_deref(), |
| 2112 | &outgoing, |
| 2113 | created_at, |
| 2114 | ) { |
| 2115 | store.put_outbox(&record).ok(); |
| 2116 | } |
| 2117 | self.notice = None; |
| 2118 | self.rebuild(false, cx); |
| 2119 | if self.in_feed() { |
| 2120 | self.scroller |
| 2121 | .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx)); |
| 2122 | } else { |
| 2123 | self.scroller |
| 2124 | .update(cx, |scroller, cx| scroller.scroll_to_end(cx)); |
| 2125 | } |
| 2126 | |
| 2127 | let receiver = runtime::spawn(async move { |
| 2128 | deliver( |
| 2129 | &engine, |
| 2130 | &conversation_id, |
| 2131 | target, |
| 2132 | thread_root_id.as_deref(), |
| 2133 | &outgoing, |
| 2134 | ) |
| 2135 | .await |
| 2136 | }); |
| 2137 | cx.spawn_in(window, async move |this, cx| { |
| 2138 | let result = receiver.await; |
| 2139 | this.update(cx, |this, cx| this.finish_send(&id, result, cx)) |
| 2140 | .ok(); |
| 2141 | }) |
| 2142 | .detach(); |
| 2143 | } |
| 2144 | |
| 2145 | fn restore_unsent( |
| 2146 | &mut self, |
| 2147 | message: &str, |
| 2148 | outgoing: &Outgoing, |
| 2149 | reply_root: Option<&str>, |
| 2150 | window: &mut Window, |
| 2151 | cx: &mut Context<Self>, |
| 2152 | ) { |
| 2153 | self.notice = Some(message.to_owned()); |
| 2154 | if let (Some(root_id), true) = (reply_root, self.in_feed()) { |
| 2155 | self.open_reply_editor(root_id.to_owned(), outgoing.reply.clone(), window, cx); |
| 2156 | if let Some(composer) = self.reply_composer.clone() { |
| 2157 | composer.update(cx, |composer, cx| composer.restore(outgoing, window, cx)); |
| 2158 | } |
| 2159 | } else { |
| 2160 | self.show_main_composer(cx); |
| 2161 | self.restore_subject(outgoing.subject.as_deref(), window, cx); |
| 2162 | self.composer |
| 2163 | .update(cx, |composer, cx| composer.restore(outgoing, window, cx)); |
| 2164 | } |
| 2165 | cx.notify(); |
| 2166 | } |
| 2167 | |
| 2168 | fn next_pending_key(&mut self) -> String { |
| 2169 | self.pending_counter += 1; |
| 2170 | format!("{PENDING_KEY_PREFIX}{}", self.pending_counter) |
| 2171 | } |
| 2172 | |
| 2173 | fn push_pending( |
| 2174 | &mut self, |
| 2175 | key: String, |
| 2176 | created_at: DateTime<Utc>, |
| 2177 | outgoing: &Outgoing, |
| 2178 | reply_root: Option<String>, |
| 2179 | cx: &App, |
| 2180 | ) { |
| 2181 | let my_user_id = self.row_context(cx).my_user_id; |
| 2182 | let conversation_id = self |
| 2183 | .current |
| 2184 | .as_ref() |
| 2185 | .map(|current| current.selection.conversation_id().to_owned()) |
| 2186 | .unwrap_or_default(); |
| 2187 | let mut row = pending_row( |
| 2188 | key.clone(), |
| 2189 | conversation_id, |
| 2190 | my_user_id, |
| 2191 | created_at, |
| 2192 | outgoing, |
| 2193 | Delivery::Sending, |
| 2194 | ); |
| 2195 | row.reply_root = reply_root; |
| 2196 | self.pending.push(row); |
| 2197 | self.pending_outgoing.insert(key, outgoing.clone()); |
| 2198 | } |
| 2199 | |
| 2200 | fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) { |
| 2201 | let (recipients, topic) = { |
| 2202 | let draft = self.draft.read(cx); |
| 2203 | let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty()); |
| 2204 | (draft.chips().to_vec(), topic) |
| 2205 | }; |
| 2206 | if recipients.is_empty() { |
| 2207 | self.restore_unsent("Add at least one person first", &outgoing, None, window, cx); |
| 2208 | self.draft |
| 2209 | .update(cx, |draft, cx| draft.focus_query(window, cx)); |
| 2210 | return; |
| 2211 | } |
| 2212 | if self |
| 2213 | .pending |
| 2214 | .iter() |
| 2215 | .any(|row| matches!(row.delivery, Delivery::Sending)) |
| 2216 | { |
| 2217 | self.restore_unsent("Still creating the chat", &outgoing, None, window, cx); |
| 2218 | return; |
| 2219 | } |
| 2220 | let state = self.app.read(cx); |
| 2221 | let (mode, engine) = (state.mode, state.engine.clone()); |
| 2222 | if mode.read_only { |
| 2223 | self.restore_unsent( |
| 2224 | "Read-only mode: nothing was sent", |
| 2225 | &outgoing, |
| 2226 | None, |
| 2227 | window, |
| 2228 | cx, |
| 2229 | ); |
| 2230 | return; |
| 2231 | } |
| 2232 | if mode.demo && outgoing.has_attachments() { |
| 2233 | self.restore_unsent( |
| 2234 | "Read-only mode: nothing was sent", |
| 2235 | &outgoing, |
| 2236 | None, |
| 2237 | window, |
| 2238 | cx, |
| 2239 | ); |
| 2240 | return; |
| 2241 | } |
| 2242 | if mode.demo { |
| 2243 | self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx); |
| 2244 | return; |
| 2245 | } |
| 2246 | let Some(engine) = engine else { |
| 2247 | self.restore_unsent( |
| 2248 | "Not connected yet: nothing was sent", |
| 2249 | &outgoing, |
| 2250 | None, |
| 2251 | window, |
| 2252 | cx, |
| 2253 | ); |
| 2254 | return; |
| 2255 | }; |
| 2256 | let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect(); |
| 2257 | let known_chat = self |
| 2258 | .draft_created |
| 2259 | .as_ref() |
| 2260 | .filter(|(created_for, _)| *created_for == user_ids) |
| 2261 | .map(|(_, chat_id)| chat_id.clone()) |
| 2262 | .or_else(|| self.draft_target_chat(cx)); |
| 2263 | self.pending.clear(); |
| 2264 | self.pending_outgoing.clear(); |
| 2265 | self.draft_error = None; |
| 2266 | self.notice = None; |
| 2267 | let key = self.next_pending_key(); |
| 2268 | self.push_pending(key.clone(), Utc::now(), &outgoing, None, cx); |
| 2269 | self.rebuild(true, cx); |
| 2270 | let recipients_for_finish = user_ids.clone(); |
| 2271 | let receiver = runtime::spawn(async move { |
| 2272 | let chat_id = match known_chat { |
| 2273 | Some(chat_id) => chat_id, |
| 2274 | None => { |
| 2275 | let created = match user_ids.as_slice() { |
| 2276 | [user_id] => engine.create_one_on_one(user_id).await, |
| 2277 | _ => engine.create_group(&user_ids, topic.as_deref()).await, |
| 2278 | }; |
| 2279 | match created { |
| 2280 | Ok(chat_id) => chat_id, |
| 2281 | Err(error) => return (None, Some(short_error(&error))), |
| 2282 | } |
| 2283 | } |
| 2284 | }; |
| 2285 | let sent = engine |
| 2286 | .send_message_with_extras( |
| 2287 | &chat_id, |
| 2288 | &outgoing.html(), |
| 2289 | None, |
| 2290 | &outgoing.mentions, |
| 2291 | &outgoing.extras(), |
| 2292 | ) |
| 2293 | .await; |
| 2294 | if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) { |
| 2295 | let _ = engine |
| 2296 | .attach_link_preview(&chat_id, &record.message_id, preview) |
| 2297 | .await; |
| 2298 | } |
| 2299 | (Some(chat_id), sent.err().map(|error| short_error(&error))) |
| 2300 | }); |
| 2301 | cx.spawn_in(window, async move |this, cx| { |
| 2302 | let result = receiver.await; |
| 2303 | this.update_in(cx, |this, _, cx| { |
| 2304 | this.finish_new_chat(&key, recipients_for_finish, result, cx) |
| 2305 | }) |
| 2306 | .ok(); |
| 2307 | }) |
| 2308 | .detach(); |
| 2309 | } |
| 2310 | |
| 2311 | fn finish_new_chat( |
| 2312 | &mut self, |
| 2313 | key: &str, |
| 2314 | user_ids: Vec<String>, |
| 2315 | result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>, |
| 2316 | cx: &mut Context<Self>, |
| 2317 | ) { |
| 2318 | if !self.draft_active || !self.pending.iter().any(|row| row.key == key) { |
| 2319 | return; |
| 2320 | } |
| 2321 | let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned()))); |
| 2322 | self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id)); |
| 2323 | match (chat_id, error) { |
| 2324 | (Some(chat_id), None) => { |
| 2325 | self.app.update(cx, |state, cx| { |
| 2326 | state.reload_sidebar(cx); |
| 2327 | state.select(Selection::Chat(chat_id), cx); |
| 2328 | }); |
| 2329 | } |
| 2330 | (created, error) => { |
| 2331 | if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) { |
| 2332 | row.delivery = Delivery::Failed(error.unwrap_or_default()); |
| 2333 | } |
| 2334 | self.draft_error = Some( |
| 2335 | if created.is_some() { |
| 2336 | "Couldn't send the message." |
| 2337 | } else { |
| 2338 | "Couldn't create the chat." |
| 2339 | } |
| 2340 | .to_owned(), |
| 2341 | ); |
| 2342 | self.rebuild(false, cx); |
| 2343 | } |
| 2344 | } |
| 2345 | } |
| 2346 | |
| 2347 | fn send_demo_new_chat( |
| 2348 | &mut self, |
| 2349 | outgoing: &Outgoing, |
| 2350 | recipients: &[super::new_chat::Pick], |
| 2351 | topic: Option<&str>, |
| 2352 | cx: &mut Context<Self>, |
| 2353 | ) { |
| 2354 | let (store, chats) = { |
| 2355 | let state = self.app.read(cx); |
| 2356 | (state.store.clone(), state.sidebar.chats.clone()) |
| 2357 | }; |
| 2358 | let people: Vec<(String, String)> = recipients |
| 2359 | .iter() |
| 2360 | .map(|pick| (pick.user_id.clone(), pick.name.clone())) |
| 2361 | .collect(); |
| 2362 | let (chat, message) = match self.draft_target_chat(cx) { |
| 2363 | Some(chat_id) => { |
| 2364 | let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else { |
| 2365 | return; |
| 2366 | }; |
| 2367 | crate::demo::send_in_chat(chat, &outgoing.text(), &outgoing.html(), Utc::now()) |
| 2368 | } |
| 2369 | None => crate::demo::new_chat( |
| 2370 | &chats, |
| 2371 | &people, |
| 2372 | topic, |
| 2373 | &outgoing.text(), |
| 2374 | &outgoing.html(), |
| 2375 | Utc::now(), |
| 2376 | ), |
| 2377 | }; |
| 2378 | let _ = store.upsert_chats(std::slice::from_ref(&chat)); |
| 2379 | let _ = store.upsert_messages(std::slice::from_ref(&message)); |
| 2380 | self.app.update(cx, |state, cx| { |
| 2381 | state.reload_sidebar(cx); |
| 2382 | state.select(Selection::Chat(chat.id.clone()), cx); |
| 2383 | }); |
| 2384 | } |
| 2385 | |
| 2386 | fn conversation_id(&self) -> Option<String> { |
| 2387 | self.current |
| 2388 | .as_ref() |
| 2389 | .map(|current| current.selection.conversation_id().to_owned()) |
| 2390 | } |
| 2391 | |
| 2392 | fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> { |
| 2393 | let conversation_id = self.conversation_id()?; |
| 2394 | let my_user_id = self.row_context(cx).my_user_id?; |
| 2395 | self.app |
| 2396 | .read(cx) |
| 2397 | .store |
| 2398 | .messages_by_id(&conversation_id, &[message_id.to_owned()]) |
| 2399 | .ok()? |
| 2400 | .remove(message_id) |
| 2401 | .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id)) |
| 2402 | } |
| 2403 | |
| 2404 | fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) { |
| 2405 | let target = match slot { |
| 2406 | HoverSlot::Row => &mut self.hovered_message, |
| 2407 | HoverSlot::Toolbar => &mut self.toolbar_hovered, |
| 2408 | }; |
| 2409 | if hovered { |
| 2410 | *target = Some(key.to_owned()); |
| 2411 | } else if target.as_deref() == Some(key) { |
| 2412 | *target = None; |
| 2413 | } |
| 2414 | if let Some(suppressed) = self.toolbar_suppressed.as_deref() |
| 2415 | && self.hovered_message.as_deref() != Some(suppressed) |
| 2416 | && self.toolbar_hovered.as_deref() != Some(suppressed) |
| 2417 | { |
| 2418 | self.toolbar_suppressed = None; |
| 2419 | } |
| 2420 | cx.notify(); |
| 2421 | } |
| 2422 | |
| 2423 | fn suppress_toolbar(&mut self, key: &str, cx: &mut Context<Self>) { |
| 2424 | if self.toolbar_hovered.as_deref() == Some(key) { |
| 2425 | self.toolbar_hovered = None; |
| 2426 | } |
| 2427 | self.toolbar_suppressed = Some(key.to_owned()); |
| 2428 | cx.notify(); |
| 2429 | } |
| 2430 | |
| 2431 | fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) { |
| 2432 | if open { |
| 2433 | self.toolbar_pinned = Some(key.to_owned()); |
| 2434 | } else if self.toolbar_pinned.as_deref() == Some(key) { |
| 2435 | self.toolbar_pinned = None; |
| 2436 | } |
| 2437 | cx.notify(); |
| 2438 | } |
| 2439 | |
| 2440 | fn toolbar_visible(&self, key: &str) -> bool { |
| 2441 | self.toolbar_suppressed.as_deref() != Some(key) |
| 2442 | && self |
| 2443 | .toolbar_pinned |
| 2444 | .as_deref() |
| 2445 | .or(self.toolbar_hovered.as_deref()) |
| 2446 | .or(self.hovered_message.as_deref()) |
| 2447 | == Some(key) |
| 2448 | } |
| 2449 | |
| 2450 | fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) { |
| 2451 | self.change_reaction(message_id, glyph, false, None, cx); |
| 2452 | } |
| 2453 | |
| 2454 | fn change_reaction( |
| 2455 | &mut self, |
| 2456 | message_id: &str, |
| 2457 | glyph: &str, |
| 2458 | only_add: bool, |
| 2459 | accepted_proposal: Option<String>, |
| 2460 | cx: &mut Context<Self>, |
| 2461 | ) -> ReactionAttempt { |
| 2462 | let Some(conversation_id) = self.conversation_id() else { |
| 2463 | return ReactionAttempt::Blocked; |
| 2464 | }; |
| 2465 | let state = self.app.read(cx); |
| 2466 | let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone()); |
| 2467 | let engine = engine.filter(|_| !mode.read_only); |
| 2468 | if !mode.demo && engine.is_none() { |
| 2469 | self.show_notice("Read-only mode: reaction not sent", cx); |
| 2470 | return ReactionAttempt::Blocked; |
| 2471 | } |
| 2472 | let my_user_id = self.row_context(cx).my_user_id; |
| 2473 | let Some(mut record) = store |
| 2474 | .messages_by_id(&conversation_id, &[message_id.to_owned()]) |
| 2475 | .ok() |
| 2476 | .and_then(|mut found| found.remove(message_id)) |
| 2477 | else { |
| 2478 | return ReactionAttempt::MissingMessage; |
| 2479 | }; |
| 2480 | let wanted = reaction_glyph(glyph); |
| 2481 | let mut visible = teams_core::reactions(&record); |
| 2482 | apply_pending_reactions( |
| 2483 | &mut visible, |
| 2484 | self.pending_reactions.get(message_id), |
| 2485 | my_user_id.as_deref(), |
| 2486 | Utc::now(), |
| 2487 | ); |
| 2488 | let added = !has_own_reaction(&visible, glyph, my_user_id.as_deref()); |
| 2489 | if only_add && !added { |
| 2490 | return ReactionAttempt::AlreadyThere; |
| 2491 | } |
| 2492 | let Some(engine) = engine.filter(|_| !mode.demo) else { |
| 2493 | let mut reactions = teams_core::reactions(&record); |
| 2494 | set_own_reaction( |
| 2495 | &mut reactions, |
| 2496 | glyph, |
| 2497 | my_user_id.as_deref(), |
| 2498 | added, |
| 2499 | Utc::now(), |
| 2500 | ); |
| 2501 | record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default(); |
| 2502 | let _ = store.upsert_messages(std::slice::from_ref(&record)); |
| 2503 | if added { |
| 2504 | self.record_reaction_use(glyph, cx); |
| 2505 | } |
| 2506 | self.rebuild(false, cx); |
| 2507 | return ReactionAttempt::Acted; |
| 2508 | }; |
| 2509 | let entries = self |
| 2510 | .pending_reactions |
| 2511 | .entry(message_id.to_owned()) |
| 2512 | .or_default(); |
| 2513 | entries.retain(|(pending, _)| *pending != wanted); |
| 2514 | entries.push((wanted.clone(), added)); |
| 2515 | self.rebuild(false, cx); |
| 2516 | let (message_id, glyph) = (message_id.to_owned(), glyph.to_owned()); |
| 2517 | let reaction_type = api_reaction(&wanted); |
| 2518 | let receiver = runtime::spawn({ |
| 2519 | let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone()); |
| 2520 | async move { |
| 2521 | if added { |
| 2522 | engine |
| 2523 | .set_reaction(&conversation_id, &message_id, &reaction_type) |
| 2524 | .await |
| 2525 | } else { |
| 2526 | engine |
| 2527 | .unset_reaction(&conversation_id, &message_id, &reaction_type) |
| 2528 | .await |
| 2529 | } |
| 2530 | } |
| 2531 | }); |
| 2532 | cx.spawn(async move |this, cx| { |
| 2533 | let outcome = match receiver.await { |
| 2534 | Ok(Ok(())) => Ok(()), |
| 2535 | Ok(Err(error)) => Err(short_error(&error)), |
| 2536 | Err(_) => Err("cancelled".to_owned()), |
| 2537 | }; |
| 2538 | this.update(cx, |this, cx| { |
| 2539 | this.finish_reaction( |
| 2540 | &conversation_id, |
| 2541 | &message_id, |
| 2542 | &glyph, |
| 2543 | added, |
| 2544 | accepted_proposal.as_deref(), |
| 2545 | outcome, |
| 2546 | cx, |
| 2547 | ) |
| 2548 | }) |
| 2549 | .ok(); |
| 2550 | }) |
| 2551 | .detach(); |
| 2552 | ReactionAttempt::Started |
| 2553 | } |
| 2554 | |
| 2555 | fn finish_reaction( |
| 2556 | &mut self, |
| 2557 | conversation_id: &str, |
| 2558 | message_id: &str, |
| 2559 | glyph: &str, |
| 2560 | added: bool, |
| 2561 | accepted_proposal: Option<&str>, |
| 2562 | outcome: Result<(), String>, |
| 2563 | cx: &mut Context<Self>, |
| 2564 | ) { |
| 2565 | let wanted = reaction_glyph(glyph); |
| 2566 | let store = self.app.read(cx).store.clone(); |
| 2567 | if let Some(proposal_id) = accepted_proposal.filter(|_| outcome.is_ok()) { |
| 2568 | crate::agent_api::resolve_reaction_proposal( |
| 2569 | conversation_id, |
| 2570 | message_id, |
| 2571 | proposal_id, |
| 2572 | mcp::ReactionOutcome::Accepted, |
| 2573 | cx, |
| 2574 | ); |
| 2575 | } |
| 2576 | if outcome.is_ok() { |
| 2577 | let my_user_id = self.row_context(cx).my_user_id; |
| 2578 | if let Some(mut record) = store |
| 2579 | .messages_by_id(conversation_id, &[message_id.to_owned()]) |
| 2580 | .ok() |
| 2581 | .and_then(|mut found| found.remove(message_id)) |
| 2582 | { |
| 2583 | let mut reactions = teams_core::reactions(&record); |
| 2584 | set_own_reaction( |
| 2585 | &mut reactions, |
| 2586 | glyph, |
| 2587 | my_user_id.as_deref(), |
| 2588 | added, |
| 2589 | Utc::now(), |
| 2590 | ); |
| 2591 | record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default(); |
| 2592 | let _ = store.upsert_messages(std::slice::from_ref(&record)); |
| 2593 | } |
| 2594 | if added { |
| 2595 | self.record_reaction_use(glyph, cx); |
| 2596 | } |
| 2597 | } |
| 2598 | if let Some(entries) = self.pending_reactions.get_mut(message_id) { |
| 2599 | entries.retain(|entry| *entry != (wanted.clone(), added)); |
| 2600 | if entries.is_empty() { |
| 2601 | self.pending_reactions.remove(message_id); |
| 2602 | } |
| 2603 | } |
| 2604 | self.rebuild(false, cx); |
| 2605 | if let Err(error) = outcome { |
| 2606 | self.show_notice(&format!("Reaction failed: {error}"), cx); |
| 2607 | } |
| 2608 | } |
| 2609 | |
| 2610 | fn record_reaction_use(&mut self, glyph: &str, cx: &mut Context<Self>) { |
| 2611 | let store = self.app.read(cx).store.clone(); |
| 2612 | self.recent.update(cx, |recent, cx| { |
| 2613 | recent.reload(&store); |
| 2614 | recent.record_use(glyph); |
| 2615 | recent.save(&store); |
| 2616 | cx.notify(); |
| 2617 | }); |
| 2618 | } |
| 2619 | |
| 2620 | fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 2621 | let Some(record) = self.own_record(message_id, cx) else { |
| 2622 | return; |
| 2623 | }; |
| 2624 | let edit = EditPreview { |
| 2625 | message_id: record.message_id.clone(), |
| 2626 | excerpt: reply_excerpt(&record), |
| 2627 | scheduled: None, |
| 2628 | }; |
| 2629 | let in_chat = matches!( |
| 2630 | self.current.as_ref().map(|current| ¤t.selection), |
| 2631 | Some(Selection::Chat(_)) |
| 2632 | ); |
| 2633 | let mentions = if in_chat { |
| 2634 | teams_core::user_mention_inputs(&record) |
| 2635 | } else { |
| 2636 | Vec::new() |
| 2637 | }; |
| 2638 | let draft = Outgoing { |
| 2639 | draft: message_draft(&record), |
| 2640 | subject: None, |
| 2641 | mentions, |
| 2642 | reply: None, |
| 2643 | edit: Some(edit), |
| 2644 | images: Vec::new(), |
| 2645 | files: Vec::new(), |
| 2646 | link_preview: None, |
| 2647 | }; |
| 2648 | self.show_main_composer(cx); |
| 2649 | self.composer |
| 2650 | .update(cx, |composer, cx| composer.begin_edit(draft, window, cx)); |
| 2651 | } |
| 2652 | |
| 2653 | fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 2654 | if self.draft_active { |
| 2655 | return; |
| 2656 | } |
| 2657 | let key = self |
| 2658 | .rows |
| 2659 | .borrow() |
| 2660 | .iter() |
| 2661 | .flat_map(Row::messages) |
| 2662 | .filter(|message| { |
| 2663 | message.own && !message.deleted && !message.key.starts_with(PENDING_KEY_PREFIX) |
| 2664 | }) |
| 2665 | .max_by_key(|message| message.created_at) |
| 2666 | .map(|message| message.key.clone()); |
| 2667 | if let Some(key) = key { |
| 2668 | self.begin_edit(&key, window, cx); |
| 2669 | } |
| 2670 | } |
| 2671 | |
| 2672 | fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) { |
| 2673 | let Some(edit) = outgoing.edit.clone() else { |
| 2674 | return; |
| 2675 | }; |
| 2676 | let Some(conversation_id) = self.conversation_id() else { |
| 2677 | return; |
| 2678 | }; |
| 2679 | let state = self.app.read(cx); |
| 2680 | let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone()); |
| 2681 | if mode.demo { |
| 2682 | if let Some(mut record) = self.own_record(&edit.message_id, cx) { |
| 2683 | record.body_html = outgoing.html(); |
| 2684 | record.edited_at = Some(Utc::now()); |
| 2685 | let _ = store.upsert_messages(std::slice::from_ref(&record)); |
| 2686 | self.rebuild(false, cx); |
| 2687 | } |
| 2688 | return; |
| 2689 | } |
| 2690 | let Some(engine) = engine.filter(|_| !mode.read_only) else { |
| 2691 | self.notice = Some("Read-only mode: edit not saved".to_owned()); |
| 2692 | self.show_main_composer(cx); |
| 2693 | self.composer |
| 2694 | .update(cx, |composer, cx| composer.restore(&outgoing, window, cx)); |
| 2695 | cx.notify(); |
| 2696 | return; |
| 2697 | }; |
| 2698 | let sent = outgoing.clone(); |
| 2699 | let receiver = runtime::spawn(async move { |
| 2700 | engine |
| 2701 | .edit_message_html( |
| 2702 | &conversation_id, |
| 2703 | &edit.message_id, |
| 2704 | &sent.html(), |
| 2705 | &sent.mentions, |
| 2706 | ) |
| 2707 | .await |
| 2708 | }); |
| 2709 | cx.spawn_in(window, async move |this, cx| { |
| 2710 | let failed = !matches!(receiver.await, Ok(Ok(()))); |
| 2711 | this.update_in(cx, |this, window, cx| { |
| 2712 | if failed { |
| 2713 | this.show_main_composer(cx); |
| 2714 | if this.composer.read(cx).is_empty(cx) { |
| 2715 | this.notice = |
| 2716 | Some("Edit failed: your text is back in the composer".to_owned()); |
| 2717 | this.composer |
| 2718 | .update(cx, |composer, cx| composer.restore(&outgoing, window, cx)); |
| 2719 | } else { |
| 2720 | this.notice = Some("Edit failed".to_owned()); |
| 2721 | } |
| 2722 | cx.notify(); |
| 2723 | } |
| 2724 | }) |
| 2725 | .ok(); |
| 2726 | }) |
| 2727 | .detach(); |
| 2728 | } |
| 2729 | |
| 2730 | fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) { |
| 2731 | let Some(mut record) = self.own_record(message_id, cx) else { |
| 2732 | return; |
| 2733 | }; |
| 2734 | let state = self.app.read(cx); |
| 2735 | let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone()); |
| 2736 | if mode.demo { |
| 2737 | record.deleted = true; |
| 2738 | let _ = store.upsert_messages(std::slice::from_ref(&record)); |
| 2739 | self.rebuild(false, cx); |
| 2740 | return; |
| 2741 | } |
| 2742 | let Some(engine) = engine.filter(|_| !mode.read_only) else { |
| 2743 | self.show_notice("Read-only mode: message not deleted", cx); |
| 2744 | return; |
| 2745 | }; |
| 2746 | let conversation_id = record.conversation_id.clone(); |
| 2747 | let receiver = runtime::spawn(async move { |
| 2748 | engine |
| 2749 | .soft_delete_message(&conversation_id, &record.message_id) |
| 2750 | .await |
| 2751 | }); |
| 2752 | self.report_failure(receiver, "Delete failed", cx); |
| 2753 | } |
| 2754 | |
| 2755 | fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) { |
| 2756 | let Some(conversation_id) = self.conversation_id() else { |
| 2757 | return; |
| 2758 | }; |
| 2759 | let record = self |
| 2760 | .app |
| 2761 | .read(cx) |
| 2762 | .store |
| 2763 | .messages_by_id(&conversation_id, &[message_id.to_owned()]) |
| 2764 | .ok() |
| 2765 | .and_then(|mut found| found.remove(message_id)); |
| 2766 | if let Some(record) = record { |
| 2767 | cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record))); |
| 2768 | } |
| 2769 | } |
| 2770 | |
| 2771 | fn refresh_card( |
| 2772 | &mut self, |
| 2773 | key: &str, |
| 2774 | card_index: usize, |
| 2775 | action: ExecuteAction, |
| 2776 | cx: &mut Context<Self>, |
| 2777 | ) { |
| 2778 | let Some(conversation_id) = self.conversation_id() else { |
| 2779 | return; |
| 2780 | }; |
| 2781 | let scope = CardScope::message(&conversation_id, key, card_index); |
| 2782 | self.app.update(cx, |state, cx| { |
| 2783 | state.refresh_card_manually(scope, action, cx) |
| 2784 | }); |
| 2785 | } |
| 2786 | |
| 2787 | pub(super) fn translate_message(&mut self, key: &str, cx: &mut Context<Self>) { |
| 2788 | let Some(conversation_id) = self.conversation_id() else { |
| 2789 | return; |
| 2790 | }; |
| 2791 | self.app.update(cx, |state, cx| { |
| 2792 | state.translate_message(&conversation_id, key, cx) |
| 2793 | }); |
| 2794 | } |
| 2795 | |
| 2796 | fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) { |
| 2797 | self.app.update(cx, |state, cx| { |
| 2798 | state.raise_notice(message.to_owned(), None, cx) |
| 2799 | }); |
| 2800 | } |
| 2801 | |
| 2802 | fn report_failure( |
| 2803 | &mut self, |
| 2804 | receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>, |
| 2805 | label: &'static str, |
| 2806 | cx: &mut Context<Self>, |
| 2807 | ) { |
| 2808 | cx.spawn(async move |this, cx| { |
| 2809 | let error = match receiver.await { |
| 2810 | Ok(Ok(())) => return, |
| 2811 | Ok(Err(error)) => short_error(&error), |
| 2812 | Err(_) => "cancelled".to_owned(), |
| 2813 | }; |
| 2814 | this.update(cx, |this, cx| { |
| 2815 | this.show_notice(&format!("{label}: {error}"), cx) |
| 2816 | }) |
| 2817 | .ok(); |
| 2818 | }) |
| 2819 | .detach(); |
| 2820 | } |
| 2821 | |
| 2822 | fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) { |
| 2823 | let (Some(conversation_id), Some(runs)) = |
| 2824 | (self.conversation_id(), crate::agents::runs_handle(cx)) |
| 2825 | else { |
| 2826 | return (Vec::new(), None); |
| 2827 | }; |
| 2828 | if key.starts_with(PENDING_KEY_PREFIX) || key.starts_with(SCHEDULED_KEY_PREFIX) { |
| 2829 | return (Vec::new(), None); |
| 2830 | } |
| 2831 | let settings = runs.read(cx).settings(); |
| 2832 | let entries: Vec<DelegateEntry> = settings |
| 2833 | .actions |
| 2834 | .iter() |
| 2835 | .map(|action| { |
| 2836 | let request = StartRequest { |
| 2837 | action_id: action.id.clone(), |
| 2838 | conversation_id: conversation_id.clone(), |
| 2839 | message_id: key.to_owned(), |
| 2840 | }; |
| 2841 | let agent_name = settings |
| 2842 | .agents |
| 2843 | .iter() |
| 2844 | .find(|agent| agent.id == action.agent_id) |
| 2845 | .map(|agent| agent.name.clone()) |
| 2846 | .unwrap_or_default(); |
| 2847 | DelegateEntry { |
| 2848 | label: action.label.clone(), |
| 2849 | agent_name, |
| 2850 | action: Rc::new(move |_, cx| crate::agents::delegate(request.clone(), cx)), |
| 2851 | } |
| 2852 | }) |
| 2853 | .collect(); |
| 2854 | let manage_agents = (!entries.is_empty()).then(|| { |
| 2855 | Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action |
| 2856 | }); |
| 2857 | (entries, manage_agents) |
| 2858 | } |
| 2859 | |
| 2860 | fn refresh_agent_runs(&mut self, cx: &App) -> (bool, HashSet<String>) { |
| 2861 | let Some(conversation_id) = self.conversation_id() else { |
| 2862 | return (false, HashSet::new()); |
| 2863 | }; |
| 2864 | let Some(runs) = crate::agents::runs_handle(cx) else { |
| 2865 | return (false, HashSet::new()); |
| 2866 | }; |
| 2867 | let mut snapshot: HashMap<String, AgentRun> = HashMap::new(); |
| 2868 | for run in runs.read(cx).for_conversation(&conversation_id) { |
| 2869 | snapshot.insert(run.message_id.clone(), run.clone()); |
| 2870 | } |
| 2871 | let layouts: HashMap<String, (usize, bool)> = snapshot |
| 2872 | .iter() |
| 2873 | .map(|(key, run)| (key.clone(), run.layout_key())) |
| 2874 | .collect(); |
| 2875 | let layout_changed: HashSet<String> = layouts |
| 2876 | .iter() |
| 2877 | .filter(|(key, layout)| self.agent_layouts.get(*key) != Some(layout)) |
| 2878 | .map(|(key, _)| key.clone()) |
| 2879 | .chain( |
| 2880 | self.agent_layouts |
| 2881 | .keys() |
| 2882 | .filter(|key| !layouts.contains_key(*key)) |
| 2883 | .cloned(), |
| 2884 | ) |
| 2885 | .collect(); |
| 2886 | self.agent_layouts = layouts; |
| 2887 | let snapshot_changed = *self.agent_runs.borrow() != snapshot; |
| 2888 | *self.agent_runs.borrow_mut() = snapshot; |
| 2889 | (snapshot_changed, layout_changed) |
| 2890 | } |
| 2891 | |
| 2892 | fn sync_agent_chips(&mut self, cx: &mut Context<Self>) { |
| 2893 | let (snapshot_changed, changed) = self.refresh_agent_runs(cx); |
| 2894 | let any_running = self.agent_runs.borrow().values().any(AgentRun::is_running); |
| 2895 | self.remeasure_rows_of(&changed, cx); |
| 2896 | if snapshot_changed || any_running { |
| 2897 | cx.notify(); |
| 2898 | } |
| 2899 | } |
| 2900 | |
| 2901 | fn remeasure_rows_of(&mut self, keys: &HashSet<String>, cx: &mut Context<Self>) { |
| 2902 | if keys.is_empty() { |
| 2903 | return; |
| 2904 | } |
| 2905 | let indices: Vec<usize> = self |
| 2906 | .rows |
| 2907 | .borrow() |
| 2908 | .iter() |
| 2909 | .enumerate() |
| 2910 | .filter(|(_, row)| row.messages().any(|message| keys.contains(&message.key))) |
| 2911 | .map(|(index, _)| index) |
| 2912 | .collect(); |
| 2913 | self.scroller.update(cx, |scroller, cx| { |
| 2914 | for index in indices { |
| 2915 | scroller.remeasure_items(index..index + 1, cx); |
| 2916 | } |
| 2917 | }); |
| 2918 | } |
| 2919 | |
| 2920 | fn message_menu( |
| 2921 | &self, |
| 2922 | message: &MessageRow, |
| 2923 | mine: HashSet<String>, |
| 2924 | refresh: Option<(usize, ExecuteAction)>, |
| 2925 | view: WeakEntity<Self>, |
| 2926 | cx: &App, |
| 2927 | ) -> MessageMenu { |
| 2928 | let (key, own) = (message.key.as_str(), message.own); |
| 2929 | let translate_label = match message.translation { |
| 2930 | Some(TranslationLine::Translated { |
| 2931 | showing_original: false, |
| 2932 | .. |
| 2933 | }) => "See original", |
| 2934 | Some(TranslationLine::Translated { .. }) => "See translation", |
| 2935 | _ => "Translate", |
| 2936 | }; |
| 2937 | let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action { |
| 2938 | let (view, key) = (view.clone(), key.to_owned()); |
| 2939 | Rc::new(move |window, cx| { |
| 2940 | view.update(cx, |this, cx| run(this, &key, window, cx)).ok(); |
| 2941 | }) |
| 2942 | }; |
| 2943 | let react: PickHandler = { |
| 2944 | let (view, key) = (view.clone(), key.to_owned()); |
| 2945 | Rc::new(move |glyph, _, cx| { |
| 2946 | view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx)) |
| 2947 | .ok(); |
| 2948 | }) |
| 2949 | }; |
| 2950 | let hover = { |
| 2951 | let (view, key) = (view.clone(), key.to_owned()); |
| 2952 | Rc::new(move |hovered: bool, cx: &mut App| { |
| 2953 | view.update(cx, |this, cx| { |
| 2954 | this.set_hover(HoverSlot::Toolbar, &key, hovered, cx) |
| 2955 | }) |
| 2956 | .ok(); |
| 2957 | }) |
| 2958 | }; |
| 2959 | let pin = { |
| 2960 | let (view, key) = (view.clone(), key.to_owned()); |
| 2961 | Rc::new(move |open: bool, _: &mut Window, cx: &mut App| { |
| 2962 | view.update(cx, |this, cx| this.set_pinned(&key, open, cx)) |
| 2963 | .ok(); |
| 2964 | }) |
| 2965 | }; |
| 2966 | let refresh_card = refresh.map(|(card_index, refresh_action)| { |
| 2967 | let (view, key) = (view.clone(), key.to_owned()); |
| 2968 | Rc::new(move |_: &mut Window, cx: &mut App| { |
| 2969 | view.update(cx, |this, cx| { |
| 2970 | this.refresh_card(&key, card_index, refresh_action.clone(), cx) |
| 2971 | }) |
| 2972 | .ok(); |
| 2973 | }) as Action |
| 2974 | }); |
| 2975 | let chat_id = self.chat_id(); |
| 2976 | let state = self.app.read(cx); |
| 2977 | let saved = self |
| 2978 | .conversation_id() |
| 2979 | .is_some_and(|conversation_id| state.is_saved(&conversation_id, key)); |
| 2980 | let pinned = chat_id |
| 2981 | .as_deref() |
| 2982 | .is_some_and(|chat_id| state.is_pinned(chat_id, key)); |
| 2983 | let in_chat = chat_id.is_some(); |
| 2984 | let (delegate, manage_agents) = self.delegate_entries(key, cx); |
| 2985 | MessageMenu { |
| 2986 | key: key.to_owned(), |
| 2987 | react, |
| 2988 | reply: Some(action(|this, key, window, cx| { |
| 2989 | this.begin_reply(key, window, cx) |
| 2990 | })), |
| 2991 | forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))), |
| 2992 | copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))), |
| 2993 | copy: action(|this, key, _, cx| this.copy_text(key, cx)), |
| 2994 | translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))), |
| 2995 | translate_label, |
| 2996 | save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))), |
| 2997 | saved, |
| 2998 | toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))), |
| 2999 | pinned, |
| 3000 | edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))), |
| 3001 | delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))), |
| 3002 | mark_unread: (in_chat && !own) |
| 3003 | .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))), |
| 3004 | refresh_card, |
| 3005 | delegate, |
| 3006 | manage_agents, |
| 3007 | pin, |
| 3008 | hover, |
| 3009 | picker: self.picker.clone(), |
| 3010 | quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT), |
| 3011 | mine, |
| 3012 | done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)), |
| 3013 | } |
| 3014 | } |
| 3015 | |
| 3016 | fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 3017 | let Some(outgoing) = self.pending_outgoing.remove(key) else { |
| 3018 | return; |
| 3019 | }; |
| 3020 | let reply_root = self |
| 3021 | .pending |
| 3022 | .iter() |
| 3023 | .find(|row| row.key == key) |
| 3024 | .and_then(|row| row.reply_root.clone()); |
| 3025 | self.pending.retain(|row| row.key != key); |
| 3026 | if self.draft_active { |
| 3027 | self.send_new_chat(outgoing, window, cx); |
| 3028 | } else { |
| 3029 | self.send_as(key.to_owned(), outgoing, reply_root, window, cx); |
| 3030 | } |
| 3031 | } |
| 3032 | |
| 3033 | fn finish_send( |
| 3034 | &mut self, |
| 3035 | key: &str, |
| 3036 | result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>, |
| 3037 | cx: &mut Context<Self>, |
| 3038 | ) { |
| 3039 | let failure = match result { |
| 3040 | Ok(Ok(())) => None, |
| 3041 | Ok(Err(error)) => Some(short_error(&error)), |
| 3042 | Err(error) => Some(short_error(&error)), |
| 3043 | }; |
| 3044 | let store = self.app.read(cx).store.clone(); |
| 3045 | match failure { |
| 3046 | None => { |
| 3047 | store.delete_outbox(key).ok(); |
| 3048 | self.pending.retain(|row| row.key != key); |
| 3049 | self.pending_outgoing.remove(key); |
| 3050 | } |
| 3051 | Some(error) => { |
| 3052 | store.mark_outbox_failed(key, &error).ok(); |
| 3053 | if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) { |
| 3054 | row.delivery = Delivery::Failed(error.clone()); |
| 3055 | self.notice = Some(format!("Not sent: {error}")); |
| 3056 | } |
| 3057 | } |
| 3058 | } |
| 3059 | self.app |
| 3060 | .update(cx, |state, cx| state.refresh_local_previews(cx)); |
| 3061 | self.rebuild(false, cx); |
| 3062 | } |
| 3063 | |
| 3064 | fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement { |
| 3065 | let target = match self.current.as_ref().map(|current| ¤t.selection) { |
| 3066 | Some(Selection::Chat(_)) => DropTarget::Chat, |
| 3067 | Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library, |
| 3068 | Some(Selection::Channel(_)) => DropTarget::Channel, |
| 3069 | None => DropTarget::NewChat, |
| 3070 | }; |
| 3071 | let title = self |
| 3072 | .current |
| 3073 | .as_ref() |
| 3074 | .map(|current| current.title.as_str()) |
| 3075 | .unwrap_or_default(); |
| 3076 | let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1)); |
| 3077 | let composer = self.composer.clone(); |
| 3078 | div() |
| 3079 | .id("drop-overlay") |
| 3080 | .absolute() |
| 3081 | .top_0() |
| 3082 | .left_0() |
| 3083 | .size_full() |
| 3084 | .opacity(0.) |
| 3085 | .bg(theme::drop_background()) |
| 3086 | .drag_over::<ExternalPaths>(move |style, _, _, cx| { |
| 3087 | if composer.read(cx).is_editing() { |
| 3088 | style |
| 3089 | } else { |
| 3090 | style.opacity(1.) |
| 3091 | } |
| 3092 | }) |
| 3093 | .on_drag_move( |
| 3094 | cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| { |
| 3095 | let count = event.drag(cx).paths().len(); |
| 3096 | if this.drag_file_count != count { |
| 3097 | this.drag_file_count = count; |
| 3098 | cx.notify(); |
| 3099 | } |
| 3100 | }), |
| 3101 | ) |
| 3102 | .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| { |
| 3103 | let paths = dropped.paths().to_vec(); |
| 3104 | if this.shared_active() { |
| 3105 | this.upload_paths(paths, cx); |
| 3106 | return; |
| 3107 | } |
| 3108 | this.composer |
| 3109 | .update(cx, |composer, cx| composer.add_paths(paths, window, cx)); |
| 3110 | })) |
| 3111 | .child( |
| 3112 | div() |
| 3113 | .absolute() |
| 3114 | .inset(px(12.)) |
| 3115 | .rounded(px(12.)) |
| 3116 | .border_2() |
| 3117 | .border_color(theme::accent()) |
| 3118 | .flex() |
| 3119 | .items_center() |
| 3120 | .justify_center() |
| 3121 | .child( |
| 3122 | v_flex() |
| 3123 | .items_center() |
| 3124 | .gap(px(6.)) |
| 3125 | .px(px(24.)) |
| 3126 | .py(px(16.)) |
| 3127 | .rounded(px(12.)) |
| 3128 | .bg(black().opacity(0.55)) |
| 3129 | .child(symbol("upload", 28., theme::accent_text())) |
| 3130 | .child( |
| 3131 | div() |
| 3132 | .text_size(px(15.)) |
| 3133 | .font_weight(FontWeight::SEMIBOLD) |
| 3134 | .text_color(theme::text_strong()) |
| 3135 | .child(heading), |
| 3136 | ) |
| 3137 | .child( |
| 3138 | div() |
| 3139 | .text_size(px(12.)) |
| 3140 | .text_color(theme::text_muted()) |
| 3141 | .child(detail), |
| 3142 | ), |
| 3143 | ), |
| 3144 | ) |
| 3145 | } |
| 3146 | |
| 3147 | fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> { |
| 3148 | let message = self.draft_error.clone()?; |
| 3149 | let failed_key = self |
| 3150 | .pending |
| 3151 | .iter() |
| 3152 | .find(|row| matches!(row.delivery, Delivery::Failed(_))) |
| 3153 | .map(|row| row.key.clone())?; |
| 3154 | Some( |
| 3155 | h_flex() |
| 3156 | .w_full() |
| 3157 | .flex_none() |
| 3158 | .px(px(20.)) |
| 3159 | .py(px(4.)) |
| 3160 | .gap(px(8.)) |
| 3161 | .items_center() |
| 3162 | .text_size(px(12.)) |
| 3163 | .text_color(theme::red_soft()) |
| 3164 | .child(message) |
| 3165 | .child( |
| 3166 | Button::new("retry-new-chat") |
| 3167 | .ghost() |
| 3168 | .compact() |
| 3169 | .label("Retry") |
| 3170 | .on_click(cx.listener(move |this, _, window, cx| { |
| 3171 | this.retry(&failed_key, window, cx) |
| 3172 | })), |
| 3173 | ), |
| 3174 | ) |
| 3175 | } |
| 3176 | |
| 3177 | fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement { |
| 3178 | let app = self.app.read(cx); |
| 3179 | let directory = &app.directory; |
| 3180 | let me = directory.me.as_ref(); |
| 3181 | let mut lead: Option<AnyElement> = None; |
| 3182 | let mut subline = String::new(); |
| 3183 | let mut stack: Option<Div> = None; |
| 3184 | match ¤t.selection { |
| 3185 | Selection::Chat(chat_id) => { |
| 3186 | if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) { |
| 3187 | let faces = others(chat, me); |
| 3188 | let face = |(user_id, name): (Option<String>, String)| Face { user_id, name }; |
| 3189 | let first = faces.first().cloned().map(face); |
| 3190 | if is_one_on_one(chat) || faces.len() < 2 { |
| 3191 | let name = first |
| 3192 | .as_ref() |
| 3193 | .map_or(current.title.as_str(), |face| face.name.as_str()); |
| 3194 | let user_id = first.as_ref().and_then(|face| face.user_id.as_deref()); |
| 3195 | let avatar = person_avatar(directory, user_id, name, 36.); |
| 3196 | let presence = user_id.map(|id| directory.presence_of(id)); |
| 3197 | let avatar = match presence { |
| 3198 | Some(kind) => with_presence(avatar, kind, 36., theme::surface()) |
| 3199 | .into_any_element(), |
| 3200 | None => avatar, |
| 3201 | }; |
| 3202 | lead = Some( |
| 3203 | opens_profile(div().id("header-avatar").flex_none(), user_id) |
| 3204 | .child(avatar) |
| 3205 | .into_any_element(), |
| 3206 | ); |
| 3207 | subline = match (user_id, presence) { |
| 3208 | (Some(id), Some(presence)) => { |
| 3209 | directory.status_label(id, presence).to_owned() |
| 3210 | } |
| 3211 | _ => String::new(), |
| 3212 | }; |
| 3213 | } else { |
| 3214 | let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone())); |
| 3215 | lead = Some(spec_avatar(directory, &pair, 36., theme::surface())); |
| 3216 | subline = format!("{} participants", chat.members.len()); |
| 3217 | let shown: Vec<Face> = faces.iter().cloned().map(face).collect(); |
| 3218 | stack = Some(member_stack(directory, &shown, shown.len())); |
| 3219 | } |
| 3220 | } |
| 3221 | } |
| 3222 | Selection::Channel(channel_id) => { |
| 3223 | let team = app.sidebar.teams.iter().find(|entry| { |
| 3224 | entry |
| 3225 | .channels |
| 3226 | .iter() |
| 3227 | .any(|channel| &channel.id == channel_id) |
| 3228 | }); |
| 3229 | let (name, key) = team |
| 3230 | .map_or((current.title.as_str(), current.title.as_str()), |entry| { |
| 3231 | (entry.team.name.as_str(), entry.team.id.as_str()) |
| 3232 | }); |
| 3233 | lead = Some(square_avatar(name, key, 36., 9.).into_any_element()); |
| 3234 | } |
| 3235 | } |
| 3236 | let mut header = h_flex() |
| 3237 | .w_full() |
| 3238 | .h(px(60.)) |
| 3239 | .flex_none() |
| 3240 | .px(px(20.)) |
| 3241 | .gap(px(12.)) |
| 3242 | .items_center(); |
| 3243 | if matches!(current.mode, ViewMode::Thread(_)) { |
| 3244 | header = header.child( |
| 3245 | h_flex() |
| 3246 | .id("back-to-channel") |
| 3247 | .flex_none() |
| 3248 | .gap(px(2.)) |
| 3249 | .pl(px(4.)) |
| 3250 | .pr(px(8.)) |
| 3251 | .py(px(4.)) |
| 3252 | .items_center() |
| 3253 | .rounded(px(6.)) |
| 3254 | .cursor_pointer() |
| 3255 | .text_size(px(13.)) |
| 3256 | .font_weight(FontWeight::SEMIBOLD) |
| 3257 | .text_color(theme::accent_text()) |
| 3258 | .hover(|button| button.bg(theme::row_hover())) |
| 3259 | .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx))) |
| 3260 | .child(icon(IconName::ChevronLeft, 16., theme::accent_text())) |
| 3261 | .child("Back to channel"), |
| 3262 | ); |
| 3263 | } |
| 3264 | let channel_note = match current.mode { |
| 3265 | ViewMode::Flat => None, |
| 3266 | ViewMode::ThreadList => Some("Posts"), |
| 3267 | ViewMode::Thread(_) => Some("Conversation"), |
| 3268 | }; |
| 3269 | if let Some(note) = channel_note { |
| 3270 | subline = note.to_owned(); |
| 3271 | } |
| 3272 | let call_controls = if self.pinned { |
| 3273 | Vec::new() |
| 3274 | } else { |
| 3275 | header_call_controls(&self.app, app, ¤t.selection) |
| 3276 | }; |
| 3277 | let sync = ¤t.sync; |
| 3278 | let loading_window = current.window_request.is_some(); |
| 3279 | if sync.failed { |
| 3280 | subline = "Not up to date".to_owned(); |
| 3281 | } else if loading_window { |
| 3282 | subline = "Loading message ...".to_owned(); |
| 3283 | } else if sync.shown_at.is_some() { |
| 3284 | subline = if sync.slow { |
| 3285 | "Taking longer than usual ..." |
| 3286 | } else if sync.empty_cache { |
| 3287 | "Loading messages ..." |
| 3288 | } else { |
| 3289 | "Updating ..." |
| 3290 | } |
| 3291 | .to_owned(); |
| 3292 | } |
| 3293 | header |
| 3294 | .relative() |
| 3295 | .when(sync.shown_at.is_some() || loading_window, |header| { |
| 3296 | header.child(progress_bar()) |
| 3297 | }) |
| 3298 | .children(lead) |
| 3299 | .child( |
| 3300 | v_flex() |
| 3301 | .flex_1() |
| 3302 | .min_w_0() |
| 3303 | .overflow_hidden() |
| 3304 | .gap(px(1.)) |
| 3305 | .child( |
| 3306 | div() |
| 3307 | .truncate() |
| 3308 | .text_size(px(15.)) |
| 3309 | .font_weight(FontWeight::SEMIBOLD) |
| 3310 | .text_color(theme::text()) |
| 3311 | .child(current.title.clone()), |
| 3312 | ) |
| 3313 | .when(!subline.is_empty(), |column| { |
| 3314 | column.child( |
| 3315 | div() |
| 3316 | .text_size(px(12.)) |
| 3317 | .text_color(theme::text_muted()) |
| 3318 | .child(subline), |
| 3319 | ) |
| 3320 | }), |
| 3321 | ) |
| 3322 | .children(stack) |
| 3323 | .children(call_controls) |
| 3324 | } |
| 3325 | } |
| 3326 | |
| 3327 | impl Render for ConversationView { |
| 3328 | fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 3329 | let background = theme::surface(); |
| 3330 | let mut root = v_flex() |
| 3331 | .when(!self.pinned, |root| { |
| 3332 | root.debug_selector(|| "shell/islands/main".into()) |
| 3333 | }) |
| 3334 | .flex_1() |
| 3335 | .w_full() |
| 3336 | .min_w_0() |
| 3337 | .h_full() |
| 3338 | .rounded(px(10.)) |
| 3339 | .bg(background) |
| 3340 | .track_focus(&self.focus_handle); |
| 3341 | let drafting = self.draft_active; |
| 3342 | if self.current.is_none() && !drafting { |
| 3343 | return root |
| 3344 | .items_center() |
| 3345 | .justify_center() |
| 3346 | .text_color(theme::text_muted()) |
| 3347 | .child("Select a chat or channel") |
| 3348 | .into_any_element(); |
| 3349 | } |
| 3350 | let in_feed = self.in_feed(); |
| 3351 | let detached = self.is_detached(); |
| 3352 | let rows_seen = self.feed_rows_seen.replace(usize::MAX); |
| 3353 | if in_feed && rows_seen != usize::MAX { |
| 3354 | self.feed_at_top = rows_seen == 0; |
| 3355 | } |
| 3356 | let rows = self.rows.clone(); |
| 3357 | let rows_seen = self.feed_rows_seen.clone(); |
| 3358 | let env = RenderEnv { |
| 3359 | view: cx.weak_entity(), |
| 3360 | app: self.app.clone(), |
| 3361 | highlighted: self.highlighted_message.clone(), |
| 3362 | drafting, |
| 3363 | reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()), |
| 3364 | timeline: self.timeline_bounds.clone(), |
| 3365 | agent_runs: self.agent_runs.clone(), |
| 3366 | reaction_proposals: self.reaction_proposals.clone(), |
| 3367 | }; |
| 3368 | let scroller = MessageScroller::new( |
| 3369 | "messages", |
| 3370 | self.scroller.clone(), |
| 3371 | move |index, window, cx| { |
| 3372 | rows_seen.set(rows_seen.get().min(index)); |
| 3373 | let rows = rows.borrow(); |
| 3374 | match rows.get(index) { |
| 3375 | Some(Row::Message(message)) => { |
| 3376 | let actions = env.message_actions(message, window, cx); |
| 3377 | let state = env.app.read(cx); |
| 3378 | render_message_row(message, index, actions, &state.directory, cx) |
| 3379 | } |
| 3380 | Some(Row::Post(post)) => { |
| 3381 | let actions = env.post_actions(post, window, cx); |
| 3382 | let state = env.app.read(cx); |
| 3383 | render_post(post, index, actions, &state.directory, cx) |
| 3384 | } |
| 3385 | Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index), |
| 3386 | Some(Row::LoadOlder) => { |
| 3387 | let view = env.view.clone(); |
| 3388 | cx.defer(move |cx| { |
| 3389 | view.update(cx, |this, cx| this.request_older(cx)).ok(); |
| 3390 | }); |
| 3391 | h_flex() |
| 3392 | .w_full() |
| 3393 | .py_2() |
| 3394 | .gap(px(6.)) |
| 3395 | .justify_center() |
| 3396 | .text_size(px(12.)) |
| 3397 | .text_color(theme::text_muted()) |
| 3398 | .child(icon(IconName::Loader, 12., theme::text_muted())) |
| 3399 | .child("Loading older messages") |
| 3400 | .into_any_element() |
| 3401 | } |
| 3402 | Some(Row::LoadNewer) => { |
| 3403 | let view = env.view.clone(); |
| 3404 | cx.defer(move |cx| { |
| 3405 | view.update(cx, |this, cx| { |
| 3406 | this.request_window_page(WindowDirection::Forward, cx) |
| 3407 | }) |
| 3408 | .ok(); |
| 3409 | }); |
| 3410 | h_flex() |
| 3411 | .w_full() |
| 3412 | .py_2() |
| 3413 | .gap(px(6.)) |
| 3414 | .justify_center() |
| 3415 | .text_size(px(12.)) |
| 3416 | .text_color(theme::text_muted()) |
| 3417 | .child(icon(IconName::Loader, 12., theme::text_muted())) |
| 3418 | .child("Loading newer messages") |
| 3419 | .into_any_element() |
| 3420 | } |
| 3421 | Some(Row::Start(start)) => { |
| 3422 | let state = env.app.read(cx); |
| 3423 | v_flex() |
| 3424 | .w_full() |
| 3425 | .items_center() |
| 3426 | .gap(px(8.)) |
| 3427 | .pt(px(32.)) |
| 3428 | .pb(px(16.)) |
| 3429 | .child(person_avatar( |
| 3430 | &state.directory, |
| 3431 | start.user_id.as_deref(), |
| 3432 | &start.title, |
| 3433 | 56., |
| 3434 | )) |
| 3435 | .child( |
| 3436 | div() |
| 3437 | .text_size(px(16.)) |
| 3438 | .font_weight(FontWeight::SEMIBOLD) |
| 3439 | .text_color(theme::text()) |
| 3440 | .child(start.title.clone()), |
| 3441 | ) |
| 3442 | .child( |
| 3443 | div() |
| 3444 | .text_size(px(12.)) |
| 3445 | .text_color(theme::text_muted()) |
| 3446 | .child("This is the beginning of the conversation"), |
| 3447 | ) |
| 3448 | .into_any_element() |
| 3449 | } |
| 3450 | None => div().into_any_element(), |
| 3451 | } |
| 3452 | }, |
| 3453 | ) |
| 3454 | .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.))) |
| 3455 | .jump_button(!in_feed) |
| 3456 | .force_jump_button(detached) |
| 3457 | .when(detached, |scroller| { |
| 3458 | let view = cx.weak_entity(); |
| 3459 | scroller.on_jump(move |_, cx| { |
| 3460 | view.update(cx, |this, cx| this.leave_detached(cx)).ok(); |
| 3461 | }) |
| 3462 | }) |
| 3463 | .with_bottom_fade(background); |
| 3464 | |
| 3465 | root = match self.current.as_ref().filter(|_| !drafting) { |
| 3466 | Some(current) => root.child(self.render_header(current, cx)), |
| 3467 | None => root.child(self.draft.clone()), |
| 3468 | }; |
| 3469 | let tab_bar = self |
| 3470 | .render_tab_bar(window, cx) |
| 3471 | .or_else(|| self.render_meeting_tab_bar(cx)); |
| 3472 | root = root.children(tab_bar.filter(|_| !drafting)); |
| 3473 | root = root.children(self.render_pin_banner(cx).filter(|_| !drafting)); |
| 3474 | let sync_failed = self |
| 3475 | .current |
| 3476 | .as_ref() |
| 3477 | .is_some_and(|current| current.sync.failed); |
| 3478 | if let Some(notice) = &self.notice { |
| 3479 | root = root.child( |
| 3480 | h_flex() |
| 3481 | .px(px(20.)) |
| 3482 | .py_1() |
| 3483 | .gap(px(8.)) |
| 3484 | .items_center() |
| 3485 | .text_xs() |
| 3486 | .bg(theme::amber().opacity(0.15)) |
| 3487 | .text_color(theme::amber()) |
| 3488 | .child(div().flex_1().min_w_0().child(notice.clone())) |
| 3489 | .when(sync_failed, |bar| { |
| 3490 | bar.child( |
| 3491 | Button::new("retry-fetch") |
| 3492 | .ghost() |
| 3493 | .compact() |
| 3494 | .label("Retry") |
| 3495 | .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))), |
| 3496 | ) |
| 3497 | }), |
| 3498 | ); |
| 3499 | } |
| 3500 | let recap_active = self.recap_active(); |
| 3501 | let empty_channel = in_feed && self.rows.borrow().is_empty(); |
| 3502 | let new_post = self.render_new_post(window, cx); |
| 3503 | let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() { |
| 3504 | let draft = self.draft.read(cx); |
| 3505 | let group_name = draft.group_name(cx); |
| 3506 | draft.render_empty(&self.app.read(cx).directory, &group_name) |
| 3507 | } else if self.shared_active() { |
| 3508 | self.render_shared(cx) |
| 3509 | } else if self.recap_active() { |
| 3510 | self.render_recap(cx) |
| 3511 | } else if empty_channel { |
| 3512 | div() |
| 3513 | .size_full() |
| 3514 | .flex() |
| 3515 | .items_center() |
| 3516 | .justify_center() |
| 3517 | .text_size(px(13.)) |
| 3518 | .text_color(theme::text_muted()) |
| 3519 | .child("No posts in this channel yet") |
| 3520 | .into_any_element() |
| 3521 | } else { |
| 3522 | scroller.into_any_element() |
| 3523 | }; |
| 3524 | root.child( |
| 3525 | v_flex() |
| 3526 | .relative() |
| 3527 | .flex_1() |
| 3528 | .min_h_0() |
| 3529 | .children(new_post) |
| 3530 | .child( |
| 3531 | div() |
| 3532 | .relative() |
| 3533 | .flex_1() |
| 3534 | .min_h_0() |
| 3535 | .child(record_bounds(&self.timeline_bounds)) |
| 3536 | .on_scroll_wheel( |
| 3537 | cx.listener(|this, _, _, cx| this.close_reaction_details(cx)), |
| 3538 | ) |
| 3539 | .child(body), |
| 3540 | ) |
| 3541 | .children(self.render_draft_error(cx)) |
| 3542 | .when(!in_feed && !recap_active, |column| { |
| 3543 | column |
| 3544 | .child(self.render_typing_line(cx)) |
| 3545 | .children(self.render_proposal_card(cx)) |
| 3546 | .child(self.composer.clone()) |
| 3547 | }) |
| 3548 | .child(self.render_drop_overlay(cx)), |
| 3549 | ) |
| 3550 | .capture_action(cx.listener(|this, _: &Escape, _, cx| { |
| 3551 | if this.reaction_details.is_some() { |
| 3552 | this.close_reaction_details(cx); |
| 3553 | cx.stop_propagation(); |
| 3554 | } |
| 3555 | })) |
| 3556 | .on_action(cx.listener(|this, _: &Escape, window, cx| { |
| 3557 | if this.draft_active { |
| 3558 | if this.draft.read(cx).has_focus(window, cx) { |
| 3559 | this.draft.update(cx, |draft, cx| draft.escape(cx)); |
| 3560 | } |
| 3561 | } else if !this.on_escape(window, cx) { |
| 3562 | cx.propagate(); |
| 3563 | } |
| 3564 | })) |
| 3565 | .into_any_element() |
| 3566 | } |
| 3567 | } |
| 3568 | |
| 3569 | fn typing_dots() -> impl IntoElement { |
| 3570 | h_flex() |
| 3571 | .gap(px(3.)) |
| 3572 | .flex_none() |
| 3573 | .children((0..TYPING_DOT_COUNT).map(|index| { |
| 3574 | let phase_offset = index as f32 / TYPING_DOT_COUNT as f32; |
| 3575 | div() |
| 3576 | .size(px(TYPING_DOT_SIZE)) |
| 3577 | .rounded_full() |
| 3578 | .bg(theme::text_muted()) |
| 3579 | .with_animation( |
| 3580 | ElementId::NamedInteger("typing-dot".into(), index as u64), |
| 3581 | Animation::new(TYPING_PULSE_PERIOD).repeat(), |
| 3582 | move |dot, delta| { |
| 3583 | let wave = 1. - ((delta - phase_offset).rem_euclid(1.) * 2. - 1.).abs(); |
| 3584 | dot.opacity(0.3 + 0.7 * wave) |
| 3585 | }, |
| 3586 | ) |
| 3587 | })) |
| 3588 | } |
| 3589 | |
| 3590 | fn progress_bar() -> impl IntoElement { |
| 3591 | div() |
| 3592 | .absolute() |
| 3593 | .left_0() |
| 3594 | .right_0() |
| 3595 | .bottom(px(-1.)) |
| 3596 | .h(px(2.)) |
| 3597 | .overflow_hidden() |
| 3598 | .bg(theme::border()) |
| 3599 | .child( |
| 3600 | div() |
| 3601 | .absolute() |
| 3602 | .top_0() |
| 3603 | .h_full() |
| 3604 | .w(relative(PROGRESS_BAR_WIDTH)) |
| 3605 | .bg(theme::own_read()) |
| 3606 | .with_animation( |
| 3607 | "sync-progress", |
| 3608 | Animation::new(PROGRESS_BAR_PERIOD).repeat(), |
| 3609 | |bar, delta| { |
| 3610 | let travel = 1. + PROGRESS_BAR_WIDTH; |
| 3611 | // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0). |
| 3612 | bar.left(relative( |
| 3613 | (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH, |
| 3614 | )) |
| 3615 | }, |
| 3616 | ), |
| 3617 | ) |
| 3618 | } |
| 3619 | |
| 3620 | #[cfg(test)] |
| 3621 | mod tests { |
| 3622 | use std::sync::Arc; |
| 3623 | |
| 3624 | use super::{DropTarget, drop_overlay_text}; |
| 3625 | |
| 3626 | use gpui_kit::test::TestWindowExt as _; |
| 3627 | use gpui_kit::{AppContext as _, TestAppContext, WindowOptions}; |
| 3628 | use store::Store; |
| 3629 | |
| 3630 | use super::ConversationView; |
| 3631 | use crate::app_state::{AppState, Mode, Selection}; |
| 3632 | |
| 3633 | #[test] |
| 3634 | fn chat_overlay_names_the_chat_and_the_onedrive() { |
| 3635 | assert_eq!( |
| 3636 | drop_overlay_text("Mara Lin", DropTarget::Chat, 3), |
| 3637 | ( |
| 3638 | "Drop to attach to Mara Lin".to_owned(), |
| 3639 | "3 files. Images go into the message, other files to your OneDrive.".to_owned() |
| 3640 | ) |
| 3641 | ); |
| 3642 | } |
| 3643 | |
| 3644 | #[test] |
| 3645 | fn channel_overlay_points_to_the_channel_files() { |
| 3646 | let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1); |
| 3647 | assert_eq!( |
| 3648 | detail, |
| 3649 | "1 file. Images go into the message, other files to the channel's Files." |
| 3650 | ); |
| 3651 | } |
| 3652 | |
| 3653 | #[test] |
| 3654 | fn new_chat_overlay_says_files_wait_for_the_chat() { |
| 3655 | let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2); |
| 3656 | assert_eq!(heading, "Drop to attach to the new chat"); |
| 3657 | assert_eq!( |
| 3658 | detail, |
| 3659 | "2 files. Images go into the message. Files can be added once the chat exists." |
| 3660 | ); |
| 3661 | } |
| 3662 | |
| 3663 | #[gpui_kit::test] |
| 3664 | fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) { |
| 3665 | cx.update(gpui_kit::init); |
| 3666 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 3667 | crate::demo::seed(&store); |
| 3668 | let mode = Mode { |
| 3669 | demo: true, |
| 3670 | read_only: false, |
| 3671 | demo_sync: None, |
| 3672 | }; |
| 3673 | let (handle, app, _view) = cx.update(|cx| { |
| 3674 | let app = cx.new(|_| { |
| 3675 | let mut state = AppState::new(store, mode); |
| 3676 | crate::demo::seed_directory(&mut state); |
| 3677 | state.selection = Some(crate::demo::first_selection()); |
| 3678 | state |
| 3679 | }); |
| 3680 | let shared = app.clone(); |
| 3681 | let (handle, view) = |
| 3682 | gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { |
| 3683 | cx.new(|cx| ConversationView::new(shared, window, cx)) |
| 3684 | }) |
| 3685 | .unwrap(); |
| 3686 | (handle, app, view) |
| 3687 | }); |
| 3688 | cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx))); |
| 3689 | let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| { |
| 3690 | cx.update_window(handle, move |_, window, cx| { |
| 3691 | run(window, cx); |
| 3692 | window.render_frame(cx); |
| 3693 | }) |
| 3694 | .unwrap(); |
| 3695 | }; |
| 3696 | step(cx, |window, cx| window.render_frame(cx)); |
| 3697 | step(cx, |window, cx| window.input("lea", cx)); |
| 3698 | step(cx, |window, cx| window.press("enter", cx)); |
| 3699 | step(cx, |window, cx| window.press("enter", cx)); |
| 3700 | step(cx, |window, cx| window.input("Hello Lea", cx)); |
| 3701 | step(cx, |window, cx| window.press("enter", cx)); |
| 3702 | cx.update(|cx| { |
| 3703 | let state = app.read(cx); |
| 3704 | assert!(!state.new_chat); |
| 3705 | assert_eq!( |
| 3706 | state.selection, |
| 3707 | Some(Selection::Chat("demo-chat-new-1".to_owned())) |
| 3708 | ); |
| 3709 | let chat = state |
| 3710 | .sidebar |
| 3711 | .chats |
| 3712 | .iter() |
| 3713 | .find(|chat| chat.id == "demo-chat-new-1") |
| 3714 | .expect("new chat in the sidebar"); |
| 3715 | assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea")); |
| 3716 | }); |
| 3717 | } |
| 3718 | |
| 3719 | #[gpui_kit::test] |
| 3720 | fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) { |
| 3721 | cx.update(gpui_kit::init); |
| 3722 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 3723 | crate::demo::seed(&store); |
| 3724 | let mode = Mode { |
| 3725 | demo: true, |
| 3726 | read_only: false, |
| 3727 | demo_sync: None, |
| 3728 | }; |
| 3729 | let (handle, app) = cx.update(|cx| { |
| 3730 | let app = cx.new(|_| { |
| 3731 | let mut state = AppState::new(store, mode); |
| 3732 | crate::demo::seed_directory(&mut state); |
| 3733 | state.selection = Some(crate::demo::first_selection()); |
| 3734 | state |
| 3735 | }); |
| 3736 | let shared = app.clone(); |
| 3737 | let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { |
| 3738 | cx.new(|cx| ConversationView::new(shared, window, cx)) |
| 3739 | }) |
| 3740 | .unwrap(); |
| 3741 | (handle, app) |
| 3742 | }); |
| 3743 | cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx))); |
| 3744 | cx.update_window(handle, |_, window, cx| { |
| 3745 | window.render_frame(cx); |
| 3746 | window.press("escape", cx); |
| 3747 | window.render_frame(cx); |
| 3748 | window.press("escape", cx); |
| 3749 | window.render_frame(cx); |
| 3750 | }) |
| 3751 | .unwrap(); |
| 3752 | cx.update(|cx| { |
| 3753 | let state = app.read(cx); |
| 3754 | assert!(!state.new_chat); |
| 3755 | assert_eq!(state.selection, Some(crate::demo::first_selection())); |
| 3756 | }); |
| 3757 | } |
| 3758 | } |