BlueGit

ict rusty-teams

Files

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

conversation.rs

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