BlueGit

ict rusty-teams

Files

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

conversation.rs

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