BlueGit

ict rusty-teams

Files

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

conversation.rs

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