BlueGit

ict rusty-teams

Files

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

conversation.rs

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