BlueGit

ict rusty-teams

Files

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

conversation.rs

conversation.rs 103.8 KiB Download Raw
1use std::cell::RefCell;
2use std::collections::HashMap;
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,
13 message_scroller::{MessageScroller, MessageScrollerState},
14 v_flex,
15};
16use gpui_kit::prelude::FluentBuilder as _;
17use gpui_kit::*;
18use store::MessageRecord;
19use teams_core::{FileCard, ImageRef, MentionInput};
20
21use super::attachments::FileActions;
22use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
23use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
24use super::message_actions::{Action, MessageMenu};
25use super::message_row::{RowActions, render_message_row, render_skeleton_row};
26use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
27use super::reaction_picker::{PickHandler, ReactionPicker};
28use super::reaction_pills::{ReactionControls, ReactionPopover};
29use super::widgets::{icon, symbol};
30use crate::app_state::{AppEvent, AppState, Selection, selection_title};
31use crate::backend::Engine;
32use crate::data::{is_one_on_one, others};
33use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
34use crate::reaction_model::UNKNOWN_REACTOR;
35use crate::read_state::{ReadTrigger, plan_read};
36use crate::render::Block;
37use crate::render::blocks::Inline;
38use crate::rows::{
39 Delivery, LocalImage, MessageRow, Receipt, Row, RowContext, Series, StartInfo, api_reaction,
40 assign_series, changed_indices, diff_keys, flat_rows, message_text, placeholder_rows,
41 reaction_glyph, reaction_type_for, reply_excerpt, thread_list_rows, thread_rows,
42 trailing_skeleton,
43};
44use crate::runtime;
45use crate::sidebar_model::{AvatarSpec, Face};
46use crate::theme;
47
48const CHAT_OPEN_LIMIT: usize = 60;
49const CHANNEL_OPEN_LIMIT: usize = 300;
50const GROWTH_HEADROOM: usize = 20;
51const META_USER_ID: &str = "me_user_id";
52const PENDING_KEY_PREFIX: &str = "pending-";
53const MAX_NOTICE_CHARS: usize = 140;
54const DEMO_DOWNLOAD_STEPS: u8 = 10;
55const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);
56const JUMP_SCAN_LIMIT: usize = 5000;
57const JUMP_CONTEXT_MESSAGES: usize = 12;
58const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
59const PROGRESS_DELAY: Duration = Duration::from_millis(400);
60const SKELETON_DELAY: Duration = Duration::from_millis(1000);
61const SLOW_AFTER: Duration = Duration::from_secs(8);
62const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
63const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
64const PROGRESS_BAR_WIDTH: f32 = 0.35;
65
66actions!(teams, [ReplyToHovered]);
67
68#[derive(Clone, Copy)]
69enum HoverSlot {
70 Row,
71 Toolbar,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75enum ViewMode {
76 Flat,
77 ThreadList,
78 Thread(String),
79}
80
81#[derive(Default)]
82struct SyncProgress {
83 messages: bool,
84 receipts: bool,
85 empty_cache: bool,
86 newest_cached: Option<DateTime<Utc>>,
87 shown_at: Option<Instant>,
88 trailing_skeleton: bool,
89 slow: bool,
90 failed: bool,
91}
92
93impl SyncProgress {
94 fn running(&self) -> bool {
95 self.messages || self.receipts
96 }
97}
98
99struct Current {
100 selection: Selection,
101 title: String,
102 mode: ViewMode,
103 loaded_limit: usize,
104 loaded_count: usize,
105 has_older: bool,
106 loading_older: bool,
107 older_blocked: bool,
108 fetched: bool,
109 first_unread: Option<String>,
110 sync: SyncProgress,
111}
112
113struct ReactionDetails {
114 message_key: String,
115 anchor_glyph: String,
116 tab: Option<String>,
117}
118
119pub struct ConversationView {
120 app: Entity<AppState>,
121 scroller: Entity<MessageScrollerState>,
122 composer: Entity<Composer>,
123 draft: Entity<NewChatDraft>,
124 draft_active: bool,
125 draft_created: Option<(Vec<String>, String)>,
126 draft_error: Option<String>,
127 rows: Rc<RefCell<Vec<Row>>>,
128 current: Option<Current>,
129 pending: Vec<MessageRow>,
130 pending_counter: usize,
131 pending_outgoing: HashMap<String, Outgoing>,
132 downloads: Downloads,
133 hovered_message: Option<String>,
134 toolbar_hovered: Option<String>,
135 toolbar_pinned: Option<String>,
136 picker: Entity<ReactionPicker>,
137 reaction_details: Option<ReactionDetails>,
138 highlighted_message: Option<String>,
139 notice: Option<String>,
140 drag_file_count: usize,
141 sync_generation: u64,
142 window_active: bool,
143 _subscriptions: Vec<Subscription>,
144}
145
146fn open_limit(selection: &Selection) -> usize {
147 match selection {
148 Selection::Chat(_) => CHAT_OPEN_LIMIT,
149 Selection::Channel(_) => CHANNEL_OPEN_LIMIT,
150 }
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154enum DropTarget {
155 Chat,
156 Channel,
157 NewChat,
158}
159
160fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) {
161 let files = if count == 1 {
162 "1 file".to_owned()
163 } else {
164 format!("{count} files")
165 };
166 match target {
167 DropTarget::Chat => (
168 format!("Drop to attach to {title}"),
169 format!("{files}. Images go into the message, other files to your OneDrive."),
170 ),
171 DropTarget::Channel => (
172 format!("Drop to attach to {title}"),
173 format!("{files}. Images go into the message, other files to the channel's Files."),
174 ),
175 DropTarget::NewChat => (
176 "Drop to attach to the new chat".to_owned(),
177 format!(
178 "{files}. Images go into the message. Files can be added once the chat exists."
179 ),
180 ),
181 }
182}
183
184fn short_error(error: &dyn std::fmt::Display) -> String {
185 error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
186}
187
188enum DownloadEvent {
189 Progress(u8),
190 Finished(Result<PathBuf, String>),
191}
192
193async fn save_file(
194 engine: &Engine,
195 card: &FileCard,
196 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
197) -> Result<PathBuf, String> {
198 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
199 .map_err(|error| short_error(&error))?;
200 engine
201 .download_file(
202 &card.open_url,
203 |bytes| part.write(bytes),
204 |percent| {
205 let _ = events.send(DownloadEvent::Progress(percent));
206 },
207 )
208 .await
209 .map_err(|error| short_error(&error))?;
210 part.finish().map_err(|error| short_error(&error))
211}
212
213impl ConversationView {
214 fn file_actions(
215 &self,
216 message_key: &str,
217 files: &[FileCard],
218 view: WeakEntity<Self>,
219 ) -> FileActions {
220 let conversation_id = self.conversation_id().unwrap_or_default();
221 let (key, cards) = (message_key.to_owned(), files.to_vec());
222 let open_urls: Vec<&str> = files.iter().map(|card| card.open_url.as_str()).collect();
223 FileActions {
224 states: self
225 .downloads
226 .states_for(&conversation_id, message_key, &open_urls),
227 activate: Rc::new(move |index, cx| {
228 let Some(card) = cards.get(index).cloned() else {
229 return;
230 };
231 let key = key.clone();
232 let conversation_id = conversation_id.clone();
233 view.update(cx, |this, cx| {
234 this.activate_file(&conversation_id, &key, card, cx)
235 })
236 .ok();
237 }),
238 }
239 }
240
241 fn activate_file(
242 &mut self,
243 conversation_id: &str,
244 message_key: &str,
245 card: FileCard,
246 cx: &mut Context<Self>,
247 ) {
248 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
249 match downloads::click_action(self.downloads.state(&key)) {
250 ClickAction::Ignore => {}
251 ClickAction::Start => self.start_download(key, card, cx),
252 ClickAction::Reveal(path) => {
253 let folder = path
254 .parent()
255 .map(Path::to_path_buf)
256 .unwrap_or_else(downloads::downloads_directory);
257 match downloads::reveal_target(&path, path.exists(), folder) {
258 RevealTarget::File(path) => downloads::reveal_in_file_manager(&path),
259 RevealTarget::Folder(folder) => cx.open_with_system(&folder),
260 }
261 }
262 }
263 }
264
265 fn start_download(&mut self, key: DownloadKey, card: FileCard, cx: &mut Context<Self>) {
266 if !self.downloads.begin(&key) {
267 return;
268 }
269 cx.notify();
270 let state = self.app.read(cx);
271 let (demo, engine) = (state.mode.demo, state.engine.clone());
272 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<DownloadEvent>();
273 if demo {
274 cx.spawn(async move |this, cx| {
275 for step in 1..=DEMO_DOWNLOAD_STEPS {
276 cx.background_executor().timer(DEMO_DOWNLOAD_STEP).await;
277 let percent = (u32::from(step) * 100 / u32::from(DEMO_DOWNLOAD_STEPS)) as u8;
278 let progressed = this.update(cx, |this, cx| {
279 this.downloads.set_progress(&key, percent);
280 cx.notify();
281 });
282 if progressed.is_err() {
283 return;
284 }
285 }
286 let outcome =
287 downloads::write_demo_file(&card.name).map_err(|error| short_error(&error));
288 this.update(cx, |this, cx| {
289 this.downloads.finish(&key, outcome);
290 cx.notify();
291 })
292 .ok();
293 })
294 .detach();
295 return;
296 }
297 let Some(engine) = engine else {
298 self.downloads.finish(&key, Err("not connected".to_owned()));
299 return;
300 };
301 drop(runtime::spawn(async move {
302 let outcome = save_file(&engine, &card, &sender).await;
303 let _ = sender.send(DownloadEvent::Finished(outcome));
304 }));
305 cx.spawn(async move |this, cx| {
306 while let Some(event) = receiver.recv().await {
307 let updated = this.update(cx, |this, cx| {
308 match event {
309 DownloadEvent::Progress(percent) => {
310 this.downloads.set_progress(&key, percent)
311 }
312 DownloadEvent::Finished(outcome) => this.downloads.finish(&key, outcome),
313 }
314 cx.notify();
315 });
316 if updated.is_err() {
317 break;
318 }
319 }
320 })
321 .detach();
322 }
323
324 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
325 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
326 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
327 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), window, cx));
328 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
329 let subscriptions = vec![
330 cx.subscribe_in(&app, window, Self::on_app_event),
331 cx.subscribe_in(&composer, window, Self::on_composer_event),
332 cx.subscribe_in(&draft, window, Self::on_draft_event),
333 cx.observe_window_activation(window, Self::on_window_activation),
334 cx.observe_keystrokes(|this, event, _, cx| {
335 if event.keystroke.key == "escape" {
336 this.close_reaction_details(cx);
337 }
338 }),
339 ];
340 let mut view = ConversationView {
341 app,
342 scroller,
343 composer,
344 draft,
345 draft_active: false,
346 draft_created: None,
347 draft_error: None,
348 rows: Rc::new(RefCell::new(Vec::new())),
349 current: None,
350 pending: Vec::new(),
351 pending_counter: 0,
352 pending_outgoing: HashMap::new(),
353 downloads: Downloads::default(),
354 hovered_message: None,
355 toolbar_hovered: None,
356 toolbar_pinned: None,
357 picker,
358 reaction_details: None,
359 highlighted_message: None,
360 notice: None,
361 drag_file_count: 0,
362 sync_generation: 0,
363 window_active: window.is_window_active(),
364 _subscriptions: subscriptions,
365 };
366 if let Some(selection) = view.app.read(cx).selection.clone() {
367 view.open(selection, window, cx);
368 }
369 view
370 }
371
372 #[cfg_attr(not(windows), allow(dead_code))]
373 pub fn composer_is_empty(&self, cx: &App) -> bool {
374 self.composer.read(cx).is_empty(cx)
375 }
376
377 #[cfg_attr(not(windows), allow(dead_code))]
378 pub fn send_in_flight(&self) -> bool {
379 self.pending
380 .iter()
381 .any(|row| matches!(row.delivery, Delivery::Sending))
382 }
383
384 fn on_window_activation(&mut self, window: &mut Window, cx: &mut Context<Self>) {
385 self.window_active = window.is_window_active();
386 self.mark_read(ReadTrigger::Activation, cx);
387 }
388
389 fn on_app_event(
390 &mut self,
391 _: &Entity<AppState>,
392 event: &AppEvent,
393 window: &mut Window,
394 cx: &mut Context<Self>,
395 ) {
396 match event {
397 AppEvent::Selection => {
398 self.reaction_details = None;
399 let (new_chat, selection) = {
400 let state = self.app.read(cx);
401 (state.new_chat, state.selection.clone())
402 };
403 if new_chat {
404 self.enter_draft(window, cx);
405 return;
406 }
407 if self.draft_active {
408 let created = self
409 .draft_created
410 .as_ref()
411 .map(|(_, chat_id)| chat_id.clone());
412 if let Some(chat_id) = created {
413 self.composer
414 .update(cx, |composer, _| composer.carry_images_into(chat_id));
415 }
416 self.leave_draft(window, cx);
417 }
418 match selection {
419 Some(selection) => self.open(selection, window, cx),
420 None => {
421 self.current = None;
422 self.rebuild(true, cx);
423 }
424 }
425 }
426 AppEvent::Messages(conversation_id) => {
427 let is_current = self
428 .current
429 .as_ref()
430 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
431 if is_current {
432 self.rebuild(false, cx);
433 self.mark_read(ReadTrigger::Incoming, cx);
434 }
435 }
436 AppEvent::Images(keys) => self.remeasure_images(keys, cx),
437 AppEvent::Jump => self.apply_pending_jump(cx),
438 AppEvent::Status => {
439 if let Some(current) = self.current.as_mut()
440 && current.sync.failed
441 {
442 current.fetched = false;
443 }
444 self.start_fetch(cx)
445 }
446 AppEvent::Directory => {
447 self.refresh_reactor_names(cx);
448 cx.notify();
449 }
450 AppEvent::Sidebar => {
451 self.mark_read(ReadTrigger::Incoming, cx);
452 self.refresh_reactor_names(cx);
453 if self.draft_active {
454 self.on_draft_changed(window, cx);
455 } else if let Some(current) = self.current.as_mut() {
456 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
457 if current.title != title {
458 current.title = title.clone();
459 let conversation_id = current.selection.conversation_id().to_owned();
460 self.composer.update(cx, |composer, cx| {
461 composer.set_conversation(&conversation_id, &title, window, cx)
462 });
463 cx.notify();
464 }
465 }
466 }
467 }
468 }
469
470 fn on_composer_event(
471 &mut self,
472 _: &Entity<Composer>,
473 event: &ComposerEvent,
474 window: &mut Window,
475 cx: &mut Context<Self>,
476 ) {
477 match event {
478 ComposerEvent::Submit(outgoing) if self.draft_active => {
479 self.send_new_chat((**outgoing).clone(), window, cx)
480 }
481 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
482 self.send_edit((**outgoing).clone(), window, cx)
483 }
484 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
485 ComposerEvent::EditLast => self.edit_last_own(window, cx),
486 }
487 }
488
489 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
490 self.toolbar_hovered = None;
491 self.toolbar_pinned = None;
492 let title = selection_title(&self.app.read(cx).sidebar, &selection);
493 let mode = match selection {
494 Selection::Chat(_) => ViewMode::Flat,
495 Selection::Channel(_) => ViewMode::ThreadList,
496 };
497 let first_unread = self.first_unread_id(&selection, cx);
498 self.current = Some(Current {
499 loaded_limit: open_limit(&selection),
500 selection,
501 title,
502 mode,
503 loaded_count: 0,
504 has_older: false,
505 loading_older: false,
506 older_blocked: false,
507 fetched: false,
508 first_unread,
509 sync: SyncProgress::default(),
510 });
511 self.sync_generation += 1;
512 self.clear_pending();
513 self.notice = None;
514 self.rebuild(true, cx);
515 self.start_fetch(cx);
516 self.mark_read(ReadTrigger::Open, cx);
517 let target = self
518 .current
519 .as_ref()
520 .map(|current| {
521 (
522 current.selection.conversation_id().to_owned(),
523 current.title.clone(),
524 )
525 })
526 .unwrap_or_default();
527 self.composer.update(cx, |composer, cx| {
528 composer.set_conversation(&target.0, &target.1, window, cx);
529 });
530 if !self.draft_active {
531 self.composer
532 .update(cx, |composer, cx| composer.focus(window, cx));
533 }
534 self.hovered_message = None;
535 self.apply_pending_jump(cx);
536 }
537
538 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
539 if !self.draft_active {
540 self.draft_active = true;
541 self.current = None;
542 self.clear_pending();
543 self.notice = None;
544 self.draft_created = None;
545 self.draft_error = None;
546 self.toolbar_hovered = None;
547 self.toolbar_pinned = None;
548 self.hovered_message = None;
549 self.sync_generation += 1;
550 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
551 self.composer.update(cx, |composer, cx| {
552 composer.set_conversation("", "", window, cx)
553 });
554 self.on_draft_changed(window, cx);
555 self.rebuild(true, cx);
556 }
557 self.draft
558 .update(cx, |draft, cx| draft.focus_query(window, cx));
559 cx.notify();
560 }
561
562 fn leave_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
563 self.draft_active = false;
564 self.draft_created = None;
565 self.draft_error = None;
566 self.clear_pending();
567 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
568 }
569
570 fn on_draft_event(
571 &mut self,
572 _: &Entity<NewChatDraft>,
573 event: &NewChatEvent,
574 window: &mut Window,
575 cx: &mut Context<Self>,
576 ) {
577 match event {
578 NewChatEvent::Changed => self.on_draft_changed(window, cx),
579 NewChatEvent::FocusComposer => self
580 .composer
581 .update(cx, |composer, cx| composer.focus(window, cx)),
582 NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)),
583 }
584 }
585
586 fn draft_target_chat(&self, cx: &App) -> Option<String> {
587 let chips = self.draft.read(cx).chips();
588 let [chip] = chips else {
589 return None;
590 };
591 let state = self.app.read(cx);
592 existing_one_on_one(
593 &state.sidebar.chats,
594 state.directory.me.as_ref(),
595 &chip.user_id,
596 )
597 .map(|chat| chat.id.clone())
598 }
599
600 fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
601 if !self.draft_active {
602 return;
603 }
604 let target = self.draft_target_chat(cx);
605 if target != self.conversation_id() {
606 match target {
607 Some(chat_id) => {
608 self.composer.update(cx, |composer, _| {
609 composer.carry_images_into(chat_id.clone())
610 });
611 self.open(Selection::Chat(chat_id), window, cx)
612 }
613 None => {
614 self.composer.update(cx, |composer, cx| {
615 composer.carry_images_into(String::new());
616 composer.set_conversation("", "", window, cx);
617 });
618 self.current = None;
619 self.sync_generation += 1;
620 self.rebuild(true, cx);
621 }
622 }
623 }
624 let placeholder = {
625 let draft = self.draft.read(cx);
626 composer_placeholder(draft.chips(), &draft.group_name(cx))
627 };
628 self.composer.update(cx, |composer, cx| {
629 composer.set_placeholder(&placeholder, window, cx)
630 });
631 cx.notify();
632 }
633
634 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
635 let indices: Vec<usize> = self
636 .rows
637 .borrow()
638 .iter()
639 .enumerate()
640 .filter_map(|(index, row)| match row {
641 Row::Message(message)
642 if message.images.iter().any(|image| keys.contains(&image.url)) =>
643 {
644 Some(index)
645 }
646 _ => None,
647 })
648 .collect();
649 self.scroller.update(cx, |scroller, cx| {
650 for index in indices {
651 scroller.remeasure_items(index..index + 1, cx);
652 }
653 });
654 cx.notify();
655 }
656
657 fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {
658 let Some(conversation_id) = self
659 .current
660 .as_ref()
661 .map(|current| current.selection.conversation_id().to_owned())
662 else {
663 return;
664 };
665 let jump = self
666 .app
667 .update(cx, |state, _| match state.pending_jump.take() {
668 Some((target, message_id)) if target == conversation_id => Some(message_id),
669 other => {
670 state.pending_jump = other;
671 None
672 }
673 });
674 if let Some(message_id) = jump {
675 self.jump_to_message(&conversation_id, &message_id, cx);
676 }
677 }
678
679 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
680 let store = self.app.read(cx).store.clone();
681 let Some(record) = store
682 .messages_by_id(conversation_id, &[message_id.to_owned()])
683 .ok()
684 .and_then(|mut found| found.remove(message_id))
685 else {
686 return;
687 };
688 let messages_from_target = store
689 .messages(conversation_id, None, JUMP_SCAN_LIMIT)
690 .ok()
691 .and_then(|all| {
692 all.iter()
693 .position(|candidate| candidate.message_id == message_id)
694 .map(|position| all.len() - position)
695 })
696 .unwrap_or_default();
697 let row_key = record
698 .reply_to_id
699 .clone()
700 .unwrap_or_else(|| message_id.to_owned());
701 let Some(current) = self.current.as_mut() else {
702 return;
703 };
704 current.loaded_limit = current
705 .loaded_limit
706 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
707 current.first_unread = None;
708 if matches!(current.selection, Selection::Channel(_)) {
709 current.mode = match record.reply_to_id {
710 Some(root_id) => ViewMode::Thread(root_id),
711 None => ViewMode::ThreadList,
712 };
713 }
714 let target_key = if matches!(current.mode, ViewMode::Thread(_)) {
715 message_id.to_owned()
716 } else {
717 row_key
718 };
719 self.clear_pending();
720 self.rebuild(true, cx);
721 let index = self
722 .rows
723 .borrow()
724 .iter()
725 .position(|row| row.key() == target_key);
726 if let Some(index) = index {
727 self.scroller
728 .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx));
729 self.highlight(target_key, cx);
730 }
731 }
732
733 fn highlight(&mut self, key: String, cx: &mut Context<Self>) {
734 self.highlighted_message = Some(key.clone());
735 cx.notify();
736 cx.spawn(async move |this, cx| {
737 cx.background_executor().timer(HIGHLIGHT_DURATION).await;
738 this.update(cx, |this, cx| {
739 if this.highlighted_message.as_deref() == Some(key.as_str()) {
740 this.highlighted_message = None;
741 cx.notify();
742 }
743 })
744 .ok();
745 })
746 .detach();
747 }
748
749 pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
750 self.composer
751 .update(cx, |composer, cx| composer.set_text(text, window, cx));
752 self.composer
753 .update(cx, |composer, cx| composer.focus(window, cx));
754 }
755
756 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
757 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
758 Row::Message(message) if !message.own => Some(message.key.clone()),
759 _ => None,
760 });
761 if let Some(key) = key {
762 self.begin_reply(&key, window, cx);
763 }
764 }
765
766 pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) {
767 if let Some(message_id) = self.hovered_message.clone() {
768 self.begin_reply(&message_id, window, cx);
769 }
770 }
771
772 fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
773 let Some(conversation_id) = self
774 .current
775 .as_ref()
776 .map(|current| current.selection.conversation_id().to_owned())
777 else {
778 return;
779 };
780 let store = self.app.read(cx).store.clone();
781 let record = store
782 .messages_by_id(&conversation_id, &[message_id.to_owned()])
783 .ok()
784 .and_then(|mut found| found.remove(message_id))
785 .filter(|record| !record.deleted);
786 let Some(record) = record else {
787 return;
788 };
789 let preview = ReplyPreview {
790 message_id: record.message_id.clone(),
791 author: record
792 .sender_name
793 .clone()
794 .unwrap_or_else(|| "Unknown".to_owned()),
795 excerpt: reply_excerpt(&record),
796 };
797 self.composer.update(cx, |composer, cx| {
798 composer.set_reply(Some(preview), cx);
799 composer.focus(window, cx);
800 });
801 }
802
803 fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> {
804 let Selection::Chat(chat_id) = selection else {
805 return None;
806 };
807 let state = self.app.read(cx);
808 if state.mode.demo {
809 return crate::demo::first_unread(chat_id);
810 }
811 state.engine.as_ref()?.first_unread_message_id(chat_id)
812 }
813
814 fn row_context(&self, cx: &App) -> RowContext {
815 let now = Local::now();
816 let app = self.app.read(cx);
817 let mut names: HashMap<String, String> = HashMap::new();
818 let known_people = app
819 .directory
820 .me
821 .iter()
822 .map(|me| (me.user_id.clone(), me.display_name.clone()))
823 .chain(
824 app.sidebar
825 .chats
826 .iter()
827 .flat_map(|chat| chat.members.iter())
828 .filter_map(|member| {
829 Some((member.user_id.clone()?, member.display_name.clone()))
830 }),
831 );
832 for (user_id, name) in known_people {
833 names.entry(user_id).or_insert(name);
834 }
835 RowContext {
836 offset: now.offset().fix(),
837 today: now.date_naive(),
838 my_user_id: app.store.meta(META_USER_ID).ok().flatten(),
839 names,
840 }
841 }
842
843 fn unknown_reactor_ids(&self) -> Vec<String> {
844 self.rows
845 .borrow()
846 .iter()
847 .filter_map(|row| match row {
848 Row::Message(message) => Some(message),
849 _ => None,
850 })
851 .flat_map(|message| message.reactions.iter())
852 .flat_map(|chip| chip.reactors.iter())
853 .filter(|reactor| reactor.name == UNKNOWN_REACTOR)
854 .filter_map(|reactor| reactor.user_id.clone())
855 .collect()
856 }
857
858 fn refresh_reactor_names(&mut self, cx: &mut Context<Self>) {
859 if self.current.is_none() {
860 return;
861 }
862 let unknown = self.unknown_reactor_ids();
863 if unknown.is_empty() {
864 return;
865 }
866 let names = self.row_context(cx).names;
867 if unknown.iter().any(|user_id| names.contains_key(user_id)) {
868 self.rebuild(false, cx);
869 }
870 }
871
872 fn drop_stale_reaction_details(&mut self) {
873 let Some(details) = self.reaction_details.as_ref() else {
874 return;
875 };
876 let present = self.rows.borrow().iter().any(|row| {
877 matches!(row, Row::Message(message) if message.key == details.message_key
878 && message.reactions.iter().any(|chip| chip.glyph() == details.anchor_glyph))
879 });
880 if !present {
881 self.reaction_details = None;
882 }
883 }
884
885 fn open_reaction_details(&mut self, message_key: &str, glyph: &str, cx: &mut Context<Self>) {
886 let multiple_kinds = self.rows.borrow().iter().any(|row| {
887 matches!(row, Row::Message(message) if message.key == message_key && message.reactions.len() > 1)
888 });
889 self.reaction_details = Some(ReactionDetails {
890 message_key: message_key.to_owned(),
891 anchor_glyph: glyph.to_owned(),
892 tab: multiple_kinds.then(|| glyph.to_owned()),
893 });
894 cx.notify();
895 }
896
897 fn select_reaction_tab(&mut self, tab: Option<String>, cx: &mut Context<Self>) {
898 if let Some(details) = self.reaction_details.as_mut() {
899 details.tab = tab;
900 cx.notify();
901 }
902 }
903
904 fn close_reaction_details(&mut self, cx: &mut Context<Self>) {
905 if self.reaction_details.take().is_some() {
906 cx.notify();
907 }
908 }
909
910 fn reaction_controls(&self, key: &str, view: WeakEntity<Self>) -> ReactionControls {
911 let open = {
912 let (view, key) = (view.clone(), key.to_owned());
913 Rc::new(move |glyph: &str, cx: &mut App| {
914 view.update(cx, |this, cx| this.open_reaction_details(&key, glyph, cx))
915 .ok();
916 })
917 };
918 let select_tab = {
919 let view = view.clone();
920 Rc::new(move |tab: Option<String>, cx: &mut App| {
921 view.update(cx, |this, cx| this.select_reaction_tab(tab, cx))
922 .ok();
923 })
924 };
925 let close = Rc::new(move |cx: &mut App| {
926 view.update(cx, |this, cx| this.close_reaction_details(cx))
927 .ok();
928 });
929 let popover = self
930 .reaction_details
931 .as_ref()
932 .filter(|details| details.message_key == key)
933 .map(|details| ReactionPopover {
934 anchor_glyph: details.anchor_glyph.clone(),
935 tab: details.tab.clone(),
936 });
937 ReactionControls {
938 open,
939 select_tab,
940 close,
941 popover,
942 }
943 }
944
945 fn start_info(&self, cx: &App) -> Option<StartInfo> {
946 let current = self.current.as_ref()?;
947 let app = self.app.read(cx);
948 let user_id = match &current.selection {
949 Selection::Chat(chat_id) => app
950 .sidebar
951 .chats
952 .iter()
953 .find(|chat| &chat.id == chat_id)
954 .filter(|chat| is_one_on_one(chat))
955 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next())
956 .and_then(|(user_id, _)| user_id),
957 Selection::Channel(_) => None,
958 };
959 Some(StartInfo {
960 title: current.title.clone(),
961 user_id,
962 })
963 }
964
965 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
966 let Some(current) = self.current.as_ref() else {
967 let mut rows: Vec<Row> = self
968 .pending
969 .iter()
970 .cloned()
971 .map(|row| Row::Message(Box::new(row)))
972 .collect();
973 assign_series(&mut rows);
974 self.apply_rows(rows, true, cx);
975 return;
976 };
977 let conversation_id = current.selection.conversation_id().to_owned();
978 let limit = if reset {
979 current.loaded_limit
980 } else {
981 current
982 .loaded_limit
983 .max(current.loaded_count + GROWTH_HEADROOM)
984 };
985 let store = self.app.read(cx).store.clone();
986 let records: Vec<MessageRecord> = store
987 .messages(&conversation_id, None, limit)
988 .unwrap_or_default();
989 let sync_has_more = store
990 .sync_state(&conversation_id)
991 .ok()
992 .flatten()
993 .is_none_or(|state| state.has_more);
994 let mut context = self.row_context(cx);
995 for record in &records {
996 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
997 context
998 .names
999 .entry(user_id.clone())
1000 .or_insert_with(|| name.clone());
1001 }
1002 }
1003 let can_load_older = self.app.read(cx).engine.is_some();
1004 let start = self.start_info(cx);
1005 let current = self.current.as_mut().expect("checked above");
1006 let first_unread = current.first_unread.clone();
1007 current.loaded_limit = limit;
1008 current.loaded_count = records.len();
1009 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1010 let placeholders = current.sync.messages
1011 && records.is_empty()
1012 && !matches!(current.mode, ViewMode::Thread(_));
1013 let trailing = current.sync.trailing_skeleton && current.mode == ViewMode::Flat;
1014 let mut rows = match &current.mode {
1015 _ if placeholders => {
1016 current.has_older = false;
1017 placeholder_rows()
1018 }
1019 ViewMode::Flat => {
1020 current.has_older = has_older;
1021 let mut rows = flat_rows(&records, &context, has_older);
1022 if !has_older && let Some(start) = start {
1023 rows.insert(0, Row::Start(start));
1024 }
1025 rows
1026 }
1027 ViewMode::ThreadList => {
1028 current.has_older = has_older;
1029 thread_list_rows(&records, &context, has_older)
1030 }
1031 ViewMode::Thread(root_id) => {
1032 current.has_older = false;
1033 thread_rows(&records, root_id, &context)
1034 }
1035 };
1036 if trailing && !placeholders {
1037 rows.push(trailing_skeleton());
1038 }
1039 rows.extend(
1040 self.pending
1041 .iter()
1042 .cloned()
1043 .map(|row| Row::Message(Box::new(row))),
1044 );
1045 let receipts = self.receipts(&records, cx);
1046 for row in rows.iter_mut() {
1047 if let Row::Message(message) = row
1048 && message.own
1049 {
1050 message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
1051 }
1052 }
1053 if let Some(unread_id) = &first_unread {
1054 for row in rows.iter_mut() {
1055 if let Row::Message(message) = row
1056 && &message.key == unread_id
1057 {
1058 message.new_marker = true;
1059 }
1060 }
1061 }
1062 assign_series(&mut rows);
1063 self.apply_rows(rows, reset, cx);
1064 }
1065
1066 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
1067 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
1068 self.drop_stale_reaction_details();
1069 let new_len = self.rows.borrow().len();
1070 if reset {
1071 let marker_index = self
1072 .rows
1073 .borrow()
1074 .iter()
1075 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
1076 self.scroller.update(cx, |scroller, cx| {
1077 scroller.reset(new_len, cx);
1078 match marker_index {
1079 Some(index) if !scroller.scroll_to_item(index, cx) => {
1080 scroller.scroll_to_end(cx)
1081 }
1082 Some(_) => {}
1083 None => scroller.scroll_to_end(cx),
1084 }
1085 });
1086 cx.notify();
1087 return;
1088 }
1089 let (splice, changed) = {
1090 let new_rows = self.rows.borrow();
1091 let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect();
1092 let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect();
1093 (
1094 diff_keys(&old_keys, &new_keys),
1095 changed_indices(&old_rows, &new_rows),
1096 )
1097 };
1098 self.scroller.update(cx, |scroller, cx| {
1099 if let Some(splice) = splice
1100 && !scroller.splice(splice.range, splice.count, cx)
1101 {
1102 scroller.reset(new_len, cx);
1103 }
1104 for index in changed {
1105 scroller.remeasure_items(index..index + 1, cx);
1106 }
1107 });
1108 cx.notify();
1109 }
1110
1111 fn start_fetch(&mut self, cx: &mut Context<Self>) {
1112 let state = self.app.read(cx);
1113 let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync);
1114 if engine.is_none() && demo_sync.is_none() {
1115 return;
1116 }
1117 let Some(current) = self.current.as_mut() else {
1118 return;
1119 };
1120 if current.fetched {
1121 return;
1122 }
1123 current.fetched = true;
1124 let is_chat = matches!(current.selection, Selection::Chat(_));
1125 let newest_cached = self.rows.borrow().iter().rev().find_map(|row| match row {
1126 Row::Message(message) if !message.key.starts_with(PENDING_KEY_PREFIX) => {
1127 Some(message.created_at)
1128 }
1129 _ => None,
1130 });
1131 let current = self.current.as_mut().expect("checked above");
1132 if current.sync.failed {
1133 self.notice = None;
1134 }
1135 current.sync = SyncProgress {
1136 messages: true,
1137 receipts: is_chat,
1138 empty_cache: newest_cached.is_none(),
1139 newest_cached,
1140 ..SyncProgress::default()
1141 };
1142 self.sync_generation += 1;
1143 let generation = self.sync_generation;
1144 let conversation_id = current.selection.conversation_id().to_owned();
1145 match (engine, demo_sync) {
1146 (Some(engine), _) => {
1147 let receiver =
1148 runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
1149 cx.spawn(async move |this, cx| {
1150 let result = receiver.await;
1151 this.update(cx, |this, cx| this.finish_fetch(generation, result, cx))
1152 .ok();
1153 })
1154 .detach();
1155 }
1156 (None, Some(delay)) => self.simulate_sync(generation, delay, cx),
1157 (None, None) => {}
1158 }
1159 self.schedule_progress(generation, cx);
1160 self.rebuild(false, cx);
1161 self.mark_read(ReadTrigger::Incoming, cx);
1162 self.refresh_receipts(generation, cx);
1163 }
1164
1165 fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) {
1166 cx.spawn(async move |this, cx| {
1167 cx.background_executor().timer(delay).await;
1168 this.update(cx, |this, cx| {
1169 if let Some(sync) = this.sync_of(generation) {
1170 sync.receipts = false;
1171 }
1172 this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx)
1173 })
1174 .ok();
1175 })
1176 .detach();
1177 }
1178
1179 fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> {
1180 if generation != self.sync_generation {
1181 return None;
1182 }
1183 self.current.as_mut().map(|current| &mut current.sync)
1184 }
1185
1186 fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1187 cx.spawn(async move |this, cx| {
1188 let stages = [
1189 (PROGRESS_DELAY, Duration::ZERO),
1190 (SKELETON_DELAY, PROGRESS_DELAY),
1191 (SLOW_AFTER, SKELETON_DELAY),
1192 ];
1193 for (stage, (at, previous)) in stages.into_iter().enumerate() {
1194 cx.background_executor().timer(at - previous).await;
1195 let running = this
1196 .update(cx, |this, cx| this.advance_progress(generation, stage, cx))
1197 .unwrap_or(false);
1198 if !running {
1199 return;
1200 }
1201 }
1202 })
1203 .detach();
1204 }
1205
1206 fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool {
1207 let Some(sync) = self.sync_of(generation) else {
1208 return false;
1209 };
1210 if !sync.running() {
1211 return false;
1212 }
1213 match stage {
1214 0 => sync.shown_at = Some(Instant::now()),
1215 1 if sync.messages => {
1216 sync.trailing_skeleton = true;
1217 self.rebuild(false, cx);
1218 }
1219 1 => {}
1220 _ => sync.slow = true,
1221 }
1222 cx.notify();
1223 true
1224 }
1225
1226 fn finish_fetch(
1227 &mut self,
1228 generation: u64,
1229 result: Result<
1230 teams_core::Result<teams_core::Delta>,
1231 tokio::sync::oneshot::error::RecvError,
1232 >,
1233 cx: &mut Context<Self>,
1234 ) {
1235 let Some(sync) = self.sync_of(generation) else {
1236 return;
1237 };
1238 sync.messages = false;
1239 sync.trailing_skeleton = false;
1240 let newest_cached = sync.newest_cached;
1241 match result {
1242 Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx),
1243 Ok(Err(error)) => self.fail_sync(generation, short_error(&error)),
1244 Err(error) => self.fail_sync(generation, short_error(&error)),
1245 }
1246 self.rebuild(false, cx);
1247 self.settle_progress(generation, cx);
1248 }
1249
1250 fn fail_sync(&mut self, generation: u64, error: String) {
1251 if let Some(sync) = self.sync_of(generation) {
1252 sync.failed = true;
1253 sync.receipts = false;
1254 }
1255 self.notice = Some(format!("Could not refresh: {error}"));
1256 }
1257
1258 fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) {
1259 let Some(newest_cached) = newest_cached else {
1260 return;
1261 };
1262 let Some(my_user_id) = self.row_context(cx).my_user_id else {
1263 return;
1264 };
1265 let store = self.app.read(cx).store.clone();
1266 let Some(current) = self.current.as_mut() else {
1267 return;
1268 };
1269 if current.first_unread.is_some() || current.mode != ViewMode::Flat {
1270 return;
1271 }
1272 let limit = current
1273 .loaded_limit
1274 .max(current.loaded_count + GROWTH_HEADROOM);
1275 current.first_unread = store
1276 .messages(current.selection.conversation_id(), None, limit)
1277 .unwrap_or_default()
1278 .into_iter()
1279 .find(|record| {
1280 record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id)
1281 })
1282 .map(|record| record.message_id);
1283 }
1284
1285 fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1286 let Some(sync) = self.sync_of(generation) else {
1287 return;
1288 };
1289 if sync.running() {
1290 return;
1291 }
1292 let remaining = sync
1293 .shown_at
1294 .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed()))
1295 .unwrap_or_default();
1296 if remaining.is_zero() {
1297 sync.shown_at = None;
1298 sync.slow = false;
1299 cx.notify();
1300 return;
1301 }
1302 cx.spawn(async move |this, cx| {
1303 cx.background_executor().timer(remaining).await;
1304 this.update(cx, |this, cx| {
1305 if let Some(sync) = this.sync_of(generation) {
1306 sync.shown_at = None;
1307 sync.slow = false;
1308 cx.notify();
1309 }
1310 })
1311 .ok();
1312 })
1313 .detach();
1314 }
1315
1316 fn retry_fetch(&mut self, cx: &mut Context<Self>) {
1317 if let Some(current) = self.current.as_mut() {
1318 current.fetched = false;
1319 }
1320 self.start_fetch(cx);
1321 }
1322
1323 fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1324 let state = self.app.read(cx);
1325 let receipts_syncing = self
1326 .current
1327 .as_ref()
1328 .is_some_and(|current| current.sync.receipts);
1329 if state.mode.demo {
1330 let read_ids = crate::demo::read_message_ids(records);
1331 return records
1332 .iter()
1333 .map(|record| {
1334 let receipt = if receipts_syncing {
1335 Receipt::Pending
1336 } else if read_ids.contains(&record.message_id) {
1337 Receipt::Read
1338 } else {
1339 Receipt::Sent
1340 };
1341 (record.message_id.clone(), receipt)
1342 })
1343 .collect();
1344 }
1345 let Some(engine) = state.engine.as_ref() else {
1346 return HashMap::new();
1347 };
1348 let unknown = if receipts_syncing {
1349 Receipt::Pending
1350 } else {
1351 Receipt::Hidden
1352 };
1353 records
1354 .iter()
1355 .map(|record| {
1356 let receipt = match engine.receipt_state_for(record) {
1357 teams_core::ReceiptState::Read { .. } => Receipt::Read,
1358 teams_core::ReceiptState::Sent => Receipt::Sent,
1359 teams_core::ReceiptState::Unknown => unknown,
1360 };
1361 (record.message_id.clone(), receipt)
1362 })
1363 .collect()
1364 }
1365
1366 fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {
1367 let state = self.app.read(cx);
1368 let (Some(engine), Some(Selection::Chat(chat_id))) = (
1369 state.engine.clone(),
1370 self.current.as_ref().map(|c| c.selection.clone()),
1371 ) else {
1372 return;
1373 };
1374 let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await });
1375 cx.spawn(async move |this, cx| {
1376 receiver.await.ok();
1377 this.update(cx, |this, cx| {
1378 let Some(sync) = this.sync_of(generation) else {
1379 return;
1380 };
1381 sync.receipts = false;
1382 this.rebuild(false, cx);
1383 this.settle_progress(generation, cx);
1384 })
1385 .ok();
1386 })
1387 .detach();
1388 }
1389
1390 fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) {
1391 if self.draft_active {
1392 return;
1393 }
1394 let state = self.app.read(cx);
1395 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
1396 else {
1397 return;
1398 };
1399 if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only {
1400 return;
1401 }
1402 let unread = state
1403 .sidebar
1404 .chats
1405 .iter()
1406 .any(|chat| chat.id == chat_id && chat.unread);
1407 let Some(plan) = plan_read(self.window_active, unread, trigger) else {
1408 return;
1409 };
1410 self.app
1411 .update(cx, |state, cx| state.mark_chat_read(&chat_id, cx));
1412 if plan.clear_divider
1413 && let Some(current) = self.current.as_mut()
1414 && current.first_unread.take().is_some()
1415 {
1416 self.rebuild(false, cx);
1417 }
1418 }
1419
1420 fn request_older(&mut self, cx: &mut Context<Self>) {
1421 let Some(engine) = self.app.read(cx).engine.clone() else {
1422 return;
1423 };
1424 let Some(current) = self.current.as_mut() else {
1425 return;
1426 };
1427 if current.loading_older || current.older_blocked || !current.has_older {
1428 return;
1429 }
1430 current.loading_older = true;
1431 let conversation_id = current.selection.conversation_id().to_owned();
1432 let task_id = conversation_id.clone();
1433 let receiver = runtime::spawn(async move { engine.load_older(&task_id).await });
1434 cx.spawn(async move |this, cx| {
1435 let result = receiver.await;
1436 this.update(cx, |this, cx| {
1437 this.finish_older(&conversation_id, result, cx)
1438 })
1439 .ok();
1440 })
1441 .detach();
1442 }
1443
1444 fn finish_older(
1445 &mut self,
1446 conversation_id: &str,
1447 result: Result<
1448 teams_core::Result<Vec<MessageRecord>>,
1449 tokio::sync::oneshot::error::RecvError,
1450 >,
1451 cx: &mut Context<Self>,
1452 ) {
1453 let Some(current) = self.current.as_mut() else {
1454 return;
1455 };
1456 if current.selection.conversation_id() != conversation_id {
1457 return;
1458 }
1459 current.loading_older = false;
1460 match result {
1461 Ok(Ok(records)) if !records.is_empty() => {
1462 current.loaded_limit = current.loaded_count + records.len();
1463 }
1464 Ok(Ok(_)) => current.older_blocked = true,
1465 Ok(Err(error)) => {
1466 current.older_blocked = true;
1467 self.notice = Some(format!(
1468 "Could not load older messages: {}",
1469 short_error(&error)
1470 ));
1471 }
1472 Err(_) => current.older_blocked = true,
1473 }
1474 self.rebuild(false, cx);
1475 }
1476
1477 fn clear_pending(&mut self) {
1478 self.pending.clear();
1479 self.pending_outgoing.clear();
1480 }
1481
1482 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1483 if let Some(current) = self.current.as_mut() {
1484 current.mode = ViewMode::Thread(root_id);
1485 }
1486 self.clear_pending();
1487 self.rebuild(true, cx);
1488 }
1489
1490 fn back_to_threads(&mut self, cx: &mut Context<Self>) {
1491 if let Some(current) = self.current.as_mut() {
1492 current.mode = ViewMode::ThreadList;
1493 }
1494 self.clear_pending();
1495 self.rebuild(true, cx);
1496 }
1497
1498 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1499 let state = self.app.read(cx);
1500 let (mode, engine) = (state.mode, state.engine.clone());
1501 let Some(current) = self.current.as_ref() else {
1502 return;
1503 };
1504 if mode.read_only || mode.demo {
1505 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1506 return;
1507 }
1508 let Some(engine) = engine else {
1509 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1510 return;
1511 };
1512 let conversation_id = current.selection.conversation_id().to_owned();
1513 let view_mode = current.mode.clone();
1514 let key = self.push_pending(&outgoing, cx);
1515 self.notice = None;
1516 self.rebuild(false, cx);
1517 self.scroller
1518 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
1519
1520 let sent = outgoing.clone();
1521 let receiver = runtime::spawn(async move {
1522 let extras = sent.extras();
1523 let Outgoing {
1524 text,
1525 mentions,
1526 reply,
1527 ..
1528 } = &sent;
1529 match (&view_mode, reply) {
1530 (_, Some(reply)) => {
1531 engine
1532 .reply_to_with_extras(
1533 &conversation_id,
1534 &reply.message_id,
1535 text,
1536 mentions,
1537 &extras,
1538 )
1539 .await
1540 }
1541 (ViewMode::Flat, None) => {
1542 engine
1543 .send_message_with_extras(&conversation_id, text, None, mentions, &extras)
1544 .await
1545 }
1546 (ViewMode::ThreadList, None) => {
1547 engine
1548 .post_to_channel_with_extras(
1549 &conversation_id,
1550 text,
1551 None,
1552 mentions,
1553 &extras,
1554 )
1555 .await
1556 }
1557 (ViewMode::Thread(root_id), None) => {
1558 engine
1559 .send_message_with_extras(
1560 &conversation_id,
1561 text,
1562 Some(root_id),
1563 mentions,
1564 &extras,
1565 )
1566 .await
1567 }
1568 }
1569 .map(|_| ())
1570 });
1571 cx.spawn_in(window, async move |this, cx| {
1572 let result = receiver.await;
1573 this.update(cx, |this, cx| this.finish_send(&key, result, cx))
1574 .ok();
1575 })
1576 .detach();
1577 }
1578
1579 fn restore_unsent(
1580 &mut self,
1581 message: &str,
1582 outgoing: &Outgoing,
1583 window: &mut Window,
1584 cx: &mut Context<Self>,
1585 ) {
1586 self.notice = Some(message.to_owned());
1587 self.composer
1588 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
1589 cx.notify();
1590 }
1591
1592 fn push_pending(&mut self, outgoing: &Outgoing, cx: &App) -> String {
1593 self.pending_counter += 1;
1594 let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
1595 let my_user_id = self.row_context(cx).my_user_id;
1596 self.pending_outgoing.insert(key.clone(), outgoing.clone());
1597 self.pending.push(MessageRow {
1598 key: key.clone(),
1599 author: "You".to_owned(),
1600 sender_id: my_user_id,
1601 created_at: Utc::now(),
1602 series: Series::default(),
1603 card: false,
1604 time: chrono::Local::now().format("%H:%M").to_string(),
1605 day_header: None,
1606 blocks: if outgoing.text.is_empty() {
1607 Vec::new()
1608 } else {
1609 vec![Block::Paragraph(Inline::plain(&outgoing.text))]
1610 },
1611 edited: false,
1612 deleted: false,
1613 reactions: Vec::new(),
1614 images: Vec::new(),
1615 local_images: outgoing
1616 .images
1617 .iter()
1618 .map(|image| LocalImage {
1619 image: image.image.clone(),
1620 size: image.dimensions,
1621 })
1622 .collect(),
1623 files: outgoing
1624 .files
1625 .iter()
1626 .map(|file| FileCard {
1627 name: file.name.clone(),
1628 kind: file.kind,
1629 content_type: None,
1630 size: Some(file.size),
1631 open_url: file.reference.content_url.clone(),
1632 })
1633 .collect(),
1634 reply_count: None,
1635 new_marker: false,
1636 reply_faces: Vec::new(),
1637 last_reply_time: None,
1638 open_thread: None,
1639 is_reply: false,
1640 delivery: Delivery::Sending,
1641 receipt: Receipt::Hidden,
1642 own: true,
1643 });
1644 key
1645 }
1646
1647 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1648 let (recipients, topic) = {
1649 let draft = self.draft.read(cx);
1650 let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty());
1651 (draft.chips().to_vec(), topic)
1652 };
1653 if recipients.is_empty() {
1654 self.restore_unsent("Add at least one person first", &outgoing, window, cx);
1655 self.draft
1656 .update(cx, |draft, cx| draft.focus_query(window, cx));
1657 return;
1658 }
1659 if self
1660 .pending
1661 .iter()
1662 .any(|row| matches!(row.delivery, Delivery::Sending))
1663 {
1664 self.restore_unsent("Still creating the chat", &outgoing, window, cx);
1665 return;
1666 }
1667 let state = self.app.read(cx);
1668 let (mode, engine) = (state.mode, state.engine.clone());
1669 if mode.read_only {
1670 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1671 return;
1672 }
1673 if mode.demo && outgoing.has_attachments() {
1674 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1675 return;
1676 }
1677 if mode.demo {
1678 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
1679 return;
1680 }
1681 let Some(engine) = engine else {
1682 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1683 return;
1684 };
1685 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
1686 let known_chat = self
1687 .draft_created
1688 .as_ref()
1689 .filter(|(created_for, _)| *created_for == user_ids)
1690 .map(|(_, chat_id)| chat_id.clone())
1691 .or_else(|| self.draft_target_chat(cx));
1692 self.pending.clear();
1693 self.pending_outgoing.clear();
1694 self.draft_error = None;
1695 self.notice = None;
1696 let key = self.push_pending(&outgoing, cx);
1697 self.rebuild(true, cx);
1698 let recipients_for_finish = user_ids.clone();
1699 let receiver = runtime::spawn(async move {
1700 let chat_id = match known_chat {
1701 Some(chat_id) => chat_id,
1702 None => {
1703 let created = match user_ids.as_slice() {
1704 [user_id] => engine.create_one_on_one(user_id).await,
1705 _ => engine.create_group(&user_ids, topic.as_deref()).await,
1706 };
1707 match created {
1708 Ok(chat_id) => chat_id,
1709 Err(error) => return (None, Some(short_error(&error))),
1710 }
1711 }
1712 };
1713 let sent = engine
1714 .send_message_with_extras(
1715 &chat_id,
1716 &outgoing.text,
1717 None,
1718 &outgoing.mentions,
1719 &outgoing.extras(),
1720 )
1721 .await;
1722 (Some(chat_id), sent.err().map(|error| short_error(&error)))
1723 });
1724 cx.spawn_in(window, async move |this, cx| {
1725 let result = receiver.await;
1726 this.update_in(cx, |this, _, cx| {
1727 this.finish_new_chat(&key, recipients_for_finish, result, cx)
1728 })
1729 .ok();
1730 })
1731 .detach();
1732 }
1733
1734 fn finish_new_chat(
1735 &mut self,
1736 key: &str,
1737 user_ids: Vec<String>,
1738 result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>,
1739 cx: &mut Context<Self>,
1740 ) {
1741 if !self.draft_active || !self.pending.iter().any(|row| row.key == key) {
1742 return;
1743 }
1744 let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned())));
1745 self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id));
1746 match (chat_id, error) {
1747 (Some(chat_id), None) => {
1748 self.app.update(cx, |state, cx| {
1749 state.reload_sidebar(cx);
1750 state.select(Selection::Chat(chat_id), cx);
1751 });
1752 }
1753 (created, error) => {
1754 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
1755 row.delivery = Delivery::Failed(error.unwrap_or_default());
1756 }
1757 self.draft_error = Some(
1758 if created.is_some() {
1759 "Couldn't send the message."
1760 } else {
1761 "Couldn't create the chat."
1762 }
1763 .to_owned(),
1764 );
1765 self.rebuild(false, cx);
1766 }
1767 }
1768 }
1769
1770 fn send_demo_new_chat(
1771 &mut self,
1772 outgoing: &Outgoing,
1773 recipients: &[super::new_chat::Pick],
1774 topic: Option<&str>,
1775 cx: &mut Context<Self>,
1776 ) {
1777 let (store, chats) = {
1778 let state = self.app.read(cx);
1779 (state.store.clone(), state.sidebar.chats.clone())
1780 };
1781 let people: Vec<(String, String)> = recipients
1782 .iter()
1783 .map(|pick| (pick.user_id.clone(), pick.name.clone()))
1784 .collect();
1785 let (chat, message) = match self.draft_target_chat(cx) {
1786 Some(chat_id) => {
1787 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
1788 return;
1789 };
1790 crate::demo::send_in_chat(chat, &outgoing.text, Utc::now())
1791 }
1792 None => crate::demo::new_chat(&chats, &people, topic, &outgoing.text, Utc::now()),
1793 };
1794 let _ = store.upsert_chats(std::slice::from_ref(&chat));
1795 let _ = store.upsert_messages(std::slice::from_ref(&message));
1796 self.app.update(cx, |state, cx| {
1797 state.reload_sidebar(cx);
1798 state.select(Selection::Chat(chat.id.clone()), cx);
1799 });
1800 }
1801
1802 fn conversation_id(&self) -> Option<String> {
1803 self.current
1804 .as_ref()
1805 .map(|current| current.selection.conversation_id().to_owned())
1806 }
1807
1808 fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
1809 let conversation_id = self.conversation_id()?;
1810 let my_user_id = self.row_context(cx).my_user_id?;
1811 self.app
1812 .read(cx)
1813 .store
1814 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1815 .ok()?
1816 .remove(message_id)
1817 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
1818 }
1819
1820 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
1821 let target = match slot {
1822 HoverSlot::Row => &mut self.hovered_message,
1823 HoverSlot::Toolbar => &mut self.toolbar_hovered,
1824 };
1825 if hovered {
1826 *target = Some(key.to_owned());
1827 } else if target.as_deref() == Some(key) {
1828 *target = None;
1829 }
1830 cx.notify();
1831 }
1832
1833 fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) {
1834 if open {
1835 self.toolbar_pinned = Some(key.to_owned());
1836 } else if self.toolbar_pinned.as_deref() == Some(key) {
1837 self.toolbar_pinned = None;
1838 }
1839 cx.notify();
1840 }
1841
1842 fn toolbar_visible(&self, key: &str) -> bool {
1843 self.toolbar_pinned
1844 .as_deref()
1845 .or(self.toolbar_hovered.as_deref())
1846 .or(self.hovered_message.as_deref())
1847 == Some(key)
1848 }
1849
1850 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
1851 let Some(conversation_id) = self.conversation_id() else {
1852 return;
1853 };
1854 let reaction_type = reaction_type_for(glyph);
1855 let wanted = reaction_glyph(glyph);
1856 let state = self.app.read(cx);
1857 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1858 let my_user_id = self.row_context(cx).my_user_id;
1859 let Some(mut record) = store
1860 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1861 .ok()
1862 .and_then(|mut found| found.remove(message_id))
1863 else {
1864 return;
1865 };
1866 let mut reactions = teams_core::reactions(&record);
1867 let mine = |reaction: &teams_core::ReactionInfo| {
1868 reaction_glyph(&reaction.reaction_type) == wanted
1869 && my_user_id.is_some()
1870 && reaction.user_id == my_user_id
1871 };
1872 let remove = reactions.iter().any(mine);
1873 if mode.demo {
1874 if remove {
1875 reactions.retain(|reaction| !mine(reaction));
1876 } else {
1877 reactions.push(teams_core::ReactionInfo {
1878 reaction_type: reaction_type.clone(),
1879 user_id: my_user_id.clone(),
1880 user_name: Some("You".to_owned()),
1881 created_at: Some(Utc::now()),
1882 });
1883 }
1884 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
1885 let _ = store.upsert_messages(std::slice::from_ref(&record));
1886 self.rebuild(false, cx);
1887 return;
1888 }
1889 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1890 self.show_notice("Read-only mode: reaction not sent", cx);
1891 return;
1892 };
1893 let message_id = message_id.to_owned();
1894 let reaction_type = api_reaction(&wanted);
1895 let receiver = runtime::spawn(async move {
1896 if remove {
1897 engine
1898 .unset_reaction(&conversation_id, &message_id, &reaction_type)
1899 .await
1900 } else {
1901 engine
1902 .set_reaction(&conversation_id, &message_id, &reaction_type)
1903 .await
1904 }
1905 });
1906 self.report_failure(receiver, "Reaction failed", cx);
1907 }
1908
1909 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
1910 let Some(record) = self.own_record(message_id, cx) else {
1911 return;
1912 };
1913 let edit = EditPreview {
1914 message_id: record.message_id.clone(),
1915 excerpt: reply_excerpt(&record),
1916 };
1917 let in_chat = matches!(
1918 self.current.as_ref().map(|current| &current.selection),
1919 Some(Selection::Chat(_))
1920 );
1921 let mentions = if in_chat {
1922 teams_core::mentions(&record)
1923 .into_iter()
1924 .filter_map(|mention| {
1925 let user_id = mention.user_id?;
1926 Some(MentionInput::user(&user_id, &mention.name))
1927 })
1928 .collect()
1929 } else {
1930 Vec::new()
1931 };
1932 let draft = Outgoing {
1933 text: message_text(&record),
1934 mentions,
1935 reply: None,
1936 edit: Some(edit),
1937 images: Vec::new(),
1938 files: Vec::new(),
1939 };
1940 self.composer
1941 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
1942 }
1943
1944 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1945 if self.draft_active {
1946 return;
1947 }
1948 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
1949 Row::Message(message)
1950 if message.own
1951 && !message.deleted
1952 && !message.key.starts_with(PENDING_KEY_PREFIX) =>
1953 {
1954 Some(message.key.clone())
1955 }
1956 _ => None,
1957 });
1958 if let Some(key) = key {
1959 self.begin_edit(&key, window, cx);
1960 }
1961 }
1962
1963 fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1964 let Some(edit) = outgoing.edit.clone() else {
1965 return;
1966 };
1967 let Some(conversation_id) = self.conversation_id() else {
1968 return;
1969 };
1970 let state = self.app.read(cx);
1971 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1972 if mode.demo {
1973 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
1974 record.body_html = teams_core::markdown_to_html(&outgoing.text);
1975 record.edited_at = Some(Utc::now());
1976 let _ = store.upsert_messages(std::slice::from_ref(&record));
1977 self.rebuild(false, cx);
1978 }
1979 return;
1980 }
1981 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1982 self.notice = Some("Read-only mode: edit not saved".to_owned());
1983 self.composer
1984 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1985 cx.notify();
1986 return;
1987 };
1988 let sent = outgoing.clone();
1989 let receiver = runtime::spawn(async move {
1990 engine
1991 .edit_message_with_mentions(
1992 &conversation_id,
1993 &edit.message_id,
1994 &sent.text,
1995 &sent.mentions,
1996 )
1997 .await
1998 });
1999 cx.spawn_in(window, async move |this, cx| {
2000 let failed = !matches!(receiver.await, Ok(Ok(())));
2001 this.update_in(cx, |this, window, cx| {
2002 if failed {
2003 if this.composer.read(cx).is_empty(cx) {
2004 this.notice =
2005 Some("Edit failed: your text is back in the composer".to_owned());
2006 this.composer
2007 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2008 } else {
2009 this.notice = Some("Edit failed".to_owned());
2010 }
2011 cx.notify();
2012 }
2013 })
2014 .ok();
2015 })
2016 .detach();
2017 }
2018
2019 fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
2020 let Some(mut record) = self.own_record(message_id, cx) else {
2021 return;
2022 };
2023 let state = self.app.read(cx);
2024 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2025 if mode.demo {
2026 record.deleted = true;
2027 let _ = store.upsert_messages(std::slice::from_ref(&record));
2028 self.rebuild(false, cx);
2029 return;
2030 }
2031 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2032 self.show_notice("Read-only mode: message not deleted", cx);
2033 return;
2034 };
2035 let conversation_id = record.conversation_id.clone();
2036 let receiver = runtime::spawn(async move {
2037 engine
2038 .soft_delete_message(&conversation_id, &record.message_id)
2039 .await
2040 });
2041 self.report_failure(receiver, "Delete failed", cx);
2042 }
2043
2044 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2045 let Some(conversation_id) = self.conversation_id() else {
2046 return;
2047 };
2048 let record = self
2049 .app
2050 .read(cx)
2051 .store
2052 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2053 .ok()
2054 .and_then(|mut found| found.remove(message_id));
2055 if let Some(record) = record {
2056 cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record)));
2057 }
2058 }
2059
2060 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
2061 self.notice = Some(message.to_owned());
2062 cx.notify();
2063 }
2064
2065 fn report_failure(
2066 &mut self,
2067 receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>,
2068 label: &'static str,
2069 cx: &mut Context<Self>,
2070 ) {
2071 cx.spawn(async move |this, cx| {
2072 let error = match receiver.await {
2073 Ok(Ok(())) => return,
2074 Ok(Err(error)) => short_error(&error),
2075 Err(_) => "cancelled".to_owned(),
2076 };
2077 this.update(cx, |this, cx| {
2078 this.show_notice(&format!("{label}: {error}"), cx)
2079 })
2080 .ok();
2081 })
2082 .detach();
2083 }
2084
2085 fn message_menu(&self, key: &str, own: bool, view: WeakEntity<Self>) -> MessageMenu {
2086 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
2087 let (view, key) = (view.clone(), key.to_owned());
2088 Rc::new(move |window, cx| {
2089 view.update(cx, |this, cx| run(this, &key, window, cx)).ok();
2090 })
2091 };
2092 let react: PickHandler = {
2093 let (view, key) = (view.clone(), key.to_owned());
2094 Rc::new(move |glyph, _, cx| {
2095 view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx))
2096 .ok();
2097 })
2098 };
2099 let hover = {
2100 let (view, key) = (view.clone(), key.to_owned());
2101 Rc::new(move |hovered: bool, cx: &mut App| {
2102 view.update(cx, |this, cx| {
2103 this.set_hover(HoverSlot::Toolbar, &key, hovered, cx)
2104 })
2105 .ok();
2106 })
2107 };
2108 let pin = {
2109 let (view, key) = (view.clone(), key.to_owned());
2110 Rc::new(move |open: bool, _: &mut Window, cx: &mut App| {
2111 view.update(cx, |this, cx| this.set_pinned(&key, open, cx))
2112 .ok();
2113 })
2114 };
2115 MessageMenu {
2116 key: key.to_owned(),
2117 react,
2118 reply: Some(action(|this, key, window, cx| {
2119 this.begin_reply(key, window, cx)
2120 })),
2121 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
2122 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
2123 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
2124 pin,
2125 hover,
2126 picker: self.picker.clone(),
2127 }
2128 }
2129
2130 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
2131 let Some(outgoing) = self.pending_outgoing.remove(key) else {
2132 return;
2133 };
2134 self.pending.retain(|row| row.key != key);
2135 if self.draft_active {
2136 self.send_new_chat(outgoing, window, cx);
2137 } else {
2138 self.send(outgoing, window, cx);
2139 }
2140 }
2141
2142 fn finish_send(
2143 &mut self,
2144 key: &str,
2145 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
2146 cx: &mut Context<Self>,
2147 ) {
2148 let failure = match result {
2149 Ok(Ok(())) => None,
2150 Ok(Err(error)) => Some(short_error(&error)),
2151 Err(error) => Some(short_error(&error)),
2152 };
2153 match failure {
2154 None => {
2155 self.pending.retain(|row| row.key != key);
2156 self.pending_outgoing.remove(key);
2157 }
2158 Some(error) => {
2159 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2160 row.delivery = Delivery::Failed(error.clone());
2161 self.notice = Some(format!("Not sent: {error}"));
2162 }
2163 }
2164 }
2165 self.rebuild(false, cx);
2166 }
2167
2168 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
2169 let target = match self.current.as_ref().map(|current| &current.selection) {
2170 Some(Selection::Chat(_)) => DropTarget::Chat,
2171 Some(Selection::Channel(_)) => DropTarget::Channel,
2172 None => DropTarget::NewChat,
2173 };
2174 let title = self
2175 .current
2176 .as_ref()
2177 .map(|current| current.title.as_str())
2178 .unwrap_or_default();
2179 let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1));
2180 let composer = self.composer.clone();
2181 div()
2182 .id("drop-overlay")
2183 .absolute()
2184 .top_0()
2185 .left_0()
2186 .size_full()
2187 .opacity(0.)
2188 .bg(theme::drop_background())
2189 .drag_over::<ExternalPaths>(move |style, _, _, cx| {
2190 if composer.read(cx).is_editing() {
2191 style
2192 } else {
2193 style.opacity(1.)
2194 }
2195 })
2196 .on_drag_move(
2197 cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
2198 let count = event.drag(cx).paths().len();
2199 if this.drag_file_count != count {
2200 this.drag_file_count = count;
2201 cx.notify();
2202 }
2203 }),
2204 )
2205 .on_drop(cx.listener(|this, dropped: &ExternalPaths, _, cx| {
2206 let paths = dropped.paths().to_vec();
2207 this.composer
2208 .update(cx, |composer, cx| composer.add_paths(paths, cx));
2209 }))
2210 .child(
2211 div()
2212 .absolute()
2213 .inset(px(12.))
2214 .rounded(px(12.))
2215 .border_2()
2216 .border_dashed()
2217 .border_color(theme::accent())
2218 .flex()
2219 .items_center()
2220 .justify_center()
2221 .child(
2222 v_flex()
2223 .items_center()
2224 .gap(px(6.))
2225 .px(px(28.))
2226 .py(px(18.))
2227 .rounded(px(12.))
2228 .bg(black().opacity(0.55))
2229 .child(symbol("upload", 28., theme::accent_text()))
2230 .child(
2231 div()
2232 .text_size(px(15.))
2233 .font_weight(FontWeight::SEMIBOLD)
2234 .text_color(theme::text_strong())
2235 .child(heading),
2236 )
2237 .child(
2238 div()
2239 .text_size(px(12.))
2240 .text_color(theme::text_muted())
2241 .child(detail),
2242 ),
2243 ),
2244 )
2245 }
2246
2247 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
2248 let message = self.draft_error.clone()?;
2249 let failed_key = self
2250 .pending
2251 .iter()
2252 .find(|row| matches!(row.delivery, Delivery::Failed(_)))
2253 .map(|row| row.key.clone())?;
2254 Some(
2255 h_flex()
2256 .w_full()
2257 .flex_none()
2258 .px(px(24.))
2259 .py(px(4.))
2260 .gap(px(8.))
2261 .items_center()
2262 .text_size(px(12.))
2263 .text_color(theme::red_soft())
2264 .child(message)
2265 .child(
2266 Button::new("retry-new-chat")
2267 .ghost()
2268 .compact()
2269 .label("Retry")
2270 .on_click(cx.listener(move |this, _, window, cx| {
2271 this.retry(&failed_key, window, cx)
2272 })),
2273 ),
2274 )
2275 }
2276
2277 fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement {
2278 let app = self.app.read(cx);
2279 let directory = &app.directory;
2280 let me = directory.me.as_ref();
2281 let mut lead: Option<AnyElement> = None;
2282 let mut subline = String::new();
2283 let mut stack: Option<Div> = None;
2284 match &current.selection {
2285 Selection::Chat(chat_id) => {
2286 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
2287 let faces = others(chat, me);
2288 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
2289 let first = faces.first().cloned().map(face);
2290 if is_one_on_one(chat) || faces.len() < 2 {
2291 let name = first
2292 .as_ref()
2293 .map_or(current.title.as_str(), |face| face.name.as_str());
2294 let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
2295 let avatar = person_avatar(directory, user_id, name, 36.);
2296 let presence = user_id.map(|id| directory.presence_of(id));
2297 lead = Some(match presence {
2298 Some(kind) => with_presence(avatar, kind, 36., theme::background())
2299 .into_any_element(),
2300 None => avatar,
2301 });
2302 subline = presence
2303 .map(|presence| presence.kind().label().to_owned())
2304 .unwrap_or_default();
2305 } else {
2306 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
2307 lead = Some(spec_avatar(directory, &pair, 36., theme::background()));
2308 subline = format!("{} participants", chat.members.len());
2309 let shown: Vec<Face> = faces.iter().cloned().map(face).collect();
2310 stack = Some(member_stack(directory, &shown, shown.len()));
2311 }
2312 }
2313 }
2314 Selection::Channel(channel_id) => {
2315 let team = app.sidebar.teams.iter().find(|entry| {
2316 entry
2317 .channels
2318 .iter()
2319 .any(|channel| &channel.id == channel_id)
2320 });
2321 let (name, key) = team
2322 .map_or((current.title.as_str(), current.title.as_str()), |entry| {
2323 (entry.team.name.as_str(), entry.team.id.as_str())
2324 });
2325 lead = Some(square_avatar(name, key, 36., 9.).into_any_element());
2326 }
2327 }
2328 let mut header = h_flex()
2329 .w_full()
2330 .h(px(60.))
2331 .flex_none()
2332 .px(px(20.))
2333 .gap(px(12.))
2334 .items_center()
2335 .border_b_1()
2336 .border_color(theme::border());
2337 if matches!(current.mode, ViewMode::Thread(_)) {
2338 header = header.child(
2339 Button::new("back-to-threads")
2340 .ghost()
2341 .compact()
2342 .label("Threads")
2343 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx))),
2344 );
2345 }
2346 let channel_note = match current.mode {
2347 ViewMode::Flat => None,
2348 ViewMode::ThreadList => Some("Threads"),
2349 ViewMode::Thread(_) => Some("Thread"),
2350 };
2351 if let Some(note) = channel_note {
2352 subline = note.to_owned();
2353 }
2354 let sync = &current.sync;
2355 if sync.failed {
2356 subline = "Not up to date".to_owned();
2357 } else if sync.shown_at.is_some() {
2358 subline = if sync.slow {
2359 "Taking longer than usual ..."
2360 } else if sync.empty_cache {
2361 "Loading messages ..."
2362 } else {
2363 "Updating ..."
2364 }
2365 .to_owned();
2366 }
2367 header
2368 .relative()
2369 .when(sync.shown_at.is_some(), |header| {
2370 header.child(progress_bar())
2371 })
2372 .children(lead)
2373 .child(
2374 v_flex()
2375 .flex_1()
2376 .min_w_0()
2377 .overflow_hidden()
2378 .gap(px(1.))
2379 .child(
2380 div()
2381 .truncate()
2382 .text_size(px(15.))
2383 .font_weight(FontWeight::SEMIBOLD)
2384 .text_color(theme::text())
2385 .child(current.title.clone()),
2386 )
2387 .when(!subline.is_empty(), |column| {
2388 column.child(
2389 div()
2390 .text_size(px(12.))
2391 .text_color(theme::text_muted())
2392 .child(subline),
2393 )
2394 }),
2395 )
2396 .children(stack)
2397 }
2398}
2399
2400impl Render for ConversationView {
2401 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2402 let background = theme::background();
2403 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2404 let drafting = self.draft_active;
2405 if self.current.is_none() && !drafting {
2406 return root
2407 .items_center()
2408 .justify_center()
2409 .text_color(theme::text_muted())
2410 .child("Select a chat or channel")
2411 .into_any_element();
2412 }
2413 let rows = self.rows.clone();
2414 let view = cx.weak_entity();
2415 let app = self.app.clone();
2416 let highlighted = self.highlighted_message.clone();
2417 let scroller = MessageScroller::new(
2418 "messages",
2419 self.scroller.clone(),
2420 move |index, window, cx| {
2421 let rows = rows.borrow();
2422 match rows.get(index) {
2423 Some(Row::Message(message)) => {
2424 let open_thread = message.open_thread.clone().map(|root_id| {
2425 let view = view.clone();
2426 Box::new(move |cx: &mut App| {
2427 let root_id = root_id.clone();
2428 view.update(cx, |this, cx| this.open_thread(root_id, cx))
2429 .ok();
2430 }) as Box<dyn Fn(&mut App)>
2431 });
2432 let retry = matches!(message.delivery, Delivery::Failed(_)).then(|| {
2433 let (view, key, handle) =
2434 (view.clone(), message.key.clone(), window.window_handle());
2435 Box::new(move |cx: &mut App| {
2436 let (view, key) = (view.clone(), key.clone());
2437 handle
2438 .update(cx, move |_, window, cx| {
2439 view.update(cx, |this, cx| this.retry(&key, window, cx))
2440 .ok();
2441 })
2442 .ok();
2443 }) as Box<dyn Fn(&mut App)>
2444 });
2445 let senders: Vec<String> = (!message.own && !message.series.has_prev)
2446 .then(|| message.sender_id.clone())
2447 .flatten()
2448 .into_iter()
2449 .chain(
2450 message
2451 .reactions
2452 .iter()
2453 .flat_map(|chip| chip.reactors.iter())
2454 .filter_map(|reactor| reactor.user_id.clone()),
2455 )
2456 .filter(|sender| app.read(cx).directory.avatar(sender).is_none())
2457 .collect();
2458 if !senders.is_empty() {
2459 let app = app.clone();
2460 cx.defer(move |cx| {
2461 app.update(cx, |state, cx| state.request_avatars(senders, cx));
2462 });
2463 }
2464 let missing_images: Vec<ImageRef> = message
2465 .images
2466 .iter()
2467 .filter(|image| app.read(cx).directory.image(&image.url).is_none())
2468 .cloned()
2469 .collect();
2470 if !missing_images.is_empty() {
2471 let app = app.clone();
2472 cx.defer(move |cx| {
2473 app.update(cx, |state, cx| {
2474 state.request_images(missing_images, cx)
2475 });
2476 });
2477 }
2478 let is_real = !drafting && !message.key.starts_with(PENDING_KEY_PREFIX);
2479 let hovered = is_real.then(|| {
2480 let (view, key) = (view.clone(), message.key.clone());
2481 Rc::new(move |hovered: bool, cx: &mut App| {
2482 view.update(cx, |this, cx| {
2483 this.set_hover(HoverSlot::Row, &key, hovered, cx)
2484 })
2485 .ok();
2486 }) as Rc<dyn Fn(bool, &mut App)>
2487 });
2488 let actionable = is_real && !message.deleted && !message.card;
2489 let (menu, react, reaction_controls) = view
2490 .upgrade()
2491 .filter(|_| actionable)
2492 .map(|entity| {
2493 let this = entity.read(cx);
2494 let menu =
2495 this.message_menu(&message.key, message.own, view.clone());
2496 let react = menu.react.clone();
2497 let visible = this.toolbar_visible(&message.key);
2498 let controls = (!message.reactions.is_empty())
2499 .then(|| this.reaction_controls(&message.key, view.clone()));
2500 (visible.then_some(menu), Some(react), controls)
2501 })
2502 .unwrap_or((None, None, None));
2503 let reply = (is_real && !message.deleted).then(|| {
2504 let (view, key, handle) =
2505 (view.clone(), message.key.clone(), window.window_handle());
2506 Box::new(move |cx: &mut App| {
2507 let (view, key) = (view.clone(), key.clone());
2508 handle
2509 .update(cx, move |_, window, cx| {
2510 view.update(cx, |this, cx| {
2511 this.begin_reply(&key, window, cx)
2512 })
2513 .ok();
2514 })
2515 .ok();
2516 }) as Box<dyn Fn(&mut App)>
2517 });
2518 let files = (is_real && !message.deleted && !message.files.is_empty())
2519 .then(|| view.upgrade())
2520 .flatten()
2521 .map(|entity| {
2522 entity.read(cx).file_actions(
2523 &message.key,
2524 &message.files,
2525 view.clone(),
2526 )
2527 });
2528 let state = app.read(cx);
2529 render_message_row(
2530 message,
2531 index,
2532 RowActions {
2533 open_thread,
2534 retry,
2535 reply,
2536 hovered,
2537 menu,
2538 react,
2539 reaction_controls,
2540 files,
2541 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
2542 },
2543 &state.directory,
2544 cx,
2545 )
2546 }
2547 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
2548 Some(Row::LoadOlder) => {
2549 let view = view.clone();
2550 cx.defer(move |cx| {
2551 view.update(cx, |this, cx| this.request_older(cx)).ok();
2552 });
2553 h_flex()
2554 .w_full()
2555 .py_2()
2556 .gap(px(6.))
2557 .justify_center()
2558 .text_size(px(12.))
2559 .text_color(theme::text_muted())
2560 .child(icon(IconName::Loader, 12., theme::text_muted()))
2561 .child("Loading older messages")
2562 .into_any_element()
2563 }
2564 Some(Row::Start(start)) => {
2565 let state = app.read(cx);
2566 v_flex()
2567 .w_full()
2568 .items_center()
2569 .gap(px(8.))
2570 .pt(px(32.))
2571 .pb(px(16.))
2572 .child(person_avatar(
2573 &state.directory,
2574 start.user_id.as_deref(),
2575 &start.title,
2576 56.,
2577 ))
2578 .child(
2579 div()
2580 .text_size(px(16.))
2581 .font_weight(FontWeight::SEMIBOLD)
2582 .text_color(theme::text())
2583 .child(start.title.clone()),
2584 )
2585 .child(
2586 div()
2587 .text_size(px(12.))
2588 .text_color(theme::text_muted())
2589 .child("This is the beginning of the conversation"),
2590 )
2591 .into_any_element()
2592 }
2593 None => div().into_any_element(),
2594 }
2595 },
2596 )
2597 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
2598 .with_bottom_fade(background);
2599
2600 root = match self.current.as_ref().filter(|_| !drafting) {
2601 Some(current) => root.child(self.render_header(current, cx)),
2602 None => root.child(self.draft.clone()),
2603 };
2604 let sync_failed = self
2605 .current
2606 .as_ref()
2607 .is_some_and(|current| current.sync.failed);
2608 if let Some(notice) = &self.notice {
2609 root = root.child(
2610 h_flex()
2611 .px_4()
2612 .py_1()
2613 .gap(px(8.))
2614 .items_center()
2615 .text_xs()
2616 .bg(theme::amber().opacity(0.15))
2617 .text_color(theme::amber())
2618 .child(div().flex_1().min_w_0().child(notice.clone()))
2619 .when(sync_failed, |bar| {
2620 bar.child(
2621 Button::new("retry-fetch")
2622 .ghost()
2623 .compact()
2624 .label("Retry")
2625 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
2626 )
2627 }),
2628 );
2629 }
2630 let empty_channel = self
2631 .current
2632 .as_ref()
2633 .is_some_and(|current| current.mode == ViewMode::ThreadList)
2634 && self.rows.borrow().is_empty();
2635 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
2636 let draft = self.draft.read(cx);
2637 let group_name = draft.group_name(cx);
2638 draft.render_empty(&self.app.read(cx).directory, &group_name)
2639 } else if empty_channel {
2640 div()
2641 .size_full()
2642 .flex()
2643 .items_center()
2644 .justify_center()
2645 .text_size(px(13.))
2646 .text_color(theme::text_muted())
2647 .child("No posts in this channel yet")
2648 .into_any_element()
2649 } else {
2650 scroller.into_any_element()
2651 };
2652 root.child(
2653 v_flex()
2654 .relative()
2655 .flex_1()
2656 .min_h_0()
2657 .child(
2658 div()
2659 .flex_1()
2660 .min_h_0()
2661 .on_scroll_wheel(
2662 cx.listener(|this, _, _, cx| this.close_reaction_details(cx)),
2663 )
2664 .child(body),
2665 )
2666 .children(self.render_draft_error(cx))
2667 .child(self.composer.clone())
2668 .child(self.render_drop_overlay(cx)),
2669 )
2670 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
2671 if this.reaction_details.is_some() {
2672 this.close_reaction_details(cx);
2673 cx.stop_propagation();
2674 }
2675 }))
2676 .when(drafting, |root| {
2677 root.on_action(cx.listener(|this, _: &Escape, window, cx| {
2678 if this.draft.read(cx).has_focus(window, cx) {
2679 this.draft.update(cx, |draft, cx| draft.escape(cx));
2680 }
2681 }))
2682 })
2683 .into_any_element()
2684 }
2685}
2686
2687fn progress_bar() -> impl IntoElement {
2688 div()
2689 .absolute()
2690 .left_0()
2691 .right_0()
2692 .bottom(px(-1.))
2693 .h(px(2.))
2694 .overflow_hidden()
2695 .bg(theme::border())
2696 .child(
2697 div()
2698 .absolute()
2699 .top_0()
2700 .h_full()
2701 .w(relative(PROGRESS_BAR_WIDTH))
2702 .bg(theme::own_read())
2703 .with_animation(
2704 "sync-progress",
2705 Animation::new(PROGRESS_BAR_PERIOD).repeat(),
2706 |bar, delta| {
2707 let travel = 1. + PROGRESS_BAR_WIDTH;
2708 // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).
2709 bar.left(relative(
2710 (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,
2711 ))
2712 },
2713 ),
2714 )
2715}
2716
2717#[cfg(test)]
2718mod tests {
2719 use std::sync::Arc;
2720
2721 use super::{DropTarget, drop_overlay_text};
2722
2723 use gpui_kit::test::TestWindowExt as _;
2724 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
2725 use store::Store;
2726
2727 use super::ConversationView;
2728 use crate::app_state::{AppState, Mode, Selection};
2729
2730 #[test]
2731 fn chat_overlay_names_the_chat_and_the_onedrive() {
2732 assert_eq!(
2733 drop_overlay_text("Mara Lin", DropTarget::Chat, 3),
2734 (
2735 "Drop to attach to Mara Lin".to_owned(),
2736 "3 files. Images go into the message, other files to your OneDrive.".to_owned()
2737 )
2738 );
2739 }
2740
2741 #[test]
2742 fn channel_overlay_points_to_the_channel_files() {
2743 let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1);
2744 assert_eq!(
2745 detail,
2746 "1 file. Images go into the message, other files to the channel's Files."
2747 );
2748 }
2749
2750 #[test]
2751 fn new_chat_overlay_says_files_wait_for_the_chat() {
2752 let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2);
2753 assert_eq!(heading, "Drop to attach to the new chat");
2754 assert_eq!(
2755 detail,
2756 "2 files. Images go into the message. Files can be added once the chat exists."
2757 );
2758 }
2759
2760 #[gpui_kit::test]
2761 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
2762 cx.update(gpui_kit::init);
2763 let store = Arc::new(Store::open_in_memory().unwrap());
2764 crate::demo::seed(&store);
2765 let mode = Mode {
2766 demo: true,
2767 read_only: false,
2768 demo_sync: None,
2769 };
2770 let (handle, app, _view) = cx.update(|cx| {
2771 let app = cx.new(|_| {
2772 let mut state = AppState::new(store, mode);
2773 crate::demo::seed_directory(&mut state);
2774 state.selection = Some(crate::demo::first_selection());
2775 state
2776 });
2777 let shared = app.clone();
2778 let (handle, view) =
2779 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2780 cx.new(|cx| ConversationView::new(shared, window, cx))
2781 })
2782 .unwrap();
2783 (handle, app, view)
2784 });
2785 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
2786 let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| {
2787 cx.update_window(handle, move |_, window, cx| {
2788 run(window, cx);
2789 window.render_frame(cx);
2790 })
2791 .unwrap();
2792 };
2793 step(cx, |window, cx| window.render_frame(cx));
2794 step(cx, |window, cx| window.input("lea", cx));
2795 step(cx, |window, cx| window.press("enter", cx));
2796 step(cx, |window, cx| window.press("enter", cx));
2797 step(cx, |window, cx| window.input("Hello Lea", cx));
2798 step(cx, |window, cx| window.press("enter", cx));
2799 cx.update(|cx| {
2800 let state = app.read(cx);
2801 assert!(!state.new_chat);
2802 assert_eq!(
2803 state.selection,
2804 Some(Selection::Chat("demo-chat-new-1".to_owned()))
2805 );
2806 let chat = state
2807 .sidebar
2808 .chats
2809 .iter()
2810 .find(|chat| chat.id == "demo-chat-new-1")
2811 .expect("new chat in the sidebar");
2812 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea"));
2813 });
2814 }
2815
2816 #[gpui_kit::test]
2817 fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) {
2818 cx.update(gpui_kit::init);
2819 let store = Arc::new(Store::open_in_memory().unwrap());
2820 crate::demo::seed(&store);
2821 let mode = Mode {
2822 demo: true,
2823 read_only: false,
2824 demo_sync: None,
2825 };
2826 let (handle, app) = cx.update(|cx| {
2827 let app = cx.new(|_| {
2828 let mut state = AppState::new(store, mode);
2829 crate::demo::seed_directory(&mut state);
2830 state.selection = Some(crate::demo::first_selection());
2831 state
2832 });
2833 let shared = app.clone();
2834 let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2835 cx.new(|cx| ConversationView::new(shared, window, cx))
2836 })
2837 .unwrap();
2838 (handle, app)
2839 });
2840 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
2841 cx.update_window(handle, |_, window, cx| {
2842 window.render_frame(cx);
2843 window.press("escape", cx);
2844 window.render_frame(cx);
2845 window.press("escape", cx);
2846 window.render_frame(cx);
2847 })
2848 .unwrap();
2849 cx.update(|cx| {
2850 let state = app.read(cx);
2851 assert!(!state.new_chat);
2852 assert_eq!(state.selection, Some(crate::demo::first_selection()));
2853 });
2854 }
2855}