BlueGit

ict rusty-teams

Files

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

conversation.rs

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