BlueGit

ict rusty-teams

Files

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

conversation.rs

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