BlueGit

ict rusty-teams

Files

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

conversation.rs

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