BlueGit

ict rusty-teams

Files

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

conversation.rs

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