BlueGit

ict rusty-teams

Files

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

conversation.rs

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