BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / conversation.rs

conversation.rs

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