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