BlueGit

ict rusty-teams

Files

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

conversation.rs

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