BlueGit

ict rusty-teams

Files

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

conversation.rs

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