BlueGit

ict rusty-teams

Files

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

conversation.rs

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