BlueGit

ict rusty-teams

Files

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

conversation.rs

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