BlueGit

ict rusty-teams

Files

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

conversation.rs

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