BlueGit

ict rusty-teams

Files

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

conversation.rs

conversation.rs 154.5 KiB Download Raw
1use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
5use std::time::{Duration, Instant};
6
7use chrono::{DateTime, Local, Offset, Utc};
8use gpui_kit::assets::IconName;
9use gpui_kit::component::{
10 button::{Button, ButtonVariants as _},
11 h_flex,
12 input::{Escape, InputState},
13 message_scroller::{MessageScroller, MessageScrollerState},
14 tooltip::Tooltip,
15 v_flex,
16};
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget, is_bot_id};
20use teams_core::{
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, is_notes_chat, without_islands,
22};
23
24mod channel_details;
25pub use channel_details::{
26 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
27 CHANNEL_DETAILS_TAG,
28};
29mod deletes;
30mod detached;
31mod feed;
32mod forward_select;
33#[cfg(test)]
34pub use forward_select::{
35 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
36};
37mod jump;
38mod notes_space;
39mod pins;
40mod proposal;
41mod recap;
42mod receipt_fade;
43mod render_env;
44mod scheduled;
45mod shared;
46
47use super::add_people_dialog::open_add_people;
48use super::attachments::FileActions;
49use super::avatar::{
50 bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
51};
52use super::call_controls::header_call_controls;
53use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
54use super::chat_members::members_popover;
55use super::chat_pop_out;
56use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
57use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
58use super::group_name::group_name_button;
59use super::message_actions::{Action, DelegateEntry, MessageMenu};
60use super::message_row::{
61 AVATAR_GAP, AVATAR_SIZE, JUMP_HIGHLIGHT_PERIOD, render_message_row, render_skeleton_row,
62};
63use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
64use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
65use super::post_card::render_post;
66use super::profile_card::opens_profile;
67use super::reaction_picker::{PickHandler, ReactionPicker};
68use super::reaction_pills::{ReactionControls, ReactionPopover};
69use super::scroll_edge::edge_divider;
70use super::toolbar_placement::{TimelineBounds, record_bounds};
71use super::widgets::{icon, symbol};
72use crate::agents::{AgentRun, StartRequest};
73use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_title};
74use crate::backend::Engine;
75use crate::card_state::CardScope;
76use crate::channel_files::DownloadSource;
77use crate::chat_settings_actions::shown_receipt;
78use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};
79use crate::demo_library::DemoLibrary;
80use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
81use crate::emoji;
82use crate::emoticons;
83use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
84use crate::notice::short_error;
85use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
86use crate::pending_rows::pending_row;
87use crate::people::{local_names, resolve_names};
88use crate::reaction_model::UNKNOWN_REACTOR;
89use crate::read_state::{ReadTrigger, missed_before_fetch, plan_read};
90use crate::rows::{
91 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
92 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
93 forward_sender_ids, has_own_reaction, message_draft, message_text, own_reaction_glyph,
94 place_local_rows, placeholder_rows, reaction_glyph, reply_excerpt, set_own_reaction,
95 thread_list_rows, thread_rows,
96};
97use crate::runtime;
98use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
99use crate::sidebar_model::{AvatarSpec, Face, channel_unread};
100use crate::theme;
101use crate::translation::TranslationLine;
102use crate::typing::typing_tooltip;
103use app_ui_kit::layout::{COMFY_RUNWAY_WIDTH, ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
104use detached::DetachedWindow;
105use feed::{FeedStash, subject_input};
106use mcp::ReactionProposal;
107use render_env::RenderEnv;
108use shared::SharedState;
109
110pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
111pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
112pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
113pub const FEED_EDGE_TAG: &str = "shell/islands/main/timeline/divider-feed";
114const HEADER_HEIGHT: f32 = 60.;
115const HEADER_PADDING: f32 = 20.;
116const HEADER_GAP: f32 = 12.;
117const POP_IN_BUTTON_SIZE: f32 = 32.;
118const HEADER_LEAD_SIZE: f32 = 36.;
119const TABS_INLINE_MIN_WIDTH: f32 = 560.;
120const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
121const TABS_ROW_HEIGHT: f32 = 36.;
122const CHAT_OPEN_LIMIT: usize = 60;
123const CHANNEL_OPEN_LIMIT: usize = 300;
124const GROWTH_HEADROOM: usize = 20;
125const META_USER_ID: &str = "me_user_id";
126const PENDING_KEY_PREFIX: &str = "pending-";
127const DEMO_DOWNLOAD_STEPS: u8 = 10;
128const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);
129const JUMP_SCAN_LIMIT: usize = 5000;
130const JUMP_CONTEXT_MESSAGES: usize = 12;
131const PROGRESS_DELAY: Duration = Duration::from_millis(400);
132const SLOW_AFTER: Duration = Duration::from_secs(8);
133const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
134const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
135const PROGRESS_BAR_WIDTH: f32 = 0.35;
136const TYPING_LINE_HEIGHT: f32 = 22.;
137const TYPING_DOT_SIZE: f32 = 5.;
138const TYPING_DOT_COUNT: usize = 3;
139const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200);
140
141#[derive(Clone, Copy)]
142enum HoverSlot {
143 Row,
144 Toolbar,
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
148enum ViewMode {
149 Flat,
150 ThreadList,
151 Thread(String),
152}
153
154#[derive(Default)]
155struct SyncProgress {
156 messages: bool,
157 receipts: bool,
158 empty_cache: bool,
159 newest_cached: Option<DateTime<Utc>>,
160 started_at: DateTime<Utc>,
161 shown_at: Option<Instant>,
162 slow: bool,
163 failed: bool,
164}
165
166impl SyncProgress {
167 fn running(&self) -> bool {
168 self.messages || self.receipts
169 }
170}
171
172struct Current {
173 selection: Selection,
174 title: String,
175 mode: ViewMode,
176 loaded_limit: usize,
177 loaded_count: usize,
178 has_older: bool,
179 loading_older: bool,
180 older_blocked: bool,
181 fetched: bool,
182 first_unread: Option<String>,
183 posts_new_after: Option<DateTime<Utc>>,
184 sync: SyncProgress,
185 detached: Option<DetachedWindow>,
186 window_request: Option<String>,
187}
188
189struct ReactionDetails {
190 message_key: String,
191 anchor_glyph: String,
192 tab: Option<String>,
193}
194
195#[derive(Clone, Copy, PartialEq, Eq)]
196enum ReactionAttempt {
197 Acted,
198 Started,
199 AlreadyThere,
200 MissingMessage,
201 Blocked,
202}
203
204pub struct ConversationView {
205 app: Entity<AppState>,
206 pinned: bool,
207 popped_out: bool,
208 scroller: Entity<MessageScrollerState>,
209 composer: Entity<Composer>,
210 subject: Entity<InputState>,
211 new_post_open: bool,
212 reply_composer: Option<Entity<Composer>>,
213 reply_root: Option<String>,
214 feed_stash: Option<FeedStash>,
215 feed_rows_seen: Rc<Cell<usize>>,
216 feed_at_top: bool,
217 draft: Entity<NewChatDraft>,
218 draft_active: bool,
219 draft_created: Option<(Vec<String>, String)>,
220 draft_error: Option<String>,
221 rows: Rc<RefCell<Vec<Row>>>,
222 current: Option<Current>,
223 pending: Vec<MessageRow>,
224 pending_counter: usize,
225 pending_outgoing: HashMap<String, Outgoing>,
226 pending_reactions: PendingReactions,
227 downloads: Downloads,
228 hovered_message: Option<String>,
229 toolbar_hovered: Option<String>,
230 timeline_bounds: TimelineBounds,
231 header_width: Rc<Cell<f32>>,
232 toolbar_pinned: Option<String>,
233 toolbar_suppressed: Option<String>,
234 recent: Entity<emoji::Recent>,
235 picker: Entity<ReactionPicker>,
236 reaction_details: Option<ReactionDetails>,
237 highlighted_message: Option<String>,
238 fetched_jump: Option<String>,
239 pin_index: usize,
240 channel_details_open: bool,
241 pinned_posts_expanded: bool,
242 channel_details_scroll: ScrollHandle,
243 scroller_watch: Option<(EntityId, Subscription)>,
244 pin_previews: HashMap<String, pins::PinPreview>,
245 pin_fetches: HashSet<String>,
246 notice: Option<String>,
247 scheduled_failure: Option<scheduled::ScheduledFailure>,
248 scheduled_in_flight: HashSet<String>,
249 drag_file_count: usize,
250 sync_generation: u64,
251 window_active: bool,
252 pane: ChannelPane,
253 recap: recap::RecapState,
254 recap_search: Entity<InputState>,
255 channel_tabs: Vec<ChannelTabRecord>,
256 tab_links: HashMap<String, String>,
257 focus_handle: FocusHandle,
258 shared: SharedState,
259 demo_library: DemoLibrary,
260 new_folder_input: Option<Entity<InputState>>,
261 agent_layouts: HashMap<String, (usize, bool)>,
262 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
263 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
264 receipt_fade: receipt_fade::ReceiptFade,
265 find_panel: Option<Entity<FindPanel>>,
266 find_subscription: Option<Subscription>,
267 _subscriptions: Vec<Subscription>,
268}
269
270fn open_limit(selection: &Selection) -> usize {
271 match selection {
272 Selection::Chat(_) => CHAT_OPEN_LIMIT,
273 Selection::Channel(_) => CHANNEL_OPEN_LIMIT,
274 }
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278enum DropTarget {
279 Chat,
280 Channel,
281 Library,
282 NewChat,
283}
284
285fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) {
286 let files = if count == 1 {
287 "1 file".to_owned()
288 } else {
289 format!("{count} files")
290 };
291 match target {
292 DropTarget::Chat => (
293 format!("Drop to attach to {title}"),
294 format!("{files}. Images go into the message, other files to your OneDrive."),
295 ),
296 DropTarget::Channel => (
297 format!("Drop to attach to {title}"),
298 format!("{files}. Images go into the message, other files to the channel's Files."),
299 ),
300 DropTarget::Library => (
301 format!("Drop to upload to {title}"),
302 format!("{files}. Files go into the folder you have open."),
303 ),
304 DropTarget::NewChat => (
305 "Drop to attach to the new chat".to_owned(),
306 format!(
307 "{files}. Images go into the message. Files can be added once the chat exists."
308 ),
309 ),
310 }
311}
312
313fn shown_in_view(mode: &ViewMode, record: &store::OutboxRecord) -> bool {
314 match mode {
315 ViewMode::Flat => record.target == OutboxTarget::Flat,
316 ViewMode::ThreadList => matches!(record.target, OutboxTarget::Post | OutboxTarget::Thread),
317 ViewMode::Thread(root_id) => {
318 record.target == OutboxTarget::Thread
319 && record.thread_root_id.as_deref() == Some(root_id.as_str())
320 }
321 }
322}
323
324enum DownloadEvent {
325 Progress(u8),
326 Finished(Result<PathBuf, String>),
327}
328
329async fn save_file(
330 engine: &Engine,
331 card: &FileCard,
332 source: &DownloadSource,
333 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
334) -> Result<PathBuf, String> {
335 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
336 .map_err(|error| short_error(&error))?;
337 let write = |bytes: &[u8]| part.write(bytes);
338 let progress = |percent| {
339 let _ = events.send(DownloadEvent::Progress(percent));
340 };
341 match source {
342 DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await,
343 DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await,
344 }
345 .map_err(|error| short_error(&error))?;
346 part.finish().map_err(|error| short_error(&error))
347}
348
349impl ConversationView {
350 fn file_actions(
351 &self,
352 message_key: &str,
353 files: &[FileCard],
354 view: WeakEntity<Self>,
355 ) -> FileActions {
356 let conversation_id = self.conversation_id().unwrap_or_default();
357 let (key, cards) = (message_key.to_owned(), files.to_vec());
358 let open_urls: Vec<&str> = files.iter().map(|card| card.open_url.as_str()).collect();
359 FileActions {
360 states: self
361 .downloads
362 .states_for(&conversation_id, message_key, &open_urls),
363 activate: Rc::new(move |index, cx| {
364 let Some(card) = cards.get(index).cloned() else {
365 return;
366 };
367 let key = key.clone();
368 let conversation_id = conversation_id.clone();
369 view.update(cx, |this, cx| {
370 this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx)
371 })
372 .ok();
373 }),
374 }
375 }
376
377 fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context<Self>) {
378 let Some(current) = self.current.as_ref() else {
379 return;
380 };
381 let now = Local::now();
382 let items = collect_gallery(&self.rows.borrow(), now.date_naive(), now.offset().fix());
383 let Some(index) = position_of(&items, message_key, url) else {
384 return;
385 };
386 let request = ViewerRequest {
387 conversation_id: current.selection.conversation_id().to_owned(),
388 conversation_title: selection_title(&self.app.read(cx).sidebar, &current.selection),
389 items,
390 index,
391 };
392 self.app
393 .update(cx, |state, cx| state.request_image_viewer(request, cx));
394 }
395
396 fn activate_file(
397 &mut self,
398 conversation_id: &str,
399 message_key: &str,
400 card: FileCard,
401 source: DownloadSource,
402 cx: &mut Context<Self>,
403 ) {
404 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
405 match downloads::click_action(self.downloads.state(&key)) {
406 ClickAction::Ignore => {}
407 ClickAction::Start => self.start_download(key, card, source, cx),
408 ClickAction::Reveal(path) => {
409 let folder = path
410 .parent()
411 .map(Path::to_path_buf)
412 .unwrap_or_else(downloads::downloads_directory);
413 match downloads::reveal_target(&path, path.exists(), folder) {
414 RevealTarget::File(path) => downloads::reveal_in_file_manager(&path),
415 RevealTarget::Folder(folder) => cx.open_with_system(&folder),
416 }
417 }
418 }
419 }
420
421 fn start_download(
422 &mut self,
423 key: DownloadKey,
424 card: FileCard,
425 source: DownloadSource,
426 cx: &mut Context<Self>,
427 ) {
428 if !self.downloads.begin(&key) {
429 return;
430 }
431 cx.notify();
432 let state = self.app.read(cx);
433 let (demo, engine) = (state.mode.demo, state.engine.clone());
434 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<DownloadEvent>();
435 if demo {
436 cx.spawn(async move |this, cx| {
437 for step in 1..=DEMO_DOWNLOAD_STEPS {
438 cx.background_executor().timer(DEMO_DOWNLOAD_STEP).await;
439 let percent = (u32::from(step) * 100 / u32::from(DEMO_DOWNLOAD_STEPS)) as u8;
440 let progressed = this.update(cx, |this, cx| {
441 this.downloads.set_progress(&key, percent);
442 cx.notify();
443 });
444 if progressed.is_err() {
445 return;
446 }
447 }
448 let outcome =
449 downloads::write_demo_file(&card.name).map_err(|error| short_error(&error));
450 this.update(cx, |this, cx| {
451 this.downloads.finish(&key, outcome);
452 cx.notify();
453 })
454 .ok();
455 })
456 .detach();
457 return;
458 }
459 let Some(engine) = engine else {
460 self.downloads.finish(&key, Err("not connected".to_owned()));
461 return;
462 };
463 drop(runtime::spawn(async move {
464 let outcome = save_file(&engine, &card, &source, &sender).await;
465 let _ = sender.send(DownloadEvent::Finished(outcome));
466 }));
467 cx.spawn(async move |this, cx| {
468 while let Some(event) = receiver.recv().await {
469 let updated = this.update(cx, |this, cx| {
470 match event {
471 DownloadEvent::Progress(percent) => {
472 this.downloads.set_progress(&key, percent)
473 }
474 DownloadEvent::Finished(outcome) => this.downloads.finish(&key, outcome),
475 }
476 cx.notify();
477 });
478 if updated.is_err() {
479 break;
480 }
481 }
482 })
483 .detach();
484 }
485
486 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
487 Self::build(app, None, window, cx)
488 }
489
490 pub fn timeline_bounds(&self) -> TimelineBounds {
491 self.timeline_bounds.clone()
492 }
493
494 pub fn pinned_to(
495 app: Entity<AppState>,
496 selection: Selection,
497 window: &mut Window,
498 cx: &mut Context<Self>,
499 ) -> Self {
500 Self::build(app, Some(selection), window, cx)
501 }
502
503 pub fn popped_out(
504 app: Entity<AppState>,
505 selection: Selection,
506 window: &mut Window,
507 cx: &mut Context<Self>,
508 ) -> Self {
509 let mut view = Self::build(app, Some(selection), window, cx);
510 view.popped_out = true;
511 view
512 }
513
514 fn build(
515 app: Entity<AppState>,
516 pinned: Option<Selection>,
517 window: &mut Window,
518 cx: &mut Context<Self>,
519 ) -> Self {
520 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
521 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
522 let subject = subject_input(window, cx);
523 let recap_search = recap::search_input(window, cx);
524 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
525 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
526 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
527 let mut subscriptions = vec![
528 cx.subscribe_in(&app, window, Self::on_app_event),
529 cx.observe(&app, |_, _, cx| cx.notify()),
530 cx.subscribe_in(&composer, window, Self::on_composer_event),
531 cx.subscribe_in(&draft, window, Self::on_draft_event),
532 cx.subscribe_in(&subject, window, Self::on_subject_event),
533 cx.subscribe_in(&recap_search, window, Self::on_recap_search_event),
534 cx.observe_window_activation(window, Self::on_window_activation),
535 cx.on_app_quit(|this, cx| {
536 this.composer
537 .update(cx, |composer, cx| composer.save_draft_now(cx));
538 async {}
539 }),
540 cx.observe_keystrokes(|this, event, _, cx| {
541 if event.keystroke.key == "escape" {
542 this.close_reaction_details(cx);
543 }
544 }),
545 ];
546 if let Some(runs) = crate::agents::runs_handle(cx) {
547 subscriptions.push(cx.observe(&runs, |this, _, cx| this.sync_agent_chips(cx)));
548 }
549 if let Some(api) = crate::agent_api::handle(cx) {
550 subscriptions.push(cx.observe(&api, |this, _, cx| this.sync_reaction_pills(cx)));
551 }
552 let mut view = ConversationView {
553 app,
554 pinned: pinned.is_some(),
555 popped_out: false,
556 scroller,
557 composer,
558 subject,
559 new_post_open: false,
560 reply_composer: None,
561 reply_root: None,
562 feed_stash: None,
563 feed_rows_seen: Rc::new(Cell::new(usize::MAX)),
564 feed_at_top: true,
565 draft,
566 draft_active: false,
567 draft_created: None,
568 draft_error: None,
569 rows: Rc::new(RefCell::new(Vec::new())),
570 current: None,
571 pending: Vec::new(),
572 pending_counter: 0,
573 pending_outgoing: HashMap::new(),
574 pending_reactions: HashMap::new(),
575 downloads: Downloads::default(),
576 hovered_message: None,
577 toolbar_hovered: None,
578 timeline_bounds: TimelineBounds::default(),
579 header_width: Rc::default(),
580 toolbar_pinned: None,
581 toolbar_suppressed: None,
582 recent,
583 picker,
584 reaction_details: None,
585 highlighted_message: None,
586 fetched_jump: None,
587 pin_index: 0,
588 channel_details_open: false,
589 pinned_posts_expanded: false,
590 channel_details_scroll: ScrollHandle::new(),
591 scroller_watch: None,
592 pin_previews: HashMap::new(),
593 pin_fetches: HashSet::new(),
594 notice: None,
595 scheduled_failure: None,
596 scheduled_in_flight: HashSet::new(),
597 drag_file_count: 0,
598 sync_generation: 0,
599 window_active: window.is_window_active(),
600 pane: ChannelPane::Posts,
601 recap: recap::RecapState::default(),
602 recap_search,
603 channel_tabs: Vec::new(),
604 tab_links: HashMap::new(),
605 focus_handle: cx.focus_handle(),
606 shared: SharedState::default(),
607 demo_library: DemoLibrary::default(),
608 new_folder_input: None,
609 agent_layouts: HashMap::new(),
610 agent_runs: Rc::new(RefCell::new(HashMap::new())),
611 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
612 receipt_fade: receipt_fade::ReceiptFade::default(),
613 find_panel: None,
614 find_subscription: None,
615 _subscriptions: subscriptions,
616 };
617 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
618 view.open(selection, window, cx);
619 }
620 view
621 }
622
623 #[cfg_attr(not(windows), allow(dead_code))]
624 pub fn composer_is_empty(&self, cx: &App) -> bool {
625 self.composer.read(cx).is_empty(cx)
626 }
627
628 #[cfg_attr(not(windows), allow(dead_code))]
629 pub fn send_in_flight(&self) -> bool {
630 self.pending
631 .iter()
632 .any(|row| matches!(row.delivery, Delivery::Sending))
633 }
634
635 fn on_window_activation(&mut self, window: &mut Window, cx: &mut Context<Self>) {
636 self.window_active = window.is_window_active();
637 self.mark_read(ReadTrigger::Activation, cx);
638 }
639
640 fn on_app_event(
641 &mut self,
642 _: &Entity<AppState>,
643 event: &AppEvent,
644 window: &mut Window,
645 cx: &mut Context<Self>,
646 ) {
647 match event {
648 AppEvent::Selection if self.pinned => {}
649 AppEvent::Selection => {
650 self.reaction_details = None;
651 let (new_chat, selection) = {
652 let state = self.app.read(cx);
653 (state.new_chat, state.selection.clone())
654 };
655 if new_chat {
656 self.enter_draft(window, cx);
657 return;
658 }
659 if self.draft_active {
660 let created = self
661 .draft_created
662 .as_ref()
663 .map(|(_, chat_id)| chat_id.clone());
664 if let Some(chat_id) = created {
665 self.composer
666 .update(cx, |composer, _| composer.carry_images_into(chat_id));
667 }
668 self.leave_draft(window, cx);
669 }
670 match selection {
671 Some(selection) => self.open(selection, window, cx),
672 None => {
673 self.current = None;
674 self.rebuild(true, cx);
675 }
676 }
677 }
678 AppEvent::Messages(conversation_id) => {
679 let is_current = self
680 .current
681 .as_ref()
682 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
683 if is_current {
684 if self.shared_active() || self.recap_active() || self.channel_details_open {
685 self.refresh_shared_items(cx);
686 }
687 self.rebuild(false, cx);
688 self.mark_read(ReadTrigger::Incoming, cx);
689 self.on_pins_changed(conversation_id, cx);
690 }
691 }
692 AppEvent::Images(keys) => self.remeasure_images(keys, cx),
693 AppEvent::Cards(conversation_id) => self.refresh_cards(conversation_id, cx),
694 AppEvent::Jump => self.apply_pending_jump(cx),
695 AppEvent::Status => {
696 if let Some(current) = self.current.as_mut()
697 && current.sync.failed
698 {
699 current.fetched = false;
700 }
701 self.start_fetch(cx)
702 }
703 AppEvent::Directory => {
704 self.refresh_reactor_names(cx);
705 cx.notify();
706 }
707 AppEvent::ForwardSelection => self.on_forward_selection_changed(window, cx),
708 AppEvent::TaskDialog
709 | AppEvent::LocalPreviews
710 | AppEvent::Forward
711 | AppEvent::ImageViewer
712 | AppEvent::StatusMessage
713 | AppEvent::Settings(_)
714 | AppEvent::Profile
715 | AppEvent::CallHistory
716 | AppEvent::Ring
717 | AppEvent::Activity
718 | AppEvent::MissedCall(_)
719 | AppEvent::MeetingReminder
720 | AppEvent::MeetingChime
721 | AppEvent::CallTone(_)
722 | AppEvent::SoundSettings
723 | AppEvent::FollowedStatus { .. }
724 | AppEvent::Call => {}
725 AppEvent::LiveMeeting => cx.notify(),
726 AppEvent::Saved => cx.notify(),
727 AppEvent::Translation | AppEvent::ChatSettings => self.rebuild(false, cx),
728 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
729 AppEvent::Typing => cx.notify(),
730 AppEvent::Scheduled => self.rebuild(false, cx),
731 AppEvent::Outbox(conversation_id) => {
732 let is_current = self
733 .current
734 .as_ref()
735 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
736 if is_current {
737 self.reload_pending(cx);
738 self.rebuild(false, cx);
739 }
740 }
741 AppEvent::Sidebar => {
742 self.reload_channel_tabs(cx);
743 self.mark_read(ReadTrigger::Incoming, cx);
744 self.refresh_reactor_names(cx);
745 if self.draft_active {
746 self.on_draft_changed(window, cx);
747 } else if let Some(current) = self.current.as_mut() {
748 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
749 if current.title != title {
750 current.title = title;
751 let conversation_id = current.selection.conversation_id().to_owned();
752 let name = composer_name(&self.app.read(cx).sidebar, &current.selection);
753 self.composer.update(cx, |composer, cx| {
754 composer.set_conversation(&conversation_id, &name, window, cx)
755 });
756 cx.notify();
757 }
758 }
759 }
760 }
761 }
762
763 fn on_composer_event(
764 &mut self,
765 _: &Entity<Composer>,
766 event: &ComposerEvent,
767 window: &mut Window,
768 cx: &mut Context<Self>,
769 ) {
770 self.report_composer_activity(event, cx);
771 match event {
772 ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx),
773 ComposerEvent::Schedule { outgoing, send_at } => {
774 self.schedule((**outgoing).clone(), *send_at, window, cx)
775 }
776 ComposerEvent::EditLast => self.edit_last_own(window, cx),
777 ComposerEvent::FocusMessages => window.focus(&self.focus_handle, cx),
778 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
779 ComposerEvent::Edited => {}
780 }
781 }
782
783 fn submit_main(&mut self, mut outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
784 if self.draft_active {
785 return self.send_new_chat(outgoing, window, cx);
786 }
787 let in_feed = self.in_feed();
788 if in_feed && outgoing.edit.is_none() {
789 outgoing.subject = self.take_subject(window, cx);
790 }
791 if in_feed {
792 self.close_new_post(cx);
793 }
794 match &outgoing.edit {
795 Some(edit) if edit.scheduled.is_some() => {
796 self.send_scheduled_edit(outgoing, window, cx)
797 }
798 Some(_) => self.send_edit(outgoing, window, cx),
799 None => self.send(outgoing, window, cx),
800 }
801 }
802
803 fn typing_root(&self) -> Option<String> {
804 match self.current.as_ref().map(|current| &current.mode) {
805 Some(ViewMode::Thread(root_id)) => Some(root_id.clone()),
806 _ => None,
807 }
808 }
809
810 fn send_typing(&self, active: bool, cx: &App) {
811 self.send_typing_in(self.typing_root(), active, cx);
812 }
813
814 fn send_typing_in(&self, thread_root_id: Option<String>, active: bool, cx: &App) {
815 let state = self.app.read(cx);
816 if state.mode.demo || state.mode.read_only || self.draft_active {
817 return;
818 }
819 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id())
820 else {
821 return;
822 };
823 drop(runtime::spawn(async move {
824 let sent = engine
825 .send_typing(&conversation_id, thread_root_id.as_deref(), active)
826 .await;
827 if let Err(error) = sent
828 && cfg!(debug_assertions)
829 {
830 crate::diagnostics::record(format!("typing indicator not sent: {error}"));
831 }
832 }));
833 }
834
835 fn stop_typing(&mut self, cx: &mut Context<Self>) {
836 if self
837 .composer
838 .update(cx, |composer, _| composer.stop_typing())
839 {
840 self.send_typing(false, cx);
841 }
842 }
843
844 fn render_typing_line(&self, cx: &App) -> impl IntoElement {
845 let app = self.app.read(cx);
846 let faces = self
847 .current
848 .as_ref()
849 .filter(|_| !self.draft_active)
850 .map(|current| app.typing.faces(current.selection.conversation_id()))
851 .unwrap_or_default();
852 let tooltip_text = typing_tooltip(
853 &faces
854 .iter()
855 .map(|face| face.name.clone())
856 .collect::<Vec<_>>(),
857 );
858 let flat = matches!(
859 self.current.as_ref().map(|current| &current.mode),
860 Some(ViewMode::Flat)
861 );
862 let faces_element = match faces.as_slice() {
863 [face] if flat => person_avatar(
864 &app.directory,
865 face.user_id.as_deref(),
866 &face.name,
867 AVATAR_SIZE,
868 ),
869 _ => member_stack(&app.directory, &faces, faces.len(), true).into_any_element(),
870 };
871 h_flex()
872 .h(px(if flat {
873 AVATAR_SIZE + 4.
874 } else {
875 TYPING_LINE_HEIGHT
876 }))
877 .flex_none()
878 .px(px(20.))
879 .gap(px(if flat { AVATAR_GAP } else { 6. }))
880 .items_center()
881 .when(!faces.is_empty(), |line| {
882 line.child(
883 div()
884 .id("typing-faces")
885 .tooltip(move |window, cx| {
886 Tooltip::new(tooltip_text.clone()).build(window, cx)
887 })
888 .child(faces_element),
889 )
890 .child(typing_dots())
891 })
892 }
893
894 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
895 if self
896 .find_panel
897 .as_ref()
898 .is_some_and(|panel| panel.read(cx).selection() != &selection)
899 {
900 self.find_panel = None;
901 self.find_subscription = None;
902 }
903 self.stop_typing(cx);
904 self.stop_reply_typing(cx);
905 self.new_post_open = false;
906 self.feed_stash = None;
907 self.feed_at_top = true;
908 self.restore_subject(None, window, cx);
909 self.toolbar_hovered = None;
910 self.toolbar_pinned = None;
911 self.toolbar_suppressed = None;
912 self.agent_layouts.clear();
913 self.agent_runs.borrow_mut().clear();
914 self.reaction_proposals.borrow_mut().clear();
915 let title = selection_title(&self.app.read(cx).sidebar, &selection);
916 let mode = match selection {
917 Selection::Chat(_) => ViewMode::Flat,
918 Selection::Channel(_) => ViewMode::ThreadList,
919 };
920 let first_unread = self.first_unread_id(&selection, cx);
921 let posts_new_after = self.channel_read_until(&selection, cx);
922 self.current = Some(Current {
923 loaded_limit: open_limit(&selection),
924 selection,
925 title,
926 mode,
927 loaded_count: 0,
928 has_older: false,
929 loading_older: false,
930 older_blocked: false,
931 fetched: false,
932 first_unread,
933 posts_new_after,
934 sync: SyncProgress::default(),
935 detached: None,
936 window_request: None,
937 });
938 self.refresh_agent_runs(cx);
939 self.refresh_reaction_pills(cx);
940 self.sync_generation += 1;
941 self.reset_channel_tabs(cx);
942 self.reset_recap(cx);
943 self.reload_pending(cx);
944 self.notice = None;
945 self.scheduled_failure = None;
946 self.app.update(cx, |state, cx| state.refresh_scheduled(cx));
947 self.rebuild(true, cx);
948 self.start_fetch(cx);
949 self.mark_read(ReadTrigger::Open, cx);
950 self.refresh_pin_previews(cx);
951 self.pinned_posts_expanded = false;
952 if let Some(conversation_id) = self.pin_conversation_id() {
953 self.app
954 .update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));
955 }
956 let target = self
957 .current
958 .as_ref()
959 .map(|current| {
960 (
961 current.selection.conversation_id().to_owned(),
962 composer_name(&self.app.read(cx).sidebar, &current.selection),
963 )
964 })
965 .unwrap_or_default();
966 self.composer.update(cx, |composer, cx| {
967 composer.set_conversation(&target.0, &target.1, window, cx);
968 });
969 self.sync_reply_composer(window, cx);
970 if !self.draft_active && !self.in_feed() {
971 self.composer
972 .update(cx, |composer, cx| composer.focus(window, cx));
973 }
974 self.hovered_message = None;
975 self.apply_pending_jump(cx);
976 }
977
978 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
979 if !self.draft_active {
980 self.stop_typing(cx);
981 self.draft_active = true;
982 self.current = None;
983 self.clear_pending();
984 self.notice = None;
985 self.draft_created = None;
986 self.draft_error = None;
987 self.toolbar_hovered = None;
988 self.toolbar_pinned = None;
989 self.toolbar_suppressed = None;
990 self.hovered_message = None;
991 self.sync_generation += 1;
992 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
993 self.composer.update(cx, |composer, cx| {
994 composer.set_conversation("", "", window, cx)
995 });
996 self.on_draft_changed(window, cx);
997 self.rebuild(true, cx);
998 }
999 let people = self
1000 .app
1001 .update(cx, |state, _| std::mem::take(&mut state.new_chat_people));
1002 if !people.is_empty() {
1003 let chips = people
1004 .into_iter()
1005 .filter_map(|person| {
1006 Some(Pick {
1007 user_id: person.user_id?,
1008 name: person.display_name,
1009 mail: None,
1010 })
1011 })
1012 .collect();
1013 self.draft
1014 .update(cx, |draft, cx| draft.set_chips(chips, cx));
1015 }
1016 self.draft
1017 .update(cx, |draft, cx| draft.focus_query(window, cx));
1018 cx.notify();
1019 }
1020
1021 fn leave_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1022 self.draft_active = false;
1023 self.draft_created = None;
1024 self.draft_error = None;
1025 self.clear_pending();
1026 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
1027 }
1028
1029 fn on_draft_event(
1030 &mut self,
1031 _: &Entity<NewChatDraft>,
1032 event: &NewChatEvent,
1033 window: &mut Window,
1034 cx: &mut Context<Self>,
1035 ) {
1036 match event {
1037 NewChatEvent::Changed => self.on_draft_changed(window, cx),
1038 NewChatEvent::FocusComposer => self
1039 .composer
1040 .update(cx, |composer, cx| composer.focus(window, cx)),
1041 NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)),
1042 }
1043 }
1044
1045 fn draft_target_chat(&self, cx: &App) -> Option<String> {
1046 let chips = self.draft.read(cx).chips();
1047 let [chip] = chips else {
1048 return None;
1049 };
1050 let state = self.app.read(cx);
1051 existing_one_on_one(
1052 &state.sidebar.chats,
1053 state.directory.me.as_ref(),
1054 &chip.user_id,
1055 )
1056 .map(|chat| chat.id.clone())
1057 }
1058
1059 fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1060 if !self.draft_active {
1061 return;
1062 }
1063 let target = self.draft_target_chat(cx);
1064 if target != self.conversation_id() {
1065 match target {
1066 Some(chat_id) => {
1067 self.composer.update(cx, |composer, _| {
1068 composer.carry_images_into(chat_id.clone())
1069 });
1070 self.open(Selection::Chat(chat_id), window, cx)
1071 }
1072 None => {
1073 self.composer.update(cx, |composer, cx| {
1074 composer.carry_images_into(String::new());
1075 composer.set_conversation("", "", window, cx);
1076 });
1077 self.current = None;
1078 self.sync_generation += 1;
1079 self.rebuild(true, cx);
1080 }
1081 }
1082 }
1083 let placeholder = {
1084 let draft = self.draft.read(cx);
1085 composer_placeholder(draft.chips(), &draft.group_name(cx))
1086 };
1087 self.composer.update(cx, |composer, cx| {
1088 composer.set_placeholder(&placeholder, window, cx)
1089 });
1090 cx.notify();
1091 }
1092
1093 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
1094 let indices: Vec<usize> = self
1095 .rows
1096 .borrow()
1097 .iter()
1098 .enumerate()
1099 .filter(|(_, row)| {
1100 row.messages().any(|message| {
1101 message.images.iter().any(|image| keys.contains(&image.url))
1102 || message
1103 .link_preview
1104 .as_ref()
1105 .and_then(LinkPreview::image)
1106 .is_some_and(|image| keys.contains(&image.url))
1107 })
1108 })
1109 .map(|(index, _)| index)
1110 .collect();
1111 self.scroller.update(cx, |scroller, cx| {
1112 for index in indices {
1113 scroller.remeasure_items(index..index + 1, cx);
1114 }
1115 });
1116 cx.notify();
1117 }
1118
1119 fn refresh_cards(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1120 let is_current = self
1121 .current
1122 .as_ref()
1123 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
1124 if !is_current {
1125 return;
1126 }
1127 self.rebuild(false, cx);
1128 let indices: Vec<usize> = self
1129 .rows
1130 .borrow()
1131 .iter()
1132 .enumerate()
1133 .filter(|(_, row)| {
1134 row.messages()
1135 .any(|message| !message.adaptive_cards.is_empty())
1136 })
1137 .map(|(index, _)| index)
1138 .collect();
1139 self.scroller.update(cx, |scroller, cx| {
1140 for index in indices {
1141 scroller.remeasure_items(index..index + 1, cx);
1142 }
1143 });
1144 cx.notify();
1145 }
1146
1147 fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {
1148 let Some(conversation_id) = self
1149 .current
1150 .as_ref()
1151 .map(|current| current.selection.conversation_id().to_owned())
1152 else {
1153 return;
1154 };
1155 let jump = self
1156 .app
1157 .update(cx, |state, _| match state.pending_jump.take() {
1158 Some((target, message_id)) if target == conversation_id => Some(message_id),
1159 other => {
1160 state.pending_jump = other;
1161 None
1162 }
1163 });
1164 if let Some(message_id) = jump {
1165 self.jump_to_message(&conversation_id, &message_id, cx);
1166 }
1167 }
1168
1169 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
1170 let store = self.app.read(cx).store.clone();
1171 let record = store
1172 .messages_by_id(conversation_id, &[message_id.to_owned()])
1173 .ok()
1174 .and_then(|mut found| found.remove(message_id));
1175 if self.chat_id().as_deref() == Some(conversation_id) {
1176 let created_at = record.as_ref().map(|record| record.created_at);
1177 match self.jump_plan_for(conversation_id, created_at, cx) {
1178 JumpPlan::LoadWindow => {
1179 self.open_detached(conversation_id.to_owned(), message_id.to_owned(), cx);
1180 return;
1181 }
1182 plan => {
1183 if let Some(current) = self.current.as_mut() {
1184 current.window_request = None;
1185 if plan == JumpPlan::LeaveWindow {
1186 current.detached = None;
1187 }
1188 }
1189 }
1190 }
1191 }
1192 let Some(record) = record else {
1193 self.open_unloaded_post(message_id, cx);
1194 return;
1195 };
1196 let messages_from_target = store
1197 .messages(conversation_id, None, JUMP_SCAN_LIMIT)
1198 .ok()
1199 .and_then(|all| {
1200 all.iter()
1201 .position(|candidate| candidate.message_id == message_id)
1202 .map(|position| all.len() - position)
1203 })
1204 .unwrap_or_default();
1205 let row_key = record
1206 .reply_to_id
1207 .clone()
1208 .unwrap_or_else(|| message_id.to_owned());
1209 let Some(current) = self.current.as_mut() else {
1210 return;
1211 };
1212 current.loaded_limit = current
1213 .loaded_limit
1214 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
1215 current.first_unread = None;
1216 let in_channel = matches!(current.selection, Selection::Channel(_));
1217 if in_channel {
1218 self.pane = ChannelPane::Posts;
1219 self.enter_feed_mode();
1220 }
1221 self.reload_pending(cx);
1222 self.rebuild(true, cx);
1223 self.reveal_row(row_key, message_id.to_owned(), cx);
1224 }
1225
1226 fn open_unloaded_post(&mut self, message_id: &str, cx: &mut Context<Self>) {
1227 let state = self.app.read(cx);
1228 let (Some(engine), Some(current)) = (state.engine.clone(), self.current.as_ref()) else {
1229 return;
1230 };
1231 if !matches!(current.selection, Selection::Channel(_))
1232 || state.mode.demo
1233 || self.fetched_jump.as_deref() == Some(message_id)
1234 {
1235 return;
1236 }
1237 self.fetched_jump = Some(message_id.to_owned());
1238 let conversation_id = current.selection.conversation_id().to_owned();
1239 let (task_conversation_id, task_message_id) = (conversation_id.clone(), message_id.to_owned());
1240 let receiver = runtime::spawn(async move {
1241 engine
1242 .refresh_message(&task_conversation_id, &task_message_id)
1243 .await
1244 });
1245 let message_id = message_id.to_owned();
1246 cx.spawn(async move |this, cx| {
1247 let Ok(Ok(Some(_))) = receiver.await else {
1248 return;
1249 };
1250 this.update(cx, |this, cx| {
1251 if this.conversation_id().as_deref() == Some(conversation_id.as_str()) {
1252 this.jump_to_message(&conversation_id, &message_id, cx);
1253 }
1254 })
1255 .ok();
1256 })
1257 .detach();
1258 }
1259
1260 fn reveal_row(&mut self, row_key: String, message_key: String, cx: &mut Context<Self>) {
1261 let index = self
1262 .rows
1263 .borrow()
1264 .iter()
1265 .position(|row| row.key() == row_key);
1266 if let Some(index) = index {
1267 self.scroller
1268 .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx));
1269 self.highlight(message_key, cx);
1270 }
1271 }
1272
1273 fn highlight(&mut self, key: String, cx: &mut Context<Self>) {
1274 self.highlighted_message = Some(key.clone());
1275 cx.notify();
1276 cx.spawn(async move |this, cx| {
1277 cx.background_executor().timer(JUMP_HIGHLIGHT_PERIOD).await;
1278 this.update(cx, |this, cx| {
1279 if this.highlighted_message.as_deref() == Some(key.as_str()) {
1280 this.highlighted_message = None;
1281 cx.notify();
1282 }
1283 })
1284 .ok();
1285 })
1286 .detach();
1287 }
1288
1289 pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1290 self.composer
1291 .update(cx, |composer, cx| composer.set_text(text, window, cx));
1292 self.composer
1293 .update(cx, |composer, cx| composer.focus(window, cx));
1294 }
1295
1296 pub fn focus_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1297 self.composer
1298 .update(cx, |composer, cx| composer.focus(window, cx));
1299 }
1300
1301 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1302 let key = self
1303 .rows
1304 .borrow()
1305 .iter()
1306 .rev()
1307 .flat_map(Row::messages)
1308 .find(|message| !message.own)
1309 .map(|message| message.key.clone());
1310 if let Some(key) = key {
1311 self.begin_reply(&key, window, cx);
1312 }
1313 }
1314
1315 pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1316 if let Some(message_id) = self.hovered_message.clone() {
1317 self.begin_reply(&message_id, window, cx);
1318 }
1319 }
1320
1321 fn reply_target(&self, message_id: &str, cx: &App) -> Option<(MessageRecord, ReplyPreview)> {
1322 let conversation_id = self.conversation_id()?;
1323 let record = self
1324 .app
1325 .read(cx)
1326 .store
1327 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1328 .ok()
1329 .and_then(|mut found| found.remove(message_id))
1330 .filter(|record| !record.deleted)?;
1331 let preview = ReplyPreview {
1332 message_id: record.message_id.clone(),
1333 author: record
1334 .sender_name
1335 .clone()
1336 .unwrap_or_else(|| "Unknown".to_owned()),
1337 excerpt: reply_excerpt(&record),
1338 };
1339 Some((record, preview))
1340 }
1341
1342 fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
1343 let Some((record, preview)) = self.reply_target(message_id, cx) else {
1344 return;
1345 };
1346 if self.in_feed() {
1347 let root_id = record
1348 .reply_to_id
1349 .clone()
1350 .unwrap_or_else(|| record.message_id.clone());
1351 self.open_reply_editor(root_id, Some(preview), window, cx);
1352 return;
1353 }
1354 self.composer.update(cx, |composer, cx| {
1355 composer.set_reply(Some(preview), cx);
1356 composer.focus(window, cx);
1357 });
1358 }
1359
1360 fn channel_read_until(&self, selection: &Selection, cx: &App) -> Option<DateTime<Utc>> {
1361 let Selection::Channel(channel_id) = selection else {
1362 return None;
1363 };
1364 let state = self.app.read(cx);
1365 if state.mode.demo {
1366 return crate::demo::channel_read_until(channel_id);
1367 }
1368 state.engine.as_ref()?.channel_read_until(channel_id)
1369 }
1370
1371 fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> {
1372 let Selection::Chat(chat_id) = selection else {
1373 return None;
1374 };
1375 let state = self.app.read(cx);
1376 if state.mode.demo {
1377 return crate::demo::first_unread(chat_id);
1378 }
1379 state.engine.as_ref()?.first_unread_message_id(chat_id)
1380 }
1381
1382 fn row_context(&self, cx: &App) -> RowContext {
1383 let now = Local::now();
1384 let app = self.app.read(cx);
1385 let names = local_names(app);
1386 let card_overrides = self
1387 .current
1388 .as_ref()
1389 .map(|current| app.cards.overrides_for(current.selection.conversation_id()))
1390 .unwrap_or_default();
1391 let translation = self
1392 .current
1393 .as_ref()
1394 .map(|current| {
1395 app.translation
1396 .context_for(current.selection.conversation_id())
1397 })
1398 .unwrap_or_default();
1399 RowContext {
1400 offset: now.offset().fix(),
1401 today: now.date_naive(),
1402 my_user_id: app.store.meta(META_USER_ID).ok().flatten(),
1403 names,
1404 pending_reactions: self.pending_reactions.clone(),
1405 card_overrides,
1406 translation,
1407 skin_tone: teams_core::skin_tone(&app.store),
1408 meeting: self.meeting_info(app),
1409 }
1410 }
1411
1412 fn unknown_reactor_ids(&self) -> Vec<String> {
1413 self.rows
1414 .borrow()
1415 .iter()
1416 .flat_map(Row::messages)
1417 .flat_map(|message| message.reactions.iter())
1418 .flat_map(|chip| chip.reactors.iter())
1419 .filter(|reactor| reactor.name == UNKNOWN_REACTOR)
1420 .filter_map(|reactor| reactor.user_id.clone())
1421 .collect()
1422 }
1423
1424 fn refresh_reactor_names(&mut self, cx: &mut Context<Self>) {
1425 if self.current.is_none() {
1426 return;
1427 }
1428 let unknown = self.unknown_reactor_ids();
1429 if unknown.is_empty() {
1430 return;
1431 }
1432 let names = resolve_names(self.app.read(cx), &unknown);
1433 if !names.is_empty() {
1434 self.rebuild(false, cx);
1435 }
1436 }
1437
1438 fn drop_stale_reaction_details(&mut self) {
1439 let Some(details) = self.reaction_details.as_ref() else {
1440 return;
1441 };
1442 let present = self
1443 .rows
1444 .borrow()
1445 .iter()
1446 .flat_map(Row::messages)
1447 .any(|message| {
1448 message.key == details.message_key
1449 && message
1450 .reactions
1451 .iter()
1452 .any(|chip| chip.glyph() == details.anchor_glyph)
1453 });
1454 if !present {
1455 self.reaction_details = None;
1456 }
1457 }
1458
1459 fn open_reaction_details(&mut self, message_key: &str, glyph: &str, cx: &mut Context<Self>) {
1460 let multiple_kinds = self
1461 .rows
1462 .borrow()
1463 .iter()
1464 .flat_map(Row::messages)
1465 .any(|message| message.key == message_key && message.reactions.len() > 1);
1466 self.reaction_details = Some(ReactionDetails {
1467 message_key: message_key.to_owned(),
1468 anchor_glyph: glyph.to_owned(),
1469 tab: multiple_kinds.then(|| glyph.to_owned()),
1470 });
1471 cx.notify();
1472 }
1473
1474 fn select_reaction_tab(&mut self, tab: Option<String>, cx: &mut Context<Self>) {
1475 if let Some(details) = self.reaction_details.as_mut() {
1476 details.tab = tab;
1477 cx.notify();
1478 }
1479 }
1480
1481 fn close_reaction_details(&mut self, cx: &mut Context<Self>) {
1482 if self.reaction_details.take().is_some() {
1483 cx.notify();
1484 }
1485 }
1486
1487 fn reaction_controls(&self, key: &str, view: WeakEntity<Self>) -> ReactionControls {
1488 let open = {
1489 let (view, key) = (view.clone(), key.to_owned());
1490 Rc::new(move |glyph: &str, cx: &mut App| {
1491 view.update(cx, |this, cx| this.open_reaction_details(&key, glyph, cx))
1492 .ok();
1493 })
1494 };
1495 let select_tab = {
1496 let view = view.clone();
1497 Rc::new(move |tab: Option<String>, cx: &mut App| {
1498 view.update(cx, |this, cx| this.select_reaction_tab(tab, cx))
1499 .ok();
1500 })
1501 };
1502 let close = Rc::new(move |cx: &mut App| {
1503 view.update(cx, |this, cx| this.close_reaction_details(cx))
1504 .ok();
1505 });
1506 let popover = self
1507 .reaction_details
1508 .as_ref()
1509 .filter(|details| details.message_key == key)
1510 .map(|details| ReactionPopover {
1511 anchor_glyph: details.anchor_glyph.clone(),
1512 tab: details.tab.clone(),
1513 });
1514 ReactionControls {
1515 open,
1516 select_tab,
1517 close,
1518 popover,
1519 }
1520 }
1521
1522 fn start_info(&self, cx: &App) -> Option<StartInfo> {
1523 let current = self.current.as_ref()?;
1524 let app = self.app.read(cx);
1525 let (user_id, member_name, notes) = match &current.selection {
1526 Selection::Chat(chat_id) => {
1527 let member = app
1528 .sidebar
1529 .chats
1530 .iter()
1531 .find(|chat| &chat.id == chat_id)
1532 .filter(|chat| is_one_on_one(chat))
1533 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next());
1534 let (user_id, name) = member.unzip();
1535 (user_id.flatten(), name, is_notes_chat(chat_id))
1536 }
1537 Selection::Channel(_) => (None, None, false),
1538 };
1539 Some(StartInfo {
1540 title: current.title.clone(),
1541 user_id,
1542 avatar_name: member_name
1543 .filter(|name| !name.is_empty())
1544 .unwrap_or_else(|| current.title.clone()),
1545 notes,
1546 })
1547 }
1548
1549 fn notes_space(&self) -> Option<StartInfo> {
1550 match self.rows.borrow().as_slice() {
1551 [Row::Start(start)] if start.notes => Some(start.clone()),
1552 _ => None,
1553 }
1554 }
1555
1556 fn watch_feed_scroll(&mut self, cx: &mut Context<Self>) {
1557 let scroller_id = self.scroller.entity_id();
1558 if self
1559 .scroller_watch
1560 .as_ref()
1561 .is_some_and(|(watched, _)| *watched == scroller_id)
1562 {
1563 return;
1564 }
1565 let subscription = cx.observe(&self.scroller, |this, _, cx| {
1566 if this.in_feed() {
1567 cx.notify();
1568 }
1569 });
1570 self.scroller_watch = Some((scroller_id, subscription));
1571 }
1572
1573 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
1574 let Some(current) = self.current.as_ref() else {
1575 let mut rows: Vec<Row> = self
1576 .pending
1577 .iter()
1578 .cloned()
1579 .map(|row| Row::Message(Box::new(row)))
1580 .collect();
1581 assign_series(&mut rows);
1582 self.apply_rows(rows, true, cx);
1583 return;
1584 };
1585 let conversation_id = current.selection.conversation_id().to_owned();
1586 let limit = if reset {
1587 current.loaded_limit
1588 } else {
1589 current
1590 .loaded_limit
1591 .max(current.loaded_count + GROWTH_HEADROOM)
1592 };
1593 let store = self.app.read(cx).store.clone();
1594 let thread_root = match &current.mode {
1595 ViewMode::Thread(root_id) => Some(root_id.clone()),
1596 ViewMode::Flat | ViewMode::ThreadList => None,
1597 };
1598 let sync_state = store.sync_state(&conversation_id).ok().flatten();
1599 let window = current.detached.as_ref().map(|detached| {
1600 (
1601 detached.oldest,
1602 detached.newest,
1603 detached.older_cursor.is_some(),
1604 detached.newer_cursor.is_some(),
1605 )
1606 });
1607 let records: Vec<MessageRecord> = match (&thread_root, window) {
1608 (Some(root_id), _) => store
1609 .thread_messages(&conversation_id, root_id)
1610 .unwrap_or_default(),
1611 (None, Some((oldest, newest, _, _))) => store
1612 .messages_between(&conversation_id, oldest, newest)
1613 .unwrap_or_default(),
1614 (None, None) if matches!(current.selection, Selection::Chat(_)) => without_islands(
1615 store
1616 .messages(&conversation_id, None, limit)
1617 .unwrap_or_default(),
1618 sync_state.as_ref().and_then(|state| state.oldest_loaded),
1619 ),
1620 (None, None) => store
1621 .messages(&conversation_id, None, limit)
1622 .unwrap_or_default(),
1623 };
1624 let sync_has_more = sync_state.as_ref().is_none_or(|state| state.has_more);
1625 let mut context = self.row_context(cx);
1626 let unnamed_ids: Vec<String> = records
1627 .iter()
1628 .flat_map(teams_core::reactions)
1629 .filter(|reaction| reaction.user_name.is_none())
1630 .filter_map(|reaction| reaction.user_id)
1631 .chain(forward_sender_ids(&records))
1632 .filter(|user_id| !context.names.contains_key(user_id))
1633 .collect();
1634 for (user_id, name) in resolve_names(self.app.read(cx), &unnamed_ids) {
1635 context.names.entry(user_id).or_insert(name);
1636 }
1637 for record in &records {
1638 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
1639 context
1640 .names
1641 .entry(user_id.clone())
1642 .or_insert_with(|| name.clone());
1643 }
1644 }
1645 let can_load_older = self.app.read(cx).engine.is_some();
1646 let start = self.start_info(cx);
1647 let current = self.current.as_mut().expect("checked above");
1648 let first_unread = current.first_unread.clone();
1649 let posts_new_after = current.posts_new_after;
1650 current.loaded_limit = limit;
1651 if thread_root.is_none() {
1652 current.loaded_count = records.len();
1653 }
1654 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1655 let placeholders = current.sync.messages
1656 && records.is_empty()
1657 && !matches!(current.mode, ViewMode::Thread(_));
1658 let in_feed = current.mode == ViewMode::ThreadList;
1659 let mut rows = match &current.mode {
1660 _ if placeholders => {
1661 current.has_older = false;
1662 placeholder_rows()
1663 }
1664 ViewMode::Flat => match window {
1665 Some((_, _, has_older_window, has_newer_window)) => {
1666 current.has_older = has_older_window;
1667 let mut rows = flat_rows(&records, &context, has_older_window);
1668 if has_newer_window {
1669 rows.push(Row::LoadNewer);
1670 }
1671 rows
1672 }
1673 None => {
1674 current.has_older = has_older;
1675 let mut rows = flat_rows(&records, &context, has_older);
1676 if !has_older && let Some(start) = start {
1677 rows.insert(0, Row::Start(start));
1678 }
1679 rows
1680 }
1681 },
1682 ViewMode::ThreadList => {
1683 current.has_older = has_older;
1684 thread_list_rows(&records, &context, has_older)
1685 }
1686 ViewMode::Thread(root_id) => {
1687 current.has_older = false;
1688 thread_rows(&records, root_id, &context)
1689 }
1690 };
1691 let local: Vec<MessageRow> = if window.is_some() {
1692 Vec::new()
1693 } else {
1694 self.pending
1695 .iter()
1696 .cloned()
1697 .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx))
1698 .collect()
1699 };
1700 if in_feed {
1701 place_local_rows(&mut rows, local);
1702 } else {
1703 rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row))));
1704 }
1705 let (mut receipts, receipt_labels) = self.receipts(&records, cx);
1706 if self.track_receipt_fades(&mut receipts) {
1707 self.schedule_fade_end(cx);
1708 }
1709 for row in rows.iter_mut() {
1710 if let Row::Message(message) = row
1711 && message.own
1712 {
1713 message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
1714 message.receipt_label = receipt_labels.get(&message.key).cloned();
1715 }
1716 }
1717 if let Some(read_until) = posts_new_after.filter(|_| in_feed) {
1718 for row in rows.iter_mut() {
1719 if let Row::Post(post) = row {
1720 post.mark_new_after(read_until);
1721 }
1722 }
1723 }
1724 if let Some(unread_id) = &first_unread {
1725 for row in rows.iter_mut() {
1726 if let Row::Message(message) = row
1727 && &message.key == unread_id
1728 {
1729 message.new_marker = true;
1730 }
1731 }
1732 }
1733 assign_series(&mut rows);
1734 self.apply_rows(rows, reset, cx);
1735 if self.is_detached() {
1736 self.scroller
1737 .update(cx, |scroller, _| scroller.stop_following());
1738 }
1739 }
1740
1741 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
1742 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
1743 self.drop_stale_reaction_details();
1744 let new_len = self.rows.borrow().len();
1745 let in_feed = self.in_feed();
1746 if reset {
1747 let marker_index = self
1748 .rows
1749 .borrow()
1750 .iter()
1751 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
1752 self.feed_at_top = true;
1753 self.scroller.update(cx, |scroller, cx| {
1754 scroller.reset(new_len, cx);
1755 if in_feed {
1756 scroller.scroll_to_item(0, cx);
1757 return;
1758 }
1759 match marker_index {
1760 Some(index) if !scroller.scroll_to_item(index, cx) => {
1761 scroller.scroll_to_end(cx)
1762 }
1763 Some(_) => {}
1764 None => scroller.scroll_to_end(cx),
1765 }
1766 });
1767 cx.notify();
1768 return;
1769 }
1770 let (splice, changed) = {
1771 let new_rows = self.rows.borrow();
1772 let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect();
1773 let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect();
1774 (
1775 diff_keys(&old_keys, &new_keys),
1776 changed_indices(&old_rows, &new_rows),
1777 )
1778 };
1779 let top_changed = splice
1780 .as_ref()
1781 .is_some_and(|splice| splice.range.start == 0);
1782 let keep_top = in_feed && (old_rows.is_empty() || (self.feed_at_top && top_changed));
1783 self.scroller.update(cx, |scroller, cx| {
1784 if let Some(splice) = splice
1785 && !scroller.splice(splice.range, splice.count, cx)
1786 {
1787 scroller.reset(new_len, cx);
1788 }
1789 if keep_top {
1790 scroller.scroll_to_item(0, cx);
1791 }
1792 for index in changed {
1793 scroller.remeasure_items(index..index + 1, cx);
1794 }
1795 });
1796 cx.notify();
1797 }
1798
1799 fn start_fetch(&mut self, cx: &mut Context<Self>) {
1800 let state = self.app.read(cx);
1801 let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync);
1802 if engine.is_none() && demo_sync.is_none() {
1803 return;
1804 }
1805 let Some(current) = self.current.as_mut() else {
1806 return;
1807 };
1808 if current.fetched {
1809 return;
1810 }
1811 current.fetched = true;
1812 let is_chat = matches!(current.selection, Selection::Chat(_));
1813 let newest_cached = self
1814 .rows
1815 .borrow()
1816 .iter()
1817 .flat_map(Row::messages)
1818 .filter(|message| !message.key.starts_with(PENDING_KEY_PREFIX))
1819 .map(|message| message.created_at)
1820 .max();
1821 let current = self.current.as_mut().expect("checked above");
1822 if current.sync.failed {
1823 self.notice = None;
1824 }
1825 current.sync = SyncProgress {
1826 messages: true,
1827 receipts: is_chat,
1828 empty_cache: newest_cached.is_none(),
1829 newest_cached,
1830 started_at: Utc::now(),
1831 ..SyncProgress::default()
1832 };
1833 self.sync_generation += 1;
1834 let generation = self.sync_generation;
1835 let conversation_id = current.selection.conversation_id().to_owned();
1836 match (engine, demo_sync) {
1837 (Some(engine), _) => {
1838 let receiver =
1839 runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
1840 cx.spawn(async move |this, cx| {
1841 let result = receiver.await;
1842 this.update(cx, |this, cx| this.finish_fetch(generation, result, cx))
1843 .ok();
1844 })
1845 .detach();
1846 }
1847 (None, Some(delay)) => self.simulate_sync(generation, delay, cx),
1848 (None, None) => {}
1849 }
1850 self.schedule_progress(generation, cx);
1851 self.rebuild(false, cx);
1852 self.mark_read(ReadTrigger::Incoming, cx);
1853 self.refresh_receipts(generation, cx);
1854 }
1855
1856 fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) {
1857 cx.spawn(async move |this, cx| {
1858 cx.background_executor().timer(delay).await;
1859 this.update(cx, |this, cx| {
1860 if let Some(sync) = this.sync_of(generation) {
1861 sync.receipts = false;
1862 }
1863 this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx)
1864 })
1865 .ok();
1866 })
1867 .detach();
1868 }
1869
1870 fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> {
1871 if generation != self.sync_generation {
1872 return None;
1873 }
1874 self.current.as_mut().map(|current| &mut current.sync)
1875 }
1876
1877 fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1878 cx.spawn(async move |this, cx| {
1879 let stages = [
1880 (PROGRESS_DELAY, Duration::ZERO),
1881 (SLOW_AFTER, PROGRESS_DELAY),
1882 ];
1883 for (stage, (at, previous)) in stages.into_iter().enumerate() {
1884 cx.background_executor().timer(at - previous).await;
1885 let running = this
1886 .update(cx, |this, cx| this.advance_progress(generation, stage, cx))
1887 .unwrap_or(false);
1888 if !running {
1889 return;
1890 }
1891 }
1892 })
1893 .detach();
1894 }
1895
1896 fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool {
1897 let Some(sync) = self.sync_of(generation) else {
1898 return false;
1899 };
1900 if !sync.running() {
1901 return false;
1902 }
1903 match stage {
1904 0 => sync.shown_at = Some(Instant::now()),
1905 _ => sync.slow = true,
1906 }
1907 cx.notify();
1908 true
1909 }
1910
1911 fn finish_fetch(
1912 &mut self,
1913 generation: u64,
1914 result: Result<
1915 teams_core::Result<teams_core::Delta>,
1916 tokio::sync::oneshot::error::RecvError,
1917 >,
1918 cx: &mut Context<Self>,
1919 ) {
1920 let Some(sync) = self.sync_of(generation) else {
1921 return;
1922 };
1923 sync.messages = false;
1924 let (newest_cached, started_at) = (sync.newest_cached, sync.started_at);
1925 match result {
1926 Ok(Ok(_)) => self.mark_fetched_new(newest_cached, started_at, cx),
1927 Ok(Err(error)) => self.fail_sync(generation, short_error(&error)),
1928 Err(error) => self.fail_sync(generation, short_error(&error)),
1929 }
1930 self.rebuild(false, cx);
1931 self.settle_progress(generation, cx);
1932 }
1933
1934 fn fail_sync(&mut self, generation: u64, error: String) {
1935 if let Some(sync) = self.sync_of(generation) {
1936 sync.failed = true;
1937 sync.receipts = false;
1938 }
1939 self.notice = Some(format!("Could not refresh: {error}"));
1940 }
1941
1942 fn mark_fetched_new(
1943 &mut self,
1944 newest_cached: Option<DateTime<Utc>>,
1945 started_at: DateTime<Utc>,
1946 cx: &mut Context<Self>,
1947 ) {
1948 let Some(newest_cached) = newest_cached else {
1949 return;
1950 };
1951 let Some(my_user_id) = self.row_context(cx).my_user_id else {
1952 return;
1953 };
1954 let store = self.app.read(cx).store.clone();
1955 let Some(current) = self.current.as_mut() else {
1956 return;
1957 };
1958 if current.first_unread.is_some() || current.mode != ViewMode::Flat {
1959 return;
1960 }
1961 let limit = current
1962 .loaded_limit
1963 .max(current.loaded_count + GROWTH_HEADROOM);
1964 current.first_unread = store
1965 .messages(current.selection.conversation_id(), None, limit)
1966 .unwrap_or_default()
1967 .into_iter()
1968 .find(|record| {
1969 missed_before_fetch(record.created_at, newest_cached, started_at)
1970 && record.sender_id.as_ref() != Some(&my_user_id)
1971 })
1972 .map(|record| record.message_id);
1973 }
1974
1975 fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1976 let Some(sync) = self.sync_of(generation) else {
1977 return;
1978 };
1979 if sync.running() {
1980 return;
1981 }
1982 let remaining = sync
1983 .shown_at
1984 .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed()))
1985 .unwrap_or_default();
1986 if remaining.is_zero() {
1987 sync.shown_at = None;
1988 sync.slow = false;
1989 cx.notify();
1990 return;
1991 }
1992 cx.spawn(async move |this, cx| {
1993 cx.background_executor().timer(remaining).await;
1994 this.update(cx, |this, cx| {
1995 if let Some(sync) = this.sync_of(generation) {
1996 sync.shown_at = None;
1997 sync.slow = false;
1998 cx.notify();
1999 }
2000 })
2001 .ok();
2002 })
2003 .detach();
2004 }
2005
2006 fn retry_fetch(&mut self, cx: &mut Context<Self>) {
2007 if let Some(current) = self.current.as_mut() {
2008 current.fetched = false;
2009 }
2010 self.start_fetch(cx);
2011 }
2012
2013 fn receipts(
2014 &self,
2015 records: &[MessageRecord],
2016 cx: &App,
2017 ) -> (HashMap<String, Receipt>, HashMap<String, String>) {
2018 let settings = self.app.read(cx).account_chat_settings();
2019 let (mut receipts, mut labels) = self.raw_receipts(records, cx);
2020 for receipt in receipts.values_mut() {
2021 *receipt = shown_receipt(&settings, *receipt);
2022 }
2023 labels.retain(|key, _| receipts.get(key).is_some_and(|receipt| *receipt != Receipt::Hidden));
2024 (receipts, labels)
2025 }
2026
2027 fn raw_receipts(
2028 &self,
2029 records: &[MessageRecord],
2030 cx: &App,
2031 ) -> (HashMap<String, Receipt>, HashMap<String, String>) {
2032 let state = self.app.read(cx);
2033 if state.mode.demo {
2034 let read_ids = crate::demo::read_message_ids(records);
2035 let receipts: HashMap<String, Receipt> = records
2036 .iter()
2037 .map(|record| {
2038 let receipt = if read_ids.contains(&record.message_id) {
2039 Receipt::Read
2040 } else {
2041 Receipt::Sent
2042 };
2043 (record.message_id.clone(), receipt)
2044 })
2045 .collect();
2046 let labels = receipts
2047 .iter()
2048 .map(|(key, receipt)| {
2049 let label = if *receipt == Receipt::Read { "Seen" } else { "Sent" };
2050 (key.clone(), label.to_owned())
2051 })
2052 .collect();
2053 return (receipts, labels);
2054 }
2055 let Some(engine) = state.engine.as_ref() else {
2056 return (HashMap::new(), HashMap::new());
2057 };
2058 let mut receipts = HashMap::new();
2059 let mut labels = HashMap::new();
2060 for record in records {
2061 let receipt_state = engine.receipt_state_for(record);
2062 if let Some(label) = crate::rows::receipt_label(&receipt_state) {
2063 labels.insert(record.message_id.clone(), label);
2064 }
2065 let receipt = match receipt_state {
2066 teams_core::ReceiptState::Read { .. } => Receipt::Read,
2067 teams_core::ReceiptState::Sent => Receipt::Sent,
2068 teams_core::ReceiptState::Unknown => Receipt::Hidden,
2069 };
2070 receipts.insert(record.message_id.clone(), receipt);
2071 }
2072 (receipts, labels)
2073 }
2074
2075 fn track_receipt_fades(&mut self, receipts: &mut HashMap<String, Receipt>) -> bool {
2076 let Some(current) = self.current.as_ref() else {
2077 return false;
2078 };
2079 let settled = !current.sync.receipts;
2080 let conversation_id = current.selection.conversation_id().to_owned();
2081 self.receipt_fade
2082 .apply(&conversation_id, settled, receipts, Instant::now())
2083 }
2084
2085 fn schedule_fade_end(&mut self, cx: &mut Context<Self>) {
2086 cx.spawn(async move |this, cx| {
2087 cx.background_executor()
2088 .timer(receipt_fade::RECEIPT_FADE)
2089 .await;
2090 this.update(cx, |this, cx| this.rebuild(false, cx)).ok();
2091 })
2092 .detach();
2093 }
2094
2095 fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {
2096 let state = self.app.read(cx);
2097 let (Some(engine), Some(Selection::Chat(chat_id))) = (
2098 state.engine.clone(),
2099 self.current.as_ref().map(|c| c.selection.clone()),
2100 ) else {
2101 return;
2102 };
2103 let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await });
2104 cx.spawn(async move |this, cx| {
2105 receiver.await.ok();
2106 this.update(cx, |this, cx| {
2107 let Some(sync) = this.sync_of(generation) else {
2108 return;
2109 };
2110 sync.receipts = false;
2111 this.rebuild(false, cx);
2112 this.settle_progress(generation, cx);
2113 })
2114 .ok();
2115 })
2116 .detach();
2117 }
2118
2119 fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) {
2120 if self.draft_active {
2121 return;
2122 }
2123 let state = self.app.read(cx);
2124 if state.viewing_call() && !self.pinned {
2125 return;
2126 }
2127 let Some(selection) = self.current.as_ref().map(|c| c.selection.clone()) else {
2128 return;
2129 };
2130 if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only {
2131 return;
2132 }
2133 let unread = match &selection {
2134 Selection::Chat(chat_id) => {
2135 state
2136 .sidebar
2137 .chats
2138 .iter()
2139 .any(|chat| &chat.id == chat_id && chat.unread)
2140 && !state.keeps_unread(chat_id)
2141 }
2142 Selection::Channel(channel_id) => channel_unread(&state.sidebar, channel_id),
2143 };
2144 let Some(plan) = plan_read(self.window_active, unread, trigger) else {
2145 return;
2146 };
2147 self.app.update(cx, |state, cx| match &selection {
2148 Selection::Chat(chat_id) => {
2149 state.ack_urgent_messages(chat_id, cx);
2150 state.mark_chat_read(chat_id, cx)
2151 }
2152 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
2153 });
2154 if plan.clear_divider
2155 && let Some(current) = self.current.as_mut()
2156 && current.first_unread.take().is_some()
2157 {
2158 self.rebuild(false, cx);
2159 }
2160 }
2161
2162 fn request_older(&mut self, cx: &mut Context<Self>) {
2163 if self.is_detached() {
2164 return self.request_window_page(WindowDirection::Backward, cx);
2165 }
2166 let Some(engine) = self.app.read(cx).engine.clone() else {
2167 return;
2168 };
2169 let Some(current) = self.current.as_mut() else {
2170 return;
2171 };
2172 if current.loading_older || current.older_blocked || !current.has_older {
2173 return;
2174 }
2175 current.loading_older = true;
2176 let conversation_id = current.selection.conversation_id().to_owned();
2177 let task_id = conversation_id.clone();
2178 let receiver = runtime::spawn(async move { engine.load_older(&task_id).await });
2179 cx.spawn(async move |this, cx| {
2180 let result = receiver.await;
2181 this.update(cx, |this, cx| {
2182 this.finish_older(&conversation_id, result, cx)
2183 })
2184 .ok();
2185 })
2186 .detach();
2187 }
2188
2189 fn finish_older(
2190 &mut self,
2191 conversation_id: &str,
2192 result: Result<
2193 teams_core::Result<Vec<MessageRecord>>,
2194 tokio::sync::oneshot::error::RecvError,
2195 >,
2196 cx: &mut Context<Self>,
2197 ) {
2198 let Some(current) = self.current.as_mut() else {
2199 return;
2200 };
2201 if current.selection.conversation_id() != conversation_id {
2202 return;
2203 }
2204 current.loading_older = false;
2205 match result {
2206 Ok(Ok(records)) if !records.is_empty() => {
2207 current.loaded_limit = current.loaded_count + records.len();
2208 }
2209 Ok(Ok(_)) => current.older_blocked = true,
2210 Ok(Err(error)) => {
2211 current.older_blocked = true;
2212 self.notice = Some(format!(
2213 "Could not load older messages: {}",
2214 short_error(&error)
2215 ));
2216 }
2217 Err(_) => current.older_blocked = true,
2218 }
2219 self.rebuild(false, cx);
2220 }
2221
2222 fn clear_pending(&mut self) {
2223 self.pending.clear();
2224 self.pending_outgoing.clear();
2225 }
2226
2227 fn outbox_route(&self, reply_root: Option<String>) -> (OutboxTarget, Option<String>) {
2228 if let Some(root_id) = reply_root {
2229 return (OutboxTarget::Thread, Some(root_id));
2230 }
2231 match self.current.as_ref().map(|current| &current.mode) {
2232 Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())),
2233 Some(ViewMode::ThreadList) => (OutboxTarget::Post, None),
2234 _ => (OutboxTarget::Flat, None),
2235 }
2236 }
2237
2238 fn reload_pending(&mut self, cx: &App) {
2239 self.clear_pending();
2240 let state = self.app.read(cx);
2241 if state.mode.demo || state.mode.read_only {
2242 return;
2243 }
2244 let Some(current) = self.current.as_ref() else {
2245 return;
2246 };
2247 let conversation_id = current.selection.conversation_id().to_owned();
2248 let Ok(records) = state.store.outbox_for_conversation(&conversation_id) else {
2249 return;
2250 };
2251 let my_user_id = state.store.meta(META_USER_ID).ok().flatten();
2252 let mut pending = Vec::new();
2253 for record in records {
2254 if !shown_in_view(&current.mode, &record) {
2255 continue;
2256 }
2257 let Some(outgoing) = outgoing_of(&record) else {
2258 continue;
2259 };
2260 let delivery = match record.state {
2261 OutboxState::Sending => Delivery::Sending,
2262 OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()),
2263 };
2264 let mut row = pending_row(
2265 record.id.clone(),
2266 conversation_id.clone(),
2267 my_user_id.clone(),
2268 record.created_at,
2269 &outgoing,
2270 delivery,
2271 );
2272 row.reply_root = record.thread_root_id.clone();
2273 pending.push((row, record.id, outgoing));
2274 }
2275 for (row, id, outgoing) in pending {
2276 self.pending.push(row);
2277 self.pending_outgoing.insert(id, outgoing);
2278 }
2279 }
2280
2281 fn discard_outbox_row(&self, id: &str, cx: &mut Context<Self>) {
2282 self.app.read(cx).store.delete_outbox(id).ok();
2283 self.app
2284 .update(cx, |state, cx| state.refresh_local_previews(cx));
2285 }
2286
2287 fn delete_pending(&mut self, key: &str, cx: &mut Context<Self>) {
2288 self.pending.retain(|row| row.key != key);
2289 self.pending_outgoing.remove(key);
2290 self.discard_outbox_row(key, cx);
2291 self.rebuild(false, cx);
2292 }
2293
2294 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2295 self.leave_detached(cx);
2296 self.send_as(new_outbox_id(), outgoing, None, window, cx);
2297 }
2298
2299 fn send_in_thread(
2300 &mut self,
2301 root_id: String,
2302 outgoing: Outgoing,
2303 window: &mut Window,
2304 cx: &mut Context<Self>,
2305 ) {
2306 self.send_as(new_outbox_id(), outgoing, Some(root_id), window, cx);
2307 }
2308
2309 fn send_as(
2310 &mut self,
2311 id: String,
2312 outgoing: Outgoing,
2313 reply_root: Option<String>,
2314 window: &mut Window,
2315 cx: &mut Context<Self>,
2316 ) {
2317 let state = self.app.read(cx);
2318 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2319 let Some(current) = self.current.as_ref() else {
2320 return;
2321 };
2322 if mode.read_only || mode.demo {
2323 self.restore_unsent(
2324 "Read-only mode: nothing was sent",
2325 &outgoing,
2326 reply_root.as_deref(),
2327 window,
2328 cx,
2329 );
2330 return;
2331 }
2332 let Some(engine) = engine else {
2333 self.discard_outbox_row(&id, cx);
2334 self.restore_unsent(
2335 "Not connected yet: nothing was sent",
2336 &outgoing,
2337 reply_root.as_deref(),
2338 window,
2339 cx,
2340 );
2341 return;
2342 };
2343 let conversation_id = current.selection.conversation_id().to_owned();
2344 let (target, thread_root_id) = self.outbox_route(reply_root);
2345 let created_at = Utc::now();
2346 self.push_pending(
2347 id.clone(),
2348 created_at,
2349 &outgoing,
2350 thread_root_id.clone(),
2351 cx,
2352 );
2353 if let Some(record) = outbox_record(
2354 &id,
2355 &conversation_id,
2356 target,
2357 thread_root_id.as_deref(),
2358 &outgoing,
2359 created_at,
2360 ) {
2361 store.put_outbox(&record).ok();
2362 }
2363 self.notice = None;
2364 self.rebuild(false, cx);
2365 if self.in_feed() {
2366 self.scroller
2367 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
2368 } else {
2369 self.scroller
2370 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
2371 }
2372
2373 let receiver = runtime::spawn(async move {
2374 deliver(
2375 &engine,
2376 &conversation_id,
2377 target,
2378 thread_root_id.as_deref(),
2379 &outgoing,
2380 )
2381 .await
2382 });
2383 cx.spawn_in(window, async move |this, cx| {
2384 let result = receiver.await;
2385 this.update(cx, |this, cx| this.finish_send(&id, result, cx))
2386 .ok();
2387 })
2388 .detach();
2389 }
2390
2391 fn restore_unsent(
2392 &mut self,
2393 message: &str,
2394 outgoing: &Outgoing,
2395 reply_root: Option<&str>,
2396 window: &mut Window,
2397 cx: &mut Context<Self>,
2398 ) {
2399 self.notice = Some(message.to_owned());
2400 if let (Some(root_id), true) = (reply_root, self.in_feed()) {
2401 self.open_reply_editor(root_id.to_owned(), outgoing.reply.clone(), window, cx);
2402 if let Some(composer) = self.reply_composer.clone() {
2403 composer.update(cx, |composer, cx| composer.restore(outgoing, window, cx));
2404 }
2405 } else {
2406 self.show_main_composer(cx);
2407 self.restore_subject(outgoing.subject.as_deref(), window, cx);
2408 self.composer
2409 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
2410 }
2411 cx.notify();
2412 }
2413
2414 fn next_pending_key(&mut self) -> String {
2415 self.pending_counter += 1;
2416 format!("{PENDING_KEY_PREFIX}{}", self.pending_counter)
2417 }
2418
2419 fn push_pending(
2420 &mut self,
2421 key: String,
2422 created_at: DateTime<Utc>,
2423 outgoing: &Outgoing,
2424 reply_root: Option<String>,
2425 cx: &App,
2426 ) {
2427 let my_user_id = self.row_context(cx).my_user_id;
2428 let conversation_id = self
2429 .current
2430 .as_ref()
2431 .map(|current| current.selection.conversation_id().to_owned())
2432 .unwrap_or_default();
2433 let mut row = pending_row(
2434 key.clone(),
2435 conversation_id,
2436 my_user_id,
2437 created_at,
2438 outgoing,
2439 Delivery::Sending,
2440 );
2441 row.reply_root = reply_root;
2442 self.pending.push(row);
2443 self.pending_outgoing.insert(key, outgoing.clone());
2444 }
2445
2446 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2447 let (recipients, topic) = {
2448 let draft = self.draft.read(cx);
2449 let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty());
2450 (draft.chips().to_vec(), topic)
2451 };
2452 if recipients.is_empty() {
2453 self.restore_unsent("Add at least one person first", &outgoing, None, window, cx);
2454 self.draft
2455 .update(cx, |draft, cx| draft.focus_query(window, cx));
2456 return;
2457 }
2458 if self
2459 .pending
2460 .iter()
2461 .any(|row| matches!(row.delivery, Delivery::Sending))
2462 {
2463 self.restore_unsent("Still creating the chat", &outgoing, None, window, cx);
2464 return;
2465 }
2466 let state = self.app.read(cx);
2467 let (mode, engine) = (state.mode, state.engine.clone());
2468 if mode.read_only {
2469 self.restore_unsent(
2470 "Read-only mode: nothing was sent",
2471 &outgoing,
2472 None,
2473 window,
2474 cx,
2475 );
2476 return;
2477 }
2478 if mode.demo && outgoing.has_attachments() {
2479 self.restore_unsent(
2480 "Read-only mode: nothing was sent",
2481 &outgoing,
2482 None,
2483 window,
2484 cx,
2485 );
2486 return;
2487 }
2488 if mode.demo {
2489 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
2490 return;
2491 }
2492 let Some(engine) = engine else {
2493 self.restore_unsent(
2494 "Not connected yet: nothing was sent",
2495 &outgoing,
2496 None,
2497 window,
2498 cx,
2499 );
2500 return;
2501 };
2502 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
2503 let known_chat = self
2504 .draft_created
2505 .as_ref()
2506 .filter(|(created_for, _)| *created_for == user_ids)
2507 .map(|(_, chat_id)| chat_id.clone())
2508 .or_else(|| self.draft_target_chat(cx));
2509 self.pending.clear();
2510 self.pending_outgoing.clear();
2511 self.draft_error = None;
2512 self.notice = None;
2513 let key = self.next_pending_key();
2514 self.push_pending(key.clone(), Utc::now(), &outgoing, None, cx);
2515 self.rebuild(true, cx);
2516 let recipients_for_finish = user_ids.clone();
2517 let receiver = runtime::spawn(async move {
2518 let chat_id = match known_chat {
2519 Some(chat_id) => chat_id,
2520 None => {
2521 let created = match user_ids.as_slice() {
2522 [user_id] => engine.create_one_on_one(user_id).await,
2523 _ => engine.create_group(&user_ids, topic.as_deref()).await,
2524 };
2525 match created {
2526 Ok(chat_id) => chat_id,
2527 Err(error) => return (None, Some(short_error(&error))),
2528 }
2529 }
2530 };
2531 let sent = engine
2532 .send_message_with_extras(
2533 &chat_id,
2534 &outgoing.html(),
2535 None,
2536 &outgoing.mentions,
2537 &outgoing.extras(),
2538 )
2539 .await;
2540 if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) {
2541 let _ = engine
2542 .attach_link_preview(&chat_id, &record.message_id, preview)
2543 .await;
2544 }
2545 (Some(chat_id), sent.err().map(|error| short_error(&error)))
2546 });
2547 cx.spawn_in(window, async move |this, cx| {
2548 let result = receiver.await;
2549 this.update_in(cx, |this, _, cx| {
2550 this.finish_new_chat(&key, recipients_for_finish, result, cx)
2551 })
2552 .ok();
2553 })
2554 .detach();
2555 }
2556
2557 fn finish_new_chat(
2558 &mut self,
2559 key: &str,
2560 user_ids: Vec<String>,
2561 result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>,
2562 cx: &mut Context<Self>,
2563 ) {
2564 if !self.draft_active || !self.pending.iter().any(|row| row.key == key) {
2565 return;
2566 }
2567 let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned())));
2568 self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id));
2569 match (chat_id, error) {
2570 (Some(chat_id), None) => {
2571 self.app.update(cx, |state, cx| {
2572 state.reload_sidebar(cx);
2573 state.select(Selection::Chat(chat_id), cx);
2574 });
2575 }
2576 (created, error) => {
2577 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2578 row.delivery = Delivery::Failed(error.unwrap_or_default());
2579 }
2580 self.draft_error = Some(
2581 if created.is_some() {
2582 "Couldn't send the message."
2583 } else {
2584 "Couldn't create the chat."
2585 }
2586 .to_owned(),
2587 );
2588 self.rebuild(false, cx);
2589 }
2590 }
2591 }
2592
2593 fn send_demo_new_chat(
2594 &mut self,
2595 outgoing: &Outgoing,
2596 recipients: &[super::new_chat::Pick],
2597 topic: Option<&str>,
2598 cx: &mut Context<Self>,
2599 ) {
2600 let (store, chats) = {
2601 let state = self.app.read(cx);
2602 (state.store.clone(), state.sidebar.chats.clone())
2603 };
2604 let people: Vec<(String, String)> = recipients
2605 .iter()
2606 .map(|pick| (pick.user_id.clone(), pick.name.clone()))
2607 .collect();
2608 let (chat, message) = match self.draft_target_chat(cx) {
2609 Some(chat_id) => {
2610 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
2611 return;
2612 };
2613 crate::demo::send_in_chat(chat, &outgoing.text(), &outgoing.html(), Utc::now())
2614 }
2615 None => crate::demo::new_chat(
2616 &chats,
2617 &people,
2618 topic,
2619 &outgoing.text(),
2620 &outgoing.html(),
2621 Utc::now(),
2622 ),
2623 };
2624 let _ = store.upsert_chats(std::slice::from_ref(&chat));
2625 let _ = store.upsert_messages(std::slice::from_ref(&message));
2626 self.app.update(cx, |state, cx| {
2627 state.reload_sidebar(cx);
2628 state.select(Selection::Chat(chat.id.clone()), cx);
2629 });
2630 }
2631
2632 fn conversation_id(&self) -> Option<String> {
2633 self.current
2634 .as_ref()
2635 .map(|current| current.selection.conversation_id().to_owned())
2636 }
2637
2638 fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
2639 let conversation_id = self.conversation_id()?;
2640 let my_user_id = self.row_context(cx).my_user_id?;
2641 self.app
2642 .read(cx)
2643 .store
2644 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2645 .ok()?
2646 .remove(message_id)
2647 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
2648 }
2649
2650 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
2651 if hovered && matches!(slot, HoverSlot::Row) {
2652 self.request_post_follow(key, cx);
2653 }
2654 let target = match slot {
2655 HoverSlot::Row => &mut self.hovered_message,
2656 HoverSlot::Toolbar => &mut self.toolbar_hovered,
2657 };
2658 if hovered {
2659 *target = Some(key.to_owned());
2660 } else if target.as_deref() == Some(key) {
2661 *target = None;
2662 }
2663 if hovered
2664 && matches!(slot, HoverSlot::Row)
2665 && self.toolbar_hovered.as_deref().is_some_and(|toolbar| toolbar != key)
2666 {
2667 self.toolbar_hovered = None;
2668 }
2669 if let Some(suppressed) = self.toolbar_suppressed.as_deref()
2670 && self.hovered_message.as_deref() != Some(suppressed)
2671 && self.toolbar_hovered.as_deref() != Some(suppressed)
2672 {
2673 self.toolbar_suppressed = None;
2674 }
2675 cx.notify();
2676 }
2677
2678 fn suppress_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
2679 if self.toolbar_hovered.as_deref() == Some(key) {
2680 self.toolbar_hovered = None;
2681 }
2682 self.toolbar_suppressed = Some(key.to_owned());
2683 cx.notify();
2684 }
2685
2686 fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) {
2687 if open {
2688 self.toolbar_pinned = Some(key.to_owned());
2689 } else if self.toolbar_pinned.as_deref() == Some(key) {
2690 self.toolbar_pinned = None;
2691 }
2692 cx.notify();
2693 }
2694
2695 fn toolbar_visible(&self, key: &str) -> bool {
2696 self.toolbar_suppressed.as_deref() != Some(key)
2697 && self
2698 .toolbar_pinned
2699 .as_deref()
2700 .or(self.toolbar_hovered.as_deref())
2701 .or(self.hovered_message.as_deref())
2702 == Some(key)
2703 }
2704
2705 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
2706 self.change_reaction(message_id, glyph, false, None, cx);
2707 }
2708
2709 fn change_reaction(
2710 &mut self,
2711 message_id: &str,
2712 glyph: &str,
2713 only_add: bool,
2714 accepted_proposal: Option<String>,
2715 cx: &mut Context<Self>,
2716 ) -> ReactionAttempt {
2717 let Some(conversation_id) = self.conversation_id() else {
2718 return ReactionAttempt::Blocked;
2719 };
2720 let state = self.app.read(cx);
2721 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2722 let engine = engine.filter(|_| !mode.read_only);
2723 if !mode.demo && engine.is_none() {
2724 self.show_notice("Read-only mode: reaction not sent", cx);
2725 return ReactionAttempt::Blocked;
2726 }
2727 let my_user_id = self.row_context(cx).my_user_id;
2728 let Some(mut record) = store
2729 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2730 .ok()
2731 .and_then(|mut found| found.remove(message_id))
2732 else {
2733 return ReactionAttempt::MissingMessage;
2734 };
2735 let wanted = reaction_glyph(glyph);
2736 let mut visible = teams_core::reactions(&record);
2737 apply_pending_reactions(
2738 &mut visible,
2739 self.pending_reactions.get(message_id),
2740 my_user_id.as_deref(),
2741 Utc::now(),
2742 );
2743 let added = !has_own_reaction(&visible, glyph, my_user_id.as_deref());
2744 if only_add && !added {
2745 return ReactionAttempt::AlreadyThere;
2746 }
2747 let skin_tone = teams_core::skin_tone(&store);
2748 let wanted = if added {
2749 wanted
2750 } else {
2751 let own = own_reaction_glyph(&visible, glyph, my_user_id.as_deref()).unwrap_or(wanted);
2752 if emoticons::without_tone(&own) == own {
2753 emoticons::with_tone(&own, skin_tone)
2754 } else {
2755 own
2756 }
2757 };
2758 let glyph = wanted.as_str();
2759 let Some(engine) = engine.filter(|_| !mode.demo) else {
2760 let mut reactions = teams_core::reactions(&record);
2761 set_own_reaction(
2762 &mut reactions,
2763 glyph,
2764 my_user_id.as_deref(),
2765 added,
2766 Utc::now(),
2767 );
2768 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2769 let _ = store.upsert_messages(std::slice::from_ref(&record));
2770 if added {
2771 self.record_reaction_use(glyph, cx);
2772 }
2773 self.rebuild(false, cx);
2774 return ReactionAttempt::Acted;
2775 };
2776 let entries = self
2777 .pending_reactions
2778 .entry(message_id.to_owned())
2779 .or_default();
2780 entries.retain(|(pending, _)| {
2781 emoticons::without_tone(pending) != emoticons::without_tone(&wanted)
2782 });
2783 entries.push((wanted.clone(), added));
2784 self.rebuild(false, cx);
2785 let (message_id, glyph) = (message_id.to_owned(), glyph.to_owned());
2786 let reaction_type = api_reaction(&wanted);
2787 let receiver = runtime::spawn({
2788 let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone());
2789 async move {
2790 if added {
2791 engine
2792 .set_reaction(&conversation_id, &message_id, &reaction_type)
2793 .await
2794 } else {
2795 engine
2796 .unset_reaction(&conversation_id, &message_id, &reaction_type)
2797 .await
2798 }
2799 }
2800 });
2801 cx.spawn(async move |this, cx| {
2802 let outcome = match receiver.await {
2803 Ok(Ok(())) => Ok(()),
2804 Ok(Err(error)) => Err(short_error(&error)),
2805 Err(_) => Err("cancelled".to_owned()),
2806 };
2807 this.update(cx, |this, cx| {
2808 this.finish_reaction(
2809 &conversation_id,
2810 &message_id,
2811 &glyph,
2812 added,
2813 accepted_proposal.as_deref(),
2814 outcome,
2815 cx,
2816 )
2817 })
2818 .ok();
2819 })
2820 .detach();
2821 ReactionAttempt::Started
2822 }
2823
2824 fn finish_reaction(
2825 &mut self,
2826 conversation_id: &str,
2827 message_id: &str,
2828 glyph: &str,
2829 added: bool,
2830 accepted_proposal: Option<&str>,
2831 outcome: Result<(), String>,
2832 cx: &mut Context<Self>,
2833 ) {
2834 let wanted = reaction_glyph(glyph);
2835 let store = self.app.read(cx).store.clone();
2836 if let Some(proposal_id) = accepted_proposal.filter(|_| outcome.is_ok()) {
2837 crate::agent_api::resolve_reaction_proposal(
2838 conversation_id,
2839 message_id,
2840 proposal_id,
2841 mcp::ReactionOutcome::Accepted,
2842 cx,
2843 );
2844 }
2845 if outcome.is_ok() {
2846 let my_user_id = self.row_context(cx).my_user_id;
2847 if let Some(mut record) = store
2848 .messages_by_id(conversation_id, &[message_id.to_owned()])
2849 .ok()
2850 .and_then(|mut found| found.remove(message_id))
2851 {
2852 let mut reactions = teams_core::reactions(&record);
2853 set_own_reaction(
2854 &mut reactions,
2855 glyph,
2856 my_user_id.as_deref(),
2857 added,
2858 Utc::now(),
2859 );
2860 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2861 let _ = store.upsert_messages(std::slice::from_ref(&record));
2862 }
2863 if added {
2864 self.record_reaction_use(glyph, cx);
2865 }
2866 }
2867 if let Some(entries) = self.pending_reactions.get_mut(message_id) {
2868 entries.retain(|entry| *entry != (wanted.clone(), added));
2869 if entries.is_empty() {
2870 self.pending_reactions.remove(message_id);
2871 }
2872 }
2873 self.rebuild(false, cx);
2874 if let Err(error) = outcome {
2875 self.show_notice(&format!("Reaction failed: {error}"), cx);
2876 }
2877 }
2878
2879 fn record_reaction_use(&mut self, glyph: &str, cx: &mut Context<Self>) {
2880 if chatsvc::custom_emoji(glyph).is_some() {
2881 return;
2882 }
2883 let store = self.app.read(cx).store.clone();
2884 self.recent.update(cx, |recent, cx| {
2885 recent.reload(&store);
2886 recent.record_use(&emoticons::without_tone(glyph));
2887 recent.save(&store);
2888 cx.notify();
2889 });
2890 }
2891
2892 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
2893 let Some(record) = self.own_record(message_id, cx) else {
2894 return;
2895 };
2896 let edit = EditPreview {
2897 message_id: record.message_id.clone(),
2898 excerpt: reply_excerpt(&record),
2899 scheduled: None,
2900 };
2901 let in_chat = matches!(
2902 self.current.as_ref().map(|current| &current.selection),
2903 Some(Selection::Chat(_))
2904 );
2905 let mentions = if in_chat {
2906 teams_core::user_mention_inputs(&record)
2907 } else {
2908 Vec::new()
2909 };
2910 let draft = Outgoing {
2911 draft: message_draft(&record),
2912 subject: None,
2913 mentions,
2914 reply: None,
2915 edit: Some(edit),
2916 images: Vec::new(),
2917 files: Vec::new(),
2918 link_preview: None,
2919 importance: Default::default(),
2920 };
2921 self.show_main_composer(cx);
2922 self.composer
2923 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
2924 }
2925
2926 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2927 if self.draft_active {
2928 return;
2929 }
2930 let key = self
2931 .rows
2932 .borrow()
2933 .iter()
2934 .flat_map(Row::messages)
2935 .filter(|message| {
2936 message.own && !message.deleted && !message.key.starts_with(PENDING_KEY_PREFIX)
2937 })
2938 .max_by_key(|message| message.created_at)
2939 .map(|message| message.key.clone());
2940 if let Some(key) = key {
2941 self.begin_edit(&key, window, cx);
2942 }
2943 }
2944
2945 fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2946 let Some(edit) = outgoing.edit.clone() else {
2947 return;
2948 };
2949 let Some(conversation_id) = self.conversation_id() else {
2950 return;
2951 };
2952 let state = self.app.read(cx);
2953 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2954 if mode.demo {
2955 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
2956 record.body_html = outgoing.html();
2957 record.edited_at = Some(Utc::now());
2958 let _ = store.upsert_messages(std::slice::from_ref(&record));
2959 self.rebuild(false, cx);
2960 }
2961 return;
2962 }
2963 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2964 self.notice = Some("Read-only mode: edit not saved".to_owned());
2965 self.show_main_composer(cx);
2966 self.composer
2967 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2968 cx.notify();
2969 return;
2970 };
2971 let sent = outgoing.clone();
2972 let receiver = runtime::spawn(async move {
2973 engine
2974 .edit_message_html(
2975 &conversation_id,
2976 &edit.message_id,
2977 &sent.html(),
2978 &sent.mentions,
2979 )
2980 .await
2981 });
2982 cx.spawn_in(window, async move |this, cx| {
2983 let failed = !matches!(receiver.await, Ok(Ok(())));
2984 this.update_in(cx, |this, window, cx| {
2985 if failed {
2986 this.show_main_composer(cx);
2987 if this.composer.read(cx).is_empty(cx) {
2988 this.notice =
2989 Some("Edit failed: your text is back in the composer".to_owned());
2990 this.composer
2991 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2992 } else {
2993 this.notice = Some("Edit failed".to_owned());
2994 }
2995 cx.notify();
2996 }
2997 })
2998 .ok();
2999 })
3000 .detach();
3001 }
3002
3003 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
3004 let Some(conversation_id) = self.conversation_id() else {
3005 return;
3006 };
3007 let record = self
3008 .app
3009 .read(cx)
3010 .store
3011 .messages_by_id(&conversation_id, &[message_id.to_owned()])
3012 .ok()
3013 .and_then(|mut found| found.remove(message_id));
3014 if let Some(record) = record {
3015 cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record)));
3016 }
3017 }
3018
3019 fn refresh_card(
3020 &mut self,
3021 key: &str,
3022 card_index: usize,
3023 action: ExecuteAction,
3024 cx: &mut Context<Self>,
3025 ) {
3026 let Some(conversation_id) = self.conversation_id() else {
3027 return;
3028 };
3029 let scope = CardScope::message(&conversation_id, key, card_index);
3030 self.app.update(cx, |state, cx| {
3031 state.refresh_card_manually(scope, action, cx)
3032 });
3033 }
3034
3035 pub(super) fn translate_message(&mut self, key: &str, cx: &mut Context<Self>) {
3036 let Some(conversation_id) = self.conversation_id() else {
3037 return;
3038 };
3039 self.app.update(cx, |state, cx| {
3040 state.translate_message(&conversation_id, key, cx)
3041 });
3042 }
3043
3044 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
3045 self.app.update(cx, |state, cx| {
3046 state.raise_notice(message.to_owned(), None, cx)
3047 });
3048 }
3049
3050 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
3051 let (Some(conversation_id), Some(runs)) =
3052 (self.conversation_id(), crate::agents::runs_handle(cx))
3053 else {
3054 return (Vec::new(), None);
3055 };
3056 if key.starts_with(PENDING_KEY_PREFIX) || key.starts_with(SCHEDULED_KEY_PREFIX) {
3057 return (Vec::new(), None);
3058 }
3059 let settings = runs.read(cx).settings();
3060 let entries: Vec<DelegateEntry> = settings
3061 .actions
3062 .iter()
3063 .map(|action| {
3064 let request = StartRequest {
3065 action_id: action.id.clone(),
3066 conversation_id: conversation_id.clone(),
3067 message_id: key.to_owned(),
3068 };
3069 let agent_name = settings
3070 .agents
3071 .iter()
3072 .find(|agent| agent.id == action.agent_id)
3073 .map(|agent| agent.name.clone())
3074 .unwrap_or_default();
3075 DelegateEntry {
3076 label: action.label.clone(),
3077 agent_name,
3078 action: Rc::new(move |_, cx| crate::agents::delegate(request.clone(), cx)),
3079 }
3080 })
3081 .collect();
3082 let manage_agents = (!entries.is_empty()).then(|| {
3083 Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action
3084 });
3085 (entries, manage_agents)
3086 }
3087
3088 fn refresh_agent_runs(&mut self, cx: &App) -> (bool, HashSet<String>) {
3089 let Some(conversation_id) = self.conversation_id() else {
3090 return (false, HashSet::new());
3091 };
3092 let Some(runs) = crate::agents::runs_handle(cx) else {
3093 return (false, HashSet::new());
3094 };
3095 let mut snapshot: HashMap<String, AgentRun> = HashMap::new();
3096 for run in runs.read(cx).for_conversation(&conversation_id) {
3097 snapshot.insert(run.message_id.clone(), run.clone());
3098 }
3099 let layouts: HashMap<String, (usize, bool)> = snapshot
3100 .iter()
3101 .map(|(key, run)| (key.clone(), run.layout_key()))
3102 .collect();
3103 let layout_changed: HashSet<String> = layouts
3104 .iter()
3105 .filter(|(key, layout)| self.agent_layouts.get(*key) != Some(layout))
3106 .map(|(key, _)| key.clone())
3107 .chain(
3108 self.agent_layouts
3109 .keys()
3110 .filter(|key| !layouts.contains_key(*key))
3111 .cloned(),
3112 )
3113 .collect();
3114 self.agent_layouts = layouts;
3115 let snapshot_changed = *self.agent_runs.borrow() != snapshot;
3116 *self.agent_runs.borrow_mut() = snapshot;
3117 (snapshot_changed, layout_changed)
3118 }
3119
3120 fn sync_agent_chips(&mut self, cx: &mut Context<Self>) {
3121 let (snapshot_changed, changed) = self.refresh_agent_runs(cx);
3122 let any_running = self.agent_runs.borrow().values().any(AgentRun::is_running);
3123 self.remeasure_rows_of(&changed, cx);
3124 if snapshot_changed || any_running {
3125 cx.notify();
3126 }
3127 }
3128
3129 fn remeasure_rows_of(&mut self, keys: &HashSet<String>, cx: &mut Context<Self>) {
3130 if keys.is_empty() {
3131 return;
3132 }
3133 let indices: Vec<usize> = self
3134 .rows
3135 .borrow()
3136 .iter()
3137 .enumerate()
3138 .filter(|(_, row)| row.messages().any(|message| keys.contains(&message.key)))
3139 .map(|(index, _)| index)
3140 .collect();
3141 self.scroller.update(cx, |scroller, cx| {
3142 for index in indices {
3143 scroller.remeasure_items(index..index + 1, cx);
3144 }
3145 });
3146 }
3147
3148 fn message_menu(
3149 &self,
3150 message: &MessageRow,
3151 mine: HashSet<String>,
3152 refresh: Option<(usize, ExecuteAction)>,
3153 view: WeakEntity<Self>,
3154 cx: &App,
3155 ) -> MessageMenu {
3156 let (key, own) = (message.key.as_str(), message.own);
3157 let translate_label = match message.translation {
3158 Some(TranslationLine::Translated {
3159 showing_original: false,
3160 ..
3161 }) => "See original",
3162 Some(TranslationLine::Translated { .. }) => "See translation",
3163 _ => "Translate",
3164 };
3165 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
3166 let (view, key) = (view.clone(), key.to_owned());
3167 Rc::new(move |window, cx| {
3168 view.update(cx, |this, cx| {
3169 this.set_pinned(&key, false, cx);
3170 run(this, &key, window, cx)
3171 })
3172 .ok();
3173 })
3174 };
3175 let react: PickHandler = {
3176 let (view, key) = (view.clone(), key.to_owned());
3177 Rc::new(move |glyph, _, cx| {
3178 view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx))
3179 .ok();
3180 })
3181 };
3182 let hover = {
3183 let (view, key) = (view.clone(), key.to_owned());
3184 Rc::new(move |hovered: bool, cx: &mut App| {
3185 view.update(cx, |this, cx| {
3186 this.set_hover(HoverSlot::Toolbar, &key, hovered, cx)
3187 })
3188 .ok();
3189 })
3190 };
3191 let pin = {
3192 let (view, key) = (view.clone(), key.to_owned());
3193 Rc::new(move |open: bool, _: &mut Window, cx: &mut App| {
3194 view.update(cx, |this, cx| this.set_pinned(&key, open, cx))
3195 .ok();
3196 })
3197 };
3198 let refresh_card = refresh.map(|(card_index, refresh_action)| {
3199 let (view, key) = (view.clone(), key.to_owned());
3200 Rc::new(move |_: &mut Window, cx: &mut App| {
3201 view.update(cx, |this, cx| {
3202 this.refresh_card(&key, card_index, refresh_action.clone(), cx)
3203 })
3204 .ok();
3205 }) as Action
3206 });
3207 let chat_id = self.chat_id();
3208 let state = self.app.read(cx);
3209 let saved = self
3210 .conversation_id()
3211 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3212 let quick = state.quick_reactions();
3213 let in_chat = chat_id.is_some();
3214 let pin_conversation_id = self.pin_conversation_id();
3215 let pinned = pin_conversation_id
3216 .as_deref()
3217 .is_some_and(|conversation_id| state.is_pinned(conversation_id, key));
3218 let pinnable = in_chat
3219 || pin_conversation_id.as_deref().is_some_and(|channel_id| {
3220 state
3221 .message_record(channel_id, key)
3222 .is_some_and(|record| record.reply_to_id.is_none())
3223 });
3224 let (delegate, manage_agents) = self.delegate_entries(key, cx);
3225 let post_followed = self.post_follow(key, cx);
3226 MessageMenu {
3227 key: key.to_owned(),
3228 react,
3229 reply: Some(action(|this, key, window, cx| {
3230 this.begin_reply(key, window, cx)
3231 })),
3232 forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),
3233 forward_multiple: in_chat
3234 .then(|| action(|this, key, _, cx| this.start_forward_selection(key, cx))),
3235 copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),
3236 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
3237 translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),
3238 translate_label,
3239 share_to_outlook: Some(action(|this, key, _, cx| this.share_to_outlook(key, cx))),
3240 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3241 saved,
3242 toggle_pinned: pinnable
3243 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3244 pinned,
3245 toggle_follow: post_followed
3246 .map(|_| action(|this, key, _, cx| this.toggle_post_follow(key, cx))),
3247 followed: post_followed.unwrap_or_default(),
3248 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3249 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
3250 mark_unread: (in_chat && !own)
3251 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
3252 refresh_card,
3253 delegate,
3254 manage_agents,
3255 pin,
3256 hover,
3257 picker: self.picker.clone(),
3258 quick,
3259 mine,
3260 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3261 }
3262 }
3263
3264 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
3265 let Some(outgoing) = self.pending_outgoing.remove(key) else {
3266 return;
3267 };
3268 let reply_root = self
3269 .pending
3270 .iter()
3271 .find(|row| row.key == key)
3272 .and_then(|row| row.reply_root.clone());
3273 self.pending.retain(|row| row.key != key);
3274 if self.draft_active {
3275 self.send_new_chat(outgoing, window, cx);
3276 } else {
3277 self.send_as(key.to_owned(), outgoing, reply_root, window, cx);
3278 }
3279 }
3280
3281 fn finish_send(
3282 &mut self,
3283 key: &str,
3284 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
3285 cx: &mut Context<Self>,
3286 ) {
3287 let failure = match result {
3288 Ok(Ok(())) => None,
3289 Ok(Err(error)) => Some(short_error(&error)),
3290 Err(error) => Some(short_error(&error)),
3291 };
3292 let store = self.app.read(cx).store.clone();
3293 match failure {
3294 None => {
3295 store.delete_outbox(key).ok();
3296 self.pending.retain(|row| row.key != key);
3297 self.pending_outgoing.remove(key);
3298 }
3299 Some(error) => {
3300 store.mark_outbox_failed(key, &error).ok();
3301 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
3302 row.delivery = Delivery::Failed(error.clone());
3303 self.notice = Some(format!("Not sent: {error}"));
3304 }
3305 }
3306 }
3307 self.app
3308 .update(cx, |state, cx| state.refresh_local_previews(cx));
3309 self.rebuild(false, cx);
3310 }
3311
3312 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
3313 let target = match self.current.as_ref().map(|current| &current.selection) {
3314 Some(Selection::Chat(_)) => DropTarget::Chat,
3315 Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library,
3316 Some(Selection::Channel(_)) => DropTarget::Channel,
3317 None => DropTarget::NewChat,
3318 };
3319 let title = self
3320 .current
3321 .as_ref()
3322 .map(|current| current.title.as_str())
3323 .unwrap_or_default();
3324 let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1));
3325 let composer = self.composer.clone();
3326 div()
3327 .id("drop-overlay")
3328 .absolute()
3329 .top_0()
3330 .left_0()
3331 .size_full()
3332 .opacity(0.)
3333 .bg(theme::drop_background())
3334 .drag_over::<ExternalPaths>(move |style, _, _, cx| {
3335 if composer.read(cx).is_editing() {
3336 style
3337 } else {
3338 style.opacity(1.)
3339 }
3340 })
3341 .on_drag_move(
3342 cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
3343 let count = event.drag(cx).paths().len();
3344 if this.drag_file_count != count {
3345 this.drag_file_count = count;
3346 cx.notify();
3347 }
3348 }),
3349 )
3350 .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
3351 let paths = dropped.paths().to_vec();
3352 if this.shared_active() {
3353 this.upload_paths(paths, cx);
3354 return;
3355 }
3356 this.composer
3357 .update(cx, |composer, cx| composer.add_paths(paths, window, cx));
3358 }))
3359 .child(
3360 div()
3361 .absolute()
3362 .inset(px(12.))
3363 .rounded(px(12.))
3364 .border_2()
3365 .border_color(theme::accent())
3366 .flex()
3367 .items_center()
3368 .justify_center()
3369 .child(
3370 v_flex()
3371 .items_center()
3372 .gap(px(6.))
3373 .px(px(24.))
3374 .py(px(16.))
3375 .rounded(px(12.))
3376 .bg(black().opacity(0.55))
3377 .child(symbol("upload", 28., theme::accent_text()))
3378 .child(
3379 div()
3380 .text_size(px(15.))
3381 .font_weight(FontWeight::SEMIBOLD)
3382 .text_color(theme::text_strong())
3383 .child(heading),
3384 )
3385 .child(
3386 div()
3387 .text_size(px(12.))
3388 .text_color(theme::text_muted())
3389 .child(detail),
3390 ),
3391 ),
3392 )
3393 }
3394
3395 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
3396 let message = self.draft_error.clone()?;
3397 let failed_key = self
3398 .pending
3399 .iter()
3400 .find(|row| matches!(row.delivery, Delivery::Failed(_)))
3401 .map(|row| row.key.clone())?;
3402 Some(
3403 h_flex()
3404 .w_full()
3405 .flex_none()
3406 .px(px(20.))
3407 .py(px(4.))
3408 .gap(px(8.))
3409 .items_center()
3410 .text_size(px(12.))
3411 .text_color(theme::red_soft())
3412 .child(message)
3413 .child(
3414 Button::new("retry-new-chat")
3415 .ghost()
3416 .compact()
3417 .label("Retry")
3418 .on_click(cx.listener(move |this, _, window, cx| {
3419 this.retry(&failed_key, window, cx)
3420 })),
3421 ),
3422 )
3423 }
3424
3425 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3426 if self.pinned || self.draft_active {
3427 return;
3428 }
3429 let Some(selection) = self
3430 .current
3431 .as_ref()
3432 .map(|current| current.selection.clone())
3433 else {
3434 return;
3435 };
3436 self.channel_details_open = false;
3437 if let Some(panel) = &self.find_panel {
3438 panel.update(cx, |panel, cx| panel.focus(window, cx));
3439 return;
3440 }
3441 let app = self.app.clone();
3442 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3443 let subscription = cx.subscribe_in(
3444 &panel,
3445 window,
3446 move |this, _, event: &FindPanelEvent, window, cx| match event {
3447 FindPanelEvent::Close => this.close_find(window, cx),
3448 FindPanelEvent::Jump(message_id) => {
3449 let (selection, message_id) = (selection.clone(), message_id.clone());
3450 this.app.update(cx, |state, cx| {
3451 state.jump_to_message(selection, message_id, cx)
3452 });
3453 }
3454 },
3455 );
3456 panel.update(cx, |panel, cx| panel.focus(window, cx));
3457 self.find_panel = Some(panel);
3458 self.find_subscription = Some(subscription);
3459 cx.notify();
3460 }
3461
3462 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3463 self.find_panel = None;
3464 self.find_subscription = None;
3465 self.composer
3466 .update(cx, |composer, cx| composer.focus(window, cx));
3467 cx.notify();
3468 }
3469
3470 fn header_width(&self, window: &Window) -> f32 {
3471 match self.header_width.get() {
3472 width if width > 0. => width,
3473 _ => {
3474 f32::from(window.viewport_size().width)
3475 - RAIL_WIDTH
3476 - SIDEBAR_WIDTH
3477 - 2. * ISLAND_GAP
3478 }
3479 }
3480 }
3481
3482 fn tabs_below_title(&self, window: &Window) -> bool {
3483 self.header_width(window) < TABS_INLINE_MIN_WIDTH
3484 }
3485
3486 fn render_header(
3487 &self,
3488 current: &Current,
3489 tabs: Option<AnyElement>,
3490 cx: &mut Context<Self>,
3491 ) -> impl IntoElement {
3492 let app = self.app.read(cx);
3493 let directory = &app.directory;
3494 let me = directory.me.as_ref();
3495 let mut lead: Option<AnyElement> = None;
3496 let mut subline = String::new();
3497 let mut stack: Option<AnyElement> = None;
3498 let mut rename: Option<AnyElement> = None;
3499 match &current.selection {
3500 Selection::Chat(chat_id) => {
3501 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
3502 let faces = others(chat, me);
3503 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
3504 let first = faces.first().cloned().map(face);
3505 if let Some(bot) = one_on_one_bot(chat, me) {
3506 lead = Some(bot_tile(directory, &face(bot), 36.));
3507 } else if is_one_on_one(chat) || faces.len() < 2 {
3508 let name = first
3509 .as_ref()
3510 .map_or(current.title.as_str(), |face| face.name.as_str());
3511 let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
3512 let avatar = person_avatar(directory, user_id, name, 36.);
3513 let presence = user_id.map(|id| directory.presence_of(id));
3514 let avatar = match presence {
3515 Some(kind) => with_presence(avatar, kind, 36., theme::surface())
3516 .into_any_element(),
3517 None => avatar,
3518 };
3519 lead = Some(
3520 opens_profile(div().id("header-avatar").flex_none(), user_id)
3521 .child(avatar)
3522 .into_any_element(),
3523 );
3524 subline = match (user_id, presence) {
3525 (Some(id), Some(presence)) => {
3526 directory.status_label(id, presence).to_owned()
3527 }
3528 _ => String::new(),
3529 };
3530 if is_one_on_one(chat) && !is_notes_chat(chat_id) {
3531 stack = Some(add_people_button(&self.app, chat_id));
3532 }
3533 } else {
3534 if chat.kind == GROUP_KIND
3535 && me.is_some_and(|me| {
3536 chat.members
3537 .iter()
3538 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3539 })
3540 {
3541 rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3542 }
3543 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3544 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3545 subline = format!("{} participants", chat.members.len());
3546 let shown: Vec<Face> = faces.iter().cloned().map(face).collect();
3547 stack = Some(members_popover(
3548 &self.app,
3549 chat_id,
3550 member_stack(directory, &shown, shown.len(), false)
3551 .debug_selector(|| MEMBERS_BUTTON.into()),
3552 ));
3553 }
3554 }
3555 }
3556 Selection::Channel(channel_id) => {
3557 let team = app.sidebar.teams.iter().find(|entry| {
3558 entry
3559 .channels
3560 .iter()
3561 .any(|channel| &channel.id == channel_id)
3562 });
3563 let (name, key) = team
3564 .map_or((current.title.as_str(), current.title.as_str()), |entry| {
3565 (entry.team.name.as_str(), entry.team.id.as_str())
3566 });
3567 lead = Some(square_avatar(name, key, 36., 9.).into_any_element());
3568 }
3569 }
3570 let mut header = h_flex()
3571 .w_full()
3572 .h(px(HEADER_HEIGHT))
3573 .flex_none()
3574 .px(px(HEADER_PADDING))
3575 .gap(px(HEADER_GAP))
3576 .items_center();
3577 if matches!(current.mode, ViewMode::Thread(_)) {
3578 header = header.child(
3579 h_flex()
3580 .id("back-to-channel")
3581 .flex_none()
3582 .gap(px(2.))
3583 .pl(px(4.))
3584 .pr(px(8.))
3585 .py(px(4.))
3586 .items_center()
3587 .rounded(px(6.))
3588 .cursor_pointer()
3589 .text_size(px(13.))
3590 .font_weight(FontWeight::SEMIBOLD)
3591 .text_color(theme::accent_text())
3592 .hover(|button| button.bg(theme::row_hover()))
3593 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx)))
3594 .child(icon(IconName::ChevronLeft, 16., theme::accent_text()))
3595 .child("Back to channel"),
3596 );
3597 }
3598 let channel_note = match current.mode {
3599 ViewMode::Flat => None,
3600 ViewMode::ThreadList => Some("Posts"),
3601 ViewMode::Thread(_) => Some("Conversation"),
3602 };
3603 if let Some(note) = channel_note {
3604 subline = note.to_owned();
3605 }
3606 let call_controls = if self.pinned && !self.popped_out {
3607 Vec::new()
3608 } else {
3609 header_call_controls(&self.app, app, &current.selection)
3610 };
3611 let sync = &current.sync;
3612 let loading_window = current.window_request.is_some();
3613 if sync.failed {
3614 subline = "Not up to date".to_owned();
3615 } else if loading_window {
3616 subline = "Loading message ...".to_owned();
3617 } else if sync.shown_at.is_some() {
3618 subline = if sync.slow {
3619 "Taking longer than usual ..."
3620 } else if sync.empty_cache {
3621 "Loading messages ..."
3622 } else {
3623 "Updating ..."
3624 }
3625 .to_owned();
3626 }
3627 let inline_tabs = tabs.map(|tabs| h_flex().h_full().flex_1().child(tabs));
3628 header
3629 .relative()
3630 .child(record_width(&self.header_width))
3631 .when(sync.shown_at.is_some() || loading_window, |header| {
3632 header.child(progress_bar())
3633 })
3634 .children(lead)
3635 .child(
3636 v_flex()
3637 .map(|column| match inline_tabs {
3638 Some(_) => column.flex_shrink(1.).max_w(px(HEADER_TITLE_MAX_WIDTH)),
3639 None => column.flex_1(),
3640 })
3641 .min_w_0()
3642 .overflow_hidden()
3643 .gap(px(1.))
3644 .child(
3645 h_flex()
3646 .min_w_0()
3647 .gap(px(2.))
3648 .items_center()
3649 .child(
3650 div()
3651 .truncate()
3652 .text_size(px(15.))
3653 .font_weight(FontWeight::SEMIBOLD)
3654 .text_color(theme::text())
3655 .child(current.title.clone()),
3656 )
3657 .children(rename),
3658 )
3659 .when(!subline.is_empty(), |column| {
3660 column.child(
3661 div()
3662 .text_size(px(12.))
3663 .text_color(theme::text_muted())
3664 .child(subline),
3665 )
3666 }),
3667 )
3668 .children(inline_tabs)
3669 .children(stack)
3670 .children(call_controls)
3671 .children(self.channel_find_button(cx))
3672 .children(self.channel_details_button(cx))
3673 .children(self.pop_in_button(current))
3674 }
3675
3676 fn pop_in_button(&self, current: &Current) -> Option<AnyElement> {
3677 let Selection::Chat(chat_id) = &current.selection else {
3678 return None;
3679 };
3680 if !self.popped_out {
3681 return None;
3682 }
3683 let (app, chat_id) = (self.app.clone(), chat_id.clone());
3684 Some(
3685 Button::new("chat-pop-in")
3686 .icon(IconName::SquareArrowDownLeft)
3687 .ghost()
3688 .size(px(POP_IN_BUTTON_SIZE))
3689 .rounded(px(8.))
3690 .tooltip(chat_pop_out::POP_IN_TOOLTIP)
3691 .on_click(move |_, window, cx| {
3692 chat_pop_out::return_to_main_window(&app, &chat_id, window, cx)
3693 })
3694 .into_any_element(),
3695 )
3696 }
3697}
3698
3699const GROUP_KIND: &str = "group";
3700
3701impl Render for ConversationView {
3702 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3703 let background = theme::surface();
3704 let mut root = v_flex()
3705 .when(!self.pinned, |root| {
3706 root.debug_selector(|| "shell/islands/main".into())
3707 })
3708 .flex_1()
3709 .w_full()
3710 .min_w_0()
3711 .h_full()
3712 .rounded(px(10.))
3713 .bg(background)
3714 .track_focus(&self.focus_handle);
3715 let drafting = self.draft_active;
3716 if self.current.is_none() && !drafting {
3717 return root
3718 .items_center()
3719 .justify_center()
3720 .text_color(theme::text_muted())
3721 .child("Select a chat or channel")
3722 .into_any_element();
3723 }
3724 let in_feed = self.in_feed();
3725 let detached = self.is_detached();
3726 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
3727 if in_feed && rows_seen != usize::MAX {
3728 self.feed_at_top = rows_seen == 0;
3729 }
3730 let forward_selection = self.active_forward_selection(cx);
3731 let rows = self.rows.clone();
3732 let rows_seen = self.feed_rows_seen.clone();
3733 let env = RenderEnv {
3734 view: cx.weak_entity(),
3735 app: self.app.clone(),
3736 highlighted: self.highlighted_message.clone(),
3737 drafting,
3738 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
3739 timeline: self.timeline_bounds.clone(),
3740 agent_runs: self.agent_runs.clone(),
3741 reaction_proposals: self.reaction_proposals.clone(),
3742 forward_selection: forward_selection.clone(),
3743 };
3744 let pin_banner = self
3745 .render_pin_banner(cx)
3746 .filter(|_| !drafting && !self.shared_active() && !self.recap_active());
3747 let timeline_top_inset = pin_banner_inset(pin_banner.is_some());
3748 let comfy = self.app.read(cx).account_chat_settings().message_density
3749 != teams_core::MessageDensity::Compact;
3750 let scroller = MessageScroller::new(
3751 "messages",
3752 self.scroller.clone(),
3753 move |index, window, cx| {
3754 rows_seen.set(rows_seen.get().min(index));
3755 let rows = rows.borrow();
3756 let row = match rows.get(index) {
3757 Some(Row::Message(message)) => {
3758 let actions = env.message_actions(message, window, cx);
3759 let state = env.app.read(cx);
3760 render_message_row(message, index, actions, &state.directory, cx)
3761 }
3762 Some(Row::Post(post)) => {
3763 let actions = env.post_actions(post, window, cx);
3764 let state = env.app.read(cx);
3765 render_post(post, index, actions, &state.directory, cx)
3766 }
3767 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
3768 Some(Row::LoadOlder) => {
3769 let view = env.view.clone();
3770 cx.defer(move |cx| {
3771 view.update(cx, |this, cx| this.request_older(cx)).ok();
3772 });
3773 h_flex()
3774 .w_full()
3775 .py_2()
3776 .gap(px(6.))
3777 .justify_center()
3778 .text_size(px(12.))
3779 .text_color(theme::text_muted())
3780 .child(icon(IconName::Loader, 12., theme::text_muted()))
3781 .child("Loading older messages")
3782 .into_any_element()
3783 }
3784 Some(Row::LoadNewer) => {
3785 let view = env.view.clone();
3786 cx.defer(move |cx| {
3787 view.update(cx, |this, cx| {
3788 this.request_window_page(WindowDirection::Forward, cx)
3789 })
3790 .ok();
3791 });
3792 h_flex()
3793 .w_full()
3794 .py_2()
3795 .gap(px(6.))
3796 .justify_center()
3797 .text_size(px(12.))
3798 .text_color(theme::text_muted())
3799 .child(icon(IconName::Loader, 12., theme::text_muted()))
3800 .child("Loading newer messages")
3801 .into_any_element()
3802 }
3803 Some(Row::Start(start)) => {
3804 let state = env.app.read(cx);
3805 v_flex()
3806 .w_full()
3807 .items_center()
3808 .gap(px(8.))
3809 .pt(px(32.))
3810 .pb(px(16.))
3811 .child(match start.user_id.as_deref() {
3812 Some(user_id) if is_bot_id(user_id) => bot_tile(
3813 &state.directory,
3814 &Face {
3815 user_id: Some(user_id.to_owned()),
3816 name: start.title.clone(),
3817 },
3818 56.,
3819 ),
3820 user_id => person_avatar(
3821 &state.directory,
3822 user_id,
3823 &start.avatar_name,
3824 56.,
3825 ),
3826 })
3827 .child(
3828 div()
3829 .text_size(px(16.))
3830 .font_weight(FontWeight::SEMIBOLD)
3831 .text_color(theme::text())
3832 .child(start.title.clone()),
3833 )
3834 .child(
3835 div()
3836 .text_size(px(12.))
3837 .text_color(theme::text_muted())
3838 .child("This is the beginning of the conversation"),
3839 )
3840 .into_any_element()
3841 }
3842 None => div().into_any_element(),
3843 };
3844 runway(row, comfy)
3845 },
3846 )
3847 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3848 .jump_button(!in_feed)
3849 .force_jump_button(detached)
3850 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
3851 .with_jump_button_renderer(|button| {
3852 button
3853 .label(jump::JUMP_TO_NEWEST_LABEL)
3854 .tooltip(jump::jump_to_newest_tooltip())
3855 .border_0()
3856 .bg(theme::accent())
3857 .text_color(theme::on_accent())
3858 })
3859 .when(detached, |scroller| {
3860 let view = cx.weak_entity();
3861 scroller.on_jump(move |_, cx| {
3862 view.update(cx, |this, cx| this.leave_detached(cx)).ok();
3863 })
3864 })
3865 .with_bottom_fade(background)
3866 .with_top_inset(timeline_top_inset);
3867
3868 root = match self.current.as_ref().filter(|_| !drafting) {
3869 Some(current) => {
3870 let tab_bar = self
3871 .render_tab_bar(window, cx)
3872 .or_else(|| self.render_meeting_tab_bar(cx));
3873 let (inline_tabs, tabs_row) = match tab_bar {
3874 Some(tabs) if self.tabs_below_title(window) => (None, Some(tabs)),
3875 tabs => (tabs, None),
3876 };
3877 root.child(self.render_header(current, inline_tabs, cx))
3878 .children(tabs_row.map(|tabs| {
3879 h_flex()
3880 .w_full()
3881 .h(px(TABS_ROW_HEIGHT))
3882 .flex_none()
3883 .px(px(HEADER_PADDING))
3884 .child(tabs)
3885 }))
3886 .child(edge_divider(HEADER_DIVIDER))
3887 }
3888 None => root.child(self.draft.clone()),
3889 };
3890 let sync_failed = self
3891 .current
3892 .as_ref()
3893 .is_some_and(|current| current.sync.failed);
3894 if let Some(notice) = &self.notice {
3895 root = root.child(
3896 h_flex()
3897 .px(px(20.))
3898 .py_1()
3899 .gap(px(8.))
3900 .items_center()
3901 .text_xs()
3902 .bg(theme::amber().opacity(0.15))
3903 .text_color(theme::amber())
3904 .child(div().flex_1().min_w_0().child(notice.clone()))
3905 .when(sync_failed, |bar| {
3906 bar.child(
3907 Button::new("retry-fetch")
3908 .ghost()
3909 .compact()
3910 .label("Retry")
3911 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
3912 )
3913 }),
3914 );
3915 }
3916 let recap_active = self.recap_active();
3917 let empty_channel = in_feed && self.rows.borrow().is_empty();
3918 let new_post = self.render_new_post(window, cx);
3919 self.watch_feed_scroll(cx);
3920 let feed_scrolled = new_post.is_some() && self.scroller.read(cx).is_scrolled_from_top();
3921 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
3922 let draft = self.draft.read(cx);
3923 let group_name = draft.group_name(cx);
3924 draft.render_empty(&self.app.read(cx).directory, &group_name)
3925 } else if self.shared_active() {
3926 self.render_shared(cx)
3927 } else if self.recap_active() {
3928 self.render_recap(cx)
3929 } else if let Some(start) = self.notes_space() {
3930 notes_space::render_notes_space(&self.app.read(cx).directory, &start)
3931 } else if empty_channel {
3932 div()
3933 .size_full()
3934 .flex()
3935 .items_center()
3936 .justify_center()
3937 .text_size(px(13.))
3938 .text_color(theme::text_muted())
3939 .child("No posts in this channel yet")
3940 .into_any_element()
3941 } else {
3942 scroller.into_any_element()
3943 };
3944 let channel_details = self.render_channel_details(cx);
3945 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3946 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3947 let content = v_flex()
3948 .relative()
3949 .flex_1()
3950 .min_w_0()
3951 .min_h_0()
3952 .children(new_post)
3953 .child(
3954 div()
3955 .debug_selector(|| TIMELINE_TAG.into())
3956 .relative()
3957 .flex_1()
3958 .min_h_0()
3959 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3960 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
3961 .child(body)
3962 .when(feed_scrolled, |timeline| {
3963 timeline.child(
3964 edge_divider(FEED_EDGE_TAG)
3965 .absolute()
3966 .top_0()
3967 .left_0()
3968 .right_0(),
3969 )
3970 })
3971 .children(pin_banner.map(|banner| pin_banner_overlay(runway(banner, comfy)))),
3972 )
3973 .children(self.render_draft_error(cx).map(|error| runway(error, comfy)))
3974 .when(
3975 !in_feed && !recap_active,
3976 |column| match &forward_selection {
3977 Some(snapshot) => {
3978 column.child(runway(self.render_forward_footer(snapshot, cx), comfy))
3979 }
3980 None => column.child(runway(
3981 v_flex()
3982 .w_full()
3983 .child(self.render_typing_line(cx))
3984 .children(self.render_proposal_card(cx))
3985 .child(self.composer.clone()),
3986 comfy,
3987 )),
3988 },
3989 )
3990 .child(self.render_drop_overlay(cx));
3991 root.child(
3992 h_flex()
3993 .relative()
3994 .flex_1()
3995 .min_h_0()
3996 .w_full()
3997 .items_stretch()
3998 .child(content)
3999 .children(channel_details)
4000 .children(find_panel.map(|panel| {
4001 div()
4002 .h_full()
4003 .w(px(FIND_PANEL_WIDTH))
4004 .min_w_0()
4005 .flex_shrink(1.)
4006 .when(find_overlays, |slot| {
4007 slot.absolute().top_0().right_0().bottom_0().max_w_full()
4008 })
4009 .child(panel)
4010 })),
4011 )
4012 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
4013 if this.reaction_details.is_some() {
4014 this.close_reaction_details(cx);
4015 cx.stop_propagation();
4016 }
4017 }))
4018 .on_action(cx.listener(|this, _: &Escape, window, cx| {
4019 if this.draft_active {
4020 if this.draft.read(cx).has_focus(window, cx) {
4021 this.draft.update(cx, |draft, cx| draft.escape(cx));
4022 }
4023 } else if this.cancel_forward_selection(cx) {
4024 } else if !this.on_escape(window, cx) {
4025 cx.propagate();
4026 }
4027 }))
4028 .into_any_element()
4029 }
4030}
4031
4032fn typing_dots() -> impl IntoElement {
4033 h_flex()
4034 .gap(px(3.))
4035 .flex_none()
4036 .children((0..TYPING_DOT_COUNT).map(|index| {
4037 let phase_offset = index as f32 / TYPING_DOT_COUNT as f32;
4038 div()
4039 .size(px(TYPING_DOT_SIZE))
4040 .rounded_full()
4041 .bg(theme::text_muted())
4042 .with_animation(
4043 ElementId::NamedInteger("typing-dot".into(), index as u64),
4044 Animation::new(TYPING_PULSE_PERIOD).repeat(),
4045 move |dot, delta| {
4046 let wave = 1. - ((delta - phase_offset).rem_euclid(1.) * 2. - 1.).abs();
4047 dot.opacity(0.3 + 0.7 * wave)
4048 },
4049 )
4050 }))
4051}
4052
4053fn record_width(width: &Rc<Cell<f32>>) -> impl IntoElement {
4054 let width = width.clone();
4055 canvas(
4056 move |bounds, window, _| {
4057 let measured = f32::from(bounds.size.width);
4058 if (measured - width.replace(measured)).abs() > 0.5 {
4059 window.request_animation_frame();
4060 }
4061 },
4062 |_, _, _, _| {},
4063 )
4064 .absolute()
4065 .top_0()
4066 .left_0()
4067 .size_full()
4068}
4069
4070fn progress_bar() -> impl IntoElement {
4071 div()
4072 .absolute()
4073 .left_0()
4074 .right_0()
4075 .bottom(px(-1.))
4076 .h(px(2.))
4077 .overflow_hidden()
4078 .bg(theme::border())
4079 .child(
4080 div()
4081 .absolute()
4082 .top_0()
4083 .h_full()
4084 .w(relative(PROGRESS_BAR_WIDTH))
4085 .bg(theme::own_read())
4086 .with_animation(
4087 "sync-progress",
4088 Animation::new(PROGRESS_BAR_PERIOD).repeat(),
4089 |bar, delta| {
4090 let travel = 1. + PROGRESS_BAR_WIDTH;
4091 // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).
4092 bar.left(relative(
4093 (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,
4094 ))
4095 },
4096 ),
4097 )
4098}
4099
4100fn add_people_button(app: &Entity<AppState>, chat_id: &str) -> AnyElement {
4101 let (app, chat_id) = (app.clone(), chat_id.to_owned());
4102 Button::new("chat-add-people")
4103 .ghost()
4104 .compact()
4105 .icon(IconName::UserPlus)
4106 .tooltip("Add people")
4107 .on_click(move |_, window, cx| open_add_people(&app, &chat_id, true, window, cx))
4108 .into_any_element()
4109}
4110
4111fn runway(content: impl IntoElement, comfy: bool) -> AnyElement {
4112 if comfy {
4113 h_flex()
4114 .w_full()
4115 .justify_center()
4116 .child(div().w_full().max_w(px(COMFY_RUNWAY_WIDTH)).child(content))
4117 .into_any_element()
4118 } else {
4119 content.into_any_element()
4120 }
4121}
4122
4123#[cfg(test)]
4124mod tests {
4125 use std::sync::Arc;
4126
4127 use super::{DropTarget, drop_overlay_text};
4128
4129 use gpui_kit::test::TestWindowExt as _;
4130 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
4131 use store::Store;
4132
4133 use super::ConversationView;
4134 use crate::app_state::{AppState, Mode, Selection};
4135
4136 #[test]
4137 fn chat_overlay_names_the_chat_and_the_onedrive() {
4138 assert_eq!(
4139 drop_overlay_text("Mara Lin", DropTarget::Chat, 3),
4140 (
4141 "Drop to attach to Mara Lin".to_owned(),
4142 "3 files. Images go into the message, other files to your OneDrive.".to_owned()
4143 )
4144 );
4145 }
4146
4147 #[test]
4148 fn channel_overlay_points_to_the_channel_files() {
4149 let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1);
4150 assert_eq!(
4151 detail,
4152 "1 file. Images go into the message, other files to the channel's Files."
4153 );
4154 }
4155
4156 #[test]
4157 fn new_chat_overlay_says_files_wait_for_the_chat() {
4158 let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2);
4159 assert_eq!(heading, "Drop to attach to the new chat");
4160 assert_eq!(
4161 detail,
4162 "2 files. Images go into the message. Files can be added once the chat exists."
4163 );
4164 }
4165
4166 #[gpui_kit::test]
4167 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
4168 cx.update(gpui_kit::init);
4169 let store = Arc::new(Store::open_in_memory().unwrap());
4170 crate::demo::seed(&store);
4171 let mode = Mode {
4172 demo: true,
4173 read_only: false,
4174 demo_sync: None,
4175 };
4176 let (handle, app, _view) = cx.update(|cx| {
4177 let app = cx.new(|_| {
4178 let mut state = AppState::new(store, mode);
4179 crate::demo::seed_directory(&mut state);
4180 state.selection = Some(crate::demo::first_selection());
4181 state
4182 });
4183 let shared = app.clone();
4184 let (handle, view) =
4185 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
4186 cx.new(|cx| ConversationView::new(shared, window, cx))
4187 })
4188 .unwrap();
4189 (handle, app, view)
4190 });
4191 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
4192 let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| {
4193 cx.update_window(handle, move |_, window, cx| {
4194 run(window, cx);
4195 window.render_frame(cx);
4196 })
4197 .unwrap();
4198 };
4199 step(cx, |window, cx| window.render_frame(cx));
4200 step(cx, |window, cx| window.input("lea", cx));
4201 step(cx, |window, cx| window.press("enter", cx));
4202 step(cx, |window, cx| window.press("enter", cx));
4203 step(cx, |window, cx| window.input("Hello Lea", cx));
4204 step(cx, |window, cx| window.press("enter", cx));
4205 cx.update(|cx| {
4206 let state = app.read(cx);
4207 assert!(!state.new_chat);
4208 assert_eq!(
4209 state.selection,
4210 Some(Selection::Chat("demo-chat-new-1".to_owned()))
4211 );
4212 let chat = state
4213 .sidebar
4214 .chats
4215 .iter()
4216 .find(|chat| chat.id == "demo-chat-new-1")
4217 .expect("new chat in the sidebar");
4218 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea"));
4219 });
4220 }
4221
4222 #[gpui_kit::test]
4223 fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) {
4224 cx.update(gpui_kit::init);
4225 let store = Arc::new(Store::open_in_memory().unwrap());
4226 crate::demo::seed(&store);
4227 let mode = Mode {
4228 demo: true,
4229 read_only: false,
4230 demo_sync: None,
4231 };
4232 let (handle, app) = cx.update(|cx| {
4233 let app = cx.new(|_| {
4234 let mut state = AppState::new(store, mode);
4235 crate::demo::seed_directory(&mut state);
4236 state.selection = Some(crate::demo::first_selection());
4237 state
4238 });
4239 let shared = app.clone();
4240 let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
4241 cx.new(|cx| ConversationView::new(shared, window, cx))
4242 })
4243 .unwrap();
4244 (handle, app)
4245 });
4246 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
4247 cx.update_window(handle, |_, window, cx| {
4248 window.render_frame(cx);
4249 window.press("escape", cx);
4250 window.render_frame(cx);
4251 window.press("escape", cx);
4252 window.render_frame(cx);
4253 })
4254 .unwrap();
4255 cx.update(|cx| {
4256 let state = app.read(cx);
4257 assert!(!state.new_chat);
4258 assert_eq!(state.selection, Some(crate::demo::first_selection()));
4259 });
4260 }
4261}