BlueGit

ict rusty-teams

Files

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

conversation.rs

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