BlueGit

ict rusty-teams

Files

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

conversation.rs

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