BlueGit

ict rusty-teams

Files

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

conversation.rs

conversation.rs 91.5 KiB Download Raw
1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::rc::Rc;
4use std::time::{Duration, Instant};
5
6use chrono::{DateTime, Local, Offset, Utc};
7use gpui_kit::assets::IconName;
8use gpui_kit::component::{
9 button::{Button, ButtonVariants as _},
10 h_flex,
11 input::Escape,
12 message_scroller::{MessageScroller, MessageScrollerState},
13 v_flex,
14};
15use gpui_kit::prelude::FluentBuilder as _;
16use gpui_kit::*;
17use store::MessageRecord;
18use teams_core::{FileCard, ImageRef, MentionInput};
19
20use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
21use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
22use super::message_actions::{Action, MessageMenu};
23use super::message_row::{RowActions, render_message_row, render_skeleton_row};
24use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
25use super::reaction_picker::{PickHandler, ReactionPicker};
26use super::widgets::{icon, symbol};
27use crate::app_state::{AppEvent, AppState, Selection, selection_title};
28use crate::data::{is_one_on_one, others};
29use crate::read_state::{ReadTrigger, plan_read};
30use crate::render::Block;
31use crate::render::blocks::Inline;
32use crate::rows::{
33 Delivery, LocalImage, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,
34 changed_indices, diff_keys, flat_rows, message_text, placeholder_rows, reaction_type_for,
35 reply_excerpt, thread_list_rows, thread_rows, trailing_skeleton,
36};
37use crate::runtime;
38use crate::sidebar_model::{AvatarSpec, Face};
39use crate::theme;
40
41const CHAT_OPEN_LIMIT: usize = 60;
42const CHANNEL_OPEN_LIMIT: usize = 300;
43const GROWTH_HEADROOM: usize = 20;
44const META_USER_ID: &str = "me_user_id";
45const PENDING_KEY_PREFIX: &str = "pending-";
46const MAX_NOTICE_CHARS: usize = 140;
47const JUMP_SCAN_LIMIT: usize = 5000;
48const JUMP_CONTEXT_MESSAGES: usize = 12;
49const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
50const PROGRESS_DELAY: Duration = Duration::from_millis(400);
51const SKELETON_DELAY: Duration = Duration::from_millis(1000);
52const SLOW_AFTER: Duration = Duration::from_secs(8);
53const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
54const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
55const PROGRESS_BAR_WIDTH: f32 = 0.35;
56
57actions!(teams, [ReplyToHovered]);
58
59#[derive(Clone, Copy)]
60enum HoverSlot {
61 Row,
62 Toolbar,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66enum ViewMode {
67 Flat,
68 ThreadList,
69 Thread(String),
70}
71
72#[derive(Default)]
73struct SyncProgress {
74 messages: bool,
75 receipts: bool,
76 empty_cache: bool,
77 newest_cached: Option<DateTime<Utc>>,
78 shown_at: Option<Instant>,
79 trailing_skeleton: bool,
80 slow: bool,
81 failed: bool,
82}
83
84impl SyncProgress {
85 fn running(&self) -> bool {
86 self.messages || self.receipts
87 }
88}
89
90struct Current {
91 selection: Selection,
92 title: String,
93 mode: ViewMode,
94 loaded_limit: usize,
95 loaded_count: usize,
96 has_older: bool,
97 loading_older: bool,
98 older_blocked: bool,
99 fetched: bool,
100 first_unread: Option<String>,
101 sync: SyncProgress,
102}
103
104pub struct ConversationView {
105 app: Entity<AppState>,
106 scroller: Entity<MessageScrollerState>,
107 composer: Entity<Composer>,
108 draft: Entity<NewChatDraft>,
109 draft_active: bool,
110 draft_created: Option<(Vec<String>, String)>,
111 draft_error: Option<String>,
112 rows: Rc<RefCell<Vec<Row>>>,
113 current: Option<Current>,
114 pending: Vec<MessageRow>,
115 pending_counter: usize,
116 pending_outgoing: HashMap<String, Outgoing>,
117 hovered_message: Option<String>,
118 toolbar_hovered: Option<String>,
119 toolbar_pinned: Option<String>,
120 picker: Entity<ReactionPicker>,
121 highlighted_message: Option<String>,
122 notice: Option<String>,
123 drag_file_count: usize,
124 sync_generation: u64,
125 window_active: bool,
126 _subscriptions: Vec<Subscription>,
127}
128
129fn open_limit(selection: &Selection) -> usize {
130 match selection {
131 Selection::Chat(_) => CHAT_OPEN_LIMIT,
132 Selection::Channel(_) => CHANNEL_OPEN_LIMIT,
133 }
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137enum DropTarget {
138 Chat,
139 Channel,
140 NewChat,
141}
142
143fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) {
144 let files = if count == 1 {
145 "1 file".to_owned()
146 } else {
147 format!("{count} files")
148 };
149 match target {
150 DropTarget::Chat => (
151 format!("Drop to attach to {title}"),
152 format!("{files}. Images go into the message, other files to your OneDrive."),
153 ),
154 DropTarget::Channel => (
155 format!("Drop to attach to {title}"),
156 format!("{files}. Images go into the message, other files to the channel's Files."),
157 ),
158 DropTarget::NewChat => (
159 "Drop to attach to the new chat".to_owned(),
160 format!(
161 "{files}. Images go into the message. Files can be added once the chat exists."
162 ),
163 ),
164 }
165}
166
167fn short_error(error: &dyn std::fmt::Display) -> String {
168 error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
169}
170
171impl ConversationView {
172 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
173 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
174 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
175 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), window, cx));
176 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
177 let subscriptions = vec![
178 cx.subscribe_in(&app, window, Self::on_app_event),
179 cx.subscribe_in(&composer, window, Self::on_composer_event),
180 cx.subscribe_in(&draft, window, Self::on_draft_event),
181 cx.observe_window_activation(window, Self::on_window_activation),
182 ];
183 let mut view = ConversationView {
184 app,
185 scroller,
186 composer,
187 draft,
188 draft_active: false,
189 draft_created: None,
190 draft_error: None,
191 rows: Rc::new(RefCell::new(Vec::new())),
192 current: None,
193 pending: Vec::new(),
194 pending_counter: 0,
195 pending_outgoing: HashMap::new(),
196 hovered_message: None,
197 toolbar_hovered: None,
198 toolbar_pinned: None,
199 picker,
200 highlighted_message: None,
201 notice: None,
202 drag_file_count: 0,
203 sync_generation: 0,
204 window_active: window.is_window_active(),
205 _subscriptions: subscriptions,
206 };
207 if let Some(selection) = view.app.read(cx).selection.clone() {
208 view.open(selection, window, cx);
209 }
210 view
211 }
212
213 #[cfg_attr(not(windows), allow(dead_code))]
214 pub fn composer_is_empty(&self, cx: &App) -> bool {
215 self.composer.read(cx).is_empty(cx)
216 }
217
218 #[cfg_attr(not(windows), allow(dead_code))]
219 pub fn send_in_flight(&self) -> bool {
220 self.pending
221 .iter()
222 .any(|row| matches!(row.delivery, Delivery::Sending))
223 }
224
225 fn on_window_activation(&mut self, window: &mut Window, cx: &mut Context<Self>) {
226 self.window_active = window.is_window_active();
227 self.mark_read(ReadTrigger::Activation, cx);
228 }
229
230 fn on_app_event(
231 &mut self,
232 _: &Entity<AppState>,
233 event: &AppEvent,
234 window: &mut Window,
235 cx: &mut Context<Self>,
236 ) {
237 match event {
238 AppEvent::Selection => {
239 let (new_chat, selection) = {
240 let state = self.app.read(cx);
241 (state.new_chat, state.selection.clone())
242 };
243 if new_chat {
244 self.enter_draft(window, cx);
245 return;
246 }
247 if self.draft_active {
248 let created = self
249 .draft_created
250 .as_ref()
251 .map(|(_, chat_id)| chat_id.clone());
252 if let Some(chat_id) = created {
253 self.composer
254 .update(cx, |composer, _| composer.carry_images_into(chat_id));
255 }
256 self.leave_draft(window, cx);
257 }
258 match selection {
259 Some(selection) => self.open(selection, window, cx),
260 None => {
261 self.current = None;
262 self.rebuild(true, cx);
263 }
264 }
265 }
266 AppEvent::Messages(conversation_id) => {
267 let is_current = self
268 .current
269 .as_ref()
270 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
271 if is_current {
272 self.rebuild(false, cx);
273 self.mark_read(ReadTrigger::Incoming, cx);
274 }
275 }
276 AppEvent::Images(keys) => self.remeasure_images(keys, cx),
277 AppEvent::Jump => self.apply_pending_jump(cx),
278 AppEvent::Status => {
279 if let Some(current) = self.current.as_mut()
280 && current.sync.failed
281 {
282 current.fetched = false;
283 }
284 self.start_fetch(cx)
285 }
286 AppEvent::Directory => cx.notify(),
287 AppEvent::Sidebar => {
288 self.mark_read(ReadTrigger::Incoming, cx);
289 if self.draft_active {
290 self.on_draft_changed(window, cx);
291 } else if let Some(current) = self.current.as_mut() {
292 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
293 if current.title != title {
294 current.title = title.clone();
295 let conversation_id = current.selection.conversation_id().to_owned();
296 self.composer.update(cx, |composer, cx| {
297 composer.set_conversation(&conversation_id, &title, window, cx)
298 });
299 cx.notify();
300 }
301 }
302 }
303 }
304 }
305
306 fn on_composer_event(
307 &mut self,
308 _: &Entity<Composer>,
309 event: &ComposerEvent,
310 window: &mut Window,
311 cx: &mut Context<Self>,
312 ) {
313 match event {
314 ComposerEvent::Submit(outgoing) if self.draft_active => {
315 self.send_new_chat((**outgoing).clone(), window, cx)
316 }
317 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
318 self.send_edit((**outgoing).clone(), window, cx)
319 }
320 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
321 ComposerEvent::EditLast => self.edit_last_own(window, cx),
322 }
323 }
324
325 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
326 self.toolbar_hovered = None;
327 self.toolbar_pinned = None;
328 let title = selection_title(&self.app.read(cx).sidebar, &selection);
329 let mode = match selection {
330 Selection::Chat(_) => ViewMode::Flat,
331 Selection::Channel(_) => ViewMode::ThreadList,
332 };
333 let first_unread = self.first_unread_id(&selection, cx);
334 self.current = Some(Current {
335 loaded_limit: open_limit(&selection),
336 selection,
337 title,
338 mode,
339 loaded_count: 0,
340 has_older: false,
341 loading_older: false,
342 older_blocked: false,
343 fetched: false,
344 first_unread,
345 sync: SyncProgress::default(),
346 });
347 self.sync_generation += 1;
348 self.clear_pending();
349 self.notice = None;
350 self.rebuild(true, cx);
351 self.start_fetch(cx);
352 self.mark_read(ReadTrigger::Open, cx);
353 let target = self
354 .current
355 .as_ref()
356 .map(|current| {
357 (
358 current.selection.conversation_id().to_owned(),
359 current.title.clone(),
360 )
361 })
362 .unwrap_or_default();
363 self.composer.update(cx, |composer, cx| {
364 composer.set_conversation(&target.0, &target.1, window, cx);
365 });
366 if !self.draft_active {
367 self.composer
368 .update(cx, |composer, cx| composer.focus(window, cx));
369 }
370 self.hovered_message = None;
371 self.apply_pending_jump(cx);
372 }
373
374 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
375 if !self.draft_active {
376 self.draft_active = true;
377 self.current = None;
378 self.clear_pending();
379 self.notice = None;
380 self.draft_created = None;
381 self.draft_error = None;
382 self.toolbar_hovered = None;
383 self.toolbar_pinned = None;
384 self.hovered_message = None;
385 self.sync_generation += 1;
386 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
387 self.composer.update(cx, |composer, cx| {
388 composer.set_conversation("", "", window, cx)
389 });
390 self.on_draft_changed(window, cx);
391 self.rebuild(true, cx);
392 }
393 self.draft
394 .update(cx, |draft, cx| draft.focus_query(window, cx));
395 cx.notify();
396 }
397
398 fn leave_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
399 self.draft_active = false;
400 self.draft_created = None;
401 self.draft_error = None;
402 self.clear_pending();
403 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
404 }
405
406 fn on_draft_event(
407 &mut self,
408 _: &Entity<NewChatDraft>,
409 event: &NewChatEvent,
410 window: &mut Window,
411 cx: &mut Context<Self>,
412 ) {
413 match event {
414 NewChatEvent::Changed => self.on_draft_changed(window, cx),
415 NewChatEvent::FocusComposer => self
416 .composer
417 .update(cx, |composer, cx| composer.focus(window, cx)),
418 NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)),
419 }
420 }
421
422 fn draft_target_chat(&self, cx: &App) -> Option<String> {
423 let chips = self.draft.read(cx).chips();
424 let [chip] = chips else {
425 return None;
426 };
427 let state = self.app.read(cx);
428 existing_one_on_one(
429 &state.sidebar.chats,
430 state.directory.me.as_ref(),
431 &chip.user_id,
432 )
433 .map(|chat| chat.id.clone())
434 }
435
436 fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
437 if !self.draft_active {
438 return;
439 }
440 let target = self.draft_target_chat(cx);
441 if target != self.conversation_id() {
442 match target {
443 Some(chat_id) => {
444 self.composer.update(cx, |composer, _| {
445 composer.carry_images_into(chat_id.clone())
446 });
447 self.open(Selection::Chat(chat_id), window, cx)
448 }
449 None => {
450 self.composer.update(cx, |composer, cx| {
451 composer.carry_images_into(String::new());
452 composer.set_conversation("", "", window, cx);
453 });
454 self.current = None;
455 self.sync_generation += 1;
456 self.rebuild(true, cx);
457 }
458 }
459 }
460 let placeholder = {
461 let draft = self.draft.read(cx);
462 composer_placeholder(draft.chips(), &draft.group_name(cx))
463 };
464 self.composer.update(cx, |composer, cx| {
465 composer.set_placeholder(&placeholder, window, cx)
466 });
467 cx.notify();
468 }
469
470 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
471 let indices: Vec<usize> = self
472 .rows
473 .borrow()
474 .iter()
475 .enumerate()
476 .filter_map(|(index, row)| match row {
477 Row::Message(message)
478 if message.images.iter().any(|image| keys.contains(&image.url)) =>
479 {
480 Some(index)
481 }
482 _ => None,
483 })
484 .collect();
485 self.scroller.update(cx, |scroller, cx| {
486 for index in indices {
487 scroller.remeasure_items(index..index + 1, cx);
488 }
489 });
490 cx.notify();
491 }
492
493 fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {
494 let Some(conversation_id) = self
495 .current
496 .as_ref()
497 .map(|current| current.selection.conversation_id().to_owned())
498 else {
499 return;
500 };
501 let jump = self
502 .app
503 .update(cx, |state, _| match state.pending_jump.take() {
504 Some((target, message_id)) if target == conversation_id => Some(message_id),
505 other => {
506 state.pending_jump = other;
507 None
508 }
509 });
510 if let Some(message_id) = jump {
511 self.jump_to_message(&conversation_id, &message_id, cx);
512 }
513 }
514
515 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
516 let store = self.app.read(cx).store.clone();
517 let Some(record) = store
518 .messages_by_id(conversation_id, &[message_id.to_owned()])
519 .ok()
520 .and_then(|mut found| found.remove(message_id))
521 else {
522 return;
523 };
524 let messages_from_target = store
525 .messages(conversation_id, None, JUMP_SCAN_LIMIT)
526 .ok()
527 .and_then(|all| {
528 all.iter()
529 .position(|candidate| candidate.message_id == message_id)
530 .map(|position| all.len() - position)
531 })
532 .unwrap_or_default();
533 let row_key = record
534 .reply_to_id
535 .clone()
536 .unwrap_or_else(|| message_id.to_owned());
537 let Some(current) = self.current.as_mut() else {
538 return;
539 };
540 current.loaded_limit = current
541 .loaded_limit
542 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
543 current.first_unread = None;
544 if matches!(current.selection, Selection::Channel(_)) {
545 current.mode = match record.reply_to_id {
546 Some(root_id) => ViewMode::Thread(root_id),
547 None => ViewMode::ThreadList,
548 };
549 }
550 let target_key = if matches!(current.mode, ViewMode::Thread(_)) {
551 message_id.to_owned()
552 } else {
553 row_key
554 };
555 self.clear_pending();
556 self.rebuild(true, cx);
557 let index = self
558 .rows
559 .borrow()
560 .iter()
561 .position(|row| row.key() == target_key);
562 if let Some(index) = index {
563 self.scroller
564 .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx));
565 self.highlight(target_key, cx);
566 }
567 }
568
569 fn highlight(&mut self, key: String, cx: &mut Context<Self>) {
570 self.highlighted_message = Some(key.clone());
571 cx.notify();
572 cx.spawn(async move |this, cx| {
573 cx.background_executor().timer(HIGHLIGHT_DURATION).await;
574 this.update(cx, |this, cx| {
575 if this.highlighted_message.as_deref() == Some(key.as_str()) {
576 this.highlighted_message = None;
577 cx.notify();
578 }
579 })
580 .ok();
581 })
582 .detach();
583 }
584
585 pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
586 self.composer
587 .update(cx, |composer, cx| composer.set_text(text, window, cx));
588 self.composer
589 .update(cx, |composer, cx| composer.focus(window, cx));
590 }
591
592 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
593 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
594 Row::Message(message) if !message.own => Some(message.key.clone()),
595 _ => None,
596 });
597 if let Some(key) = key {
598 self.begin_reply(&key, window, cx);
599 }
600 }
601
602 pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) {
603 if let Some(message_id) = self.hovered_message.clone() {
604 self.begin_reply(&message_id, window, cx);
605 }
606 }
607
608 fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
609 let Some(conversation_id) = self
610 .current
611 .as_ref()
612 .map(|current| current.selection.conversation_id().to_owned())
613 else {
614 return;
615 };
616 let store = self.app.read(cx).store.clone();
617 let record = store
618 .messages_by_id(&conversation_id, &[message_id.to_owned()])
619 .ok()
620 .and_then(|mut found| found.remove(message_id))
621 .filter(|record| !record.deleted);
622 let Some(record) = record else {
623 return;
624 };
625 let preview = ReplyPreview {
626 message_id: record.message_id.clone(),
627 author: record
628 .sender_name
629 .clone()
630 .unwrap_or_else(|| "Unknown".to_owned()),
631 excerpt: reply_excerpt(&record),
632 };
633 self.composer.update(cx, |composer, cx| {
634 composer.set_reply(Some(preview), cx);
635 composer.focus(window, cx);
636 });
637 }
638
639 fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> {
640 let Selection::Chat(chat_id) = selection else {
641 return None;
642 };
643 let state = self.app.read(cx);
644 if state.mode.demo {
645 return crate::demo::first_unread(chat_id);
646 }
647 state.engine.as_ref()?.first_unread_message_id(chat_id)
648 }
649
650 fn row_context(&self, cx: &App) -> RowContext {
651 let now = Local::now();
652 RowContext {
653 offset: now.offset().fix(),
654 today: now.date_naive(),
655 my_user_id: self.app.read(cx).store.meta(META_USER_ID).ok().flatten(),
656 }
657 }
658
659 fn start_info(&self, cx: &App) -> Option<StartInfo> {
660 let current = self.current.as_ref()?;
661 let app = self.app.read(cx);
662 let user_id = match &current.selection {
663 Selection::Chat(chat_id) => app
664 .sidebar
665 .chats
666 .iter()
667 .find(|chat| &chat.id == chat_id)
668 .filter(|chat| is_one_on_one(chat))
669 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next())
670 .and_then(|(user_id, _)| user_id),
671 Selection::Channel(_) => None,
672 };
673 Some(StartInfo {
674 title: current.title.clone(),
675 user_id,
676 })
677 }
678
679 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
680 let Some(current) = self.current.as_ref() else {
681 let mut rows: Vec<Row> = self
682 .pending
683 .iter()
684 .cloned()
685 .map(|row| Row::Message(Box::new(row)))
686 .collect();
687 assign_series(&mut rows);
688 self.apply_rows(rows, true, cx);
689 return;
690 };
691 let conversation_id = current.selection.conversation_id().to_owned();
692 let limit = if reset {
693 current.loaded_limit
694 } else {
695 current
696 .loaded_limit
697 .max(current.loaded_count + GROWTH_HEADROOM)
698 };
699 let store = self.app.read(cx).store.clone();
700 let records: Vec<MessageRecord> = store
701 .messages(&conversation_id, None, limit)
702 .unwrap_or_default();
703 let sync_has_more = store
704 .sync_state(&conversation_id)
705 .ok()
706 .flatten()
707 .is_none_or(|state| state.has_more);
708 let context = self.row_context(cx);
709 let can_load_older = self.app.read(cx).engine.is_some();
710 let start = self.start_info(cx);
711 let current = self.current.as_mut().expect("checked above");
712 let first_unread = current.first_unread.clone();
713 current.loaded_limit = limit;
714 current.loaded_count = records.len();
715 let has_older = sync_has_more && !current.older_blocked && can_load_older;
716 let placeholders = current.sync.messages
717 && records.is_empty()
718 && !matches!(current.mode, ViewMode::Thread(_));
719 let trailing = current.sync.trailing_skeleton && current.mode == ViewMode::Flat;
720 let mut rows = match &current.mode {
721 _ if placeholders => {
722 current.has_older = false;
723 placeholder_rows()
724 }
725 ViewMode::Flat => {
726 current.has_older = has_older;
727 let mut rows = flat_rows(&records, &context, has_older);
728 if !has_older && let Some(start) = start {
729 rows.insert(0, Row::Start(start));
730 }
731 rows
732 }
733 ViewMode::ThreadList => {
734 current.has_older = has_older;
735 thread_list_rows(&records, &context, has_older)
736 }
737 ViewMode::Thread(root_id) => {
738 current.has_older = false;
739 thread_rows(&records, root_id, &context)
740 }
741 };
742 if trailing && !placeholders {
743 rows.push(trailing_skeleton());
744 }
745 rows.extend(
746 self.pending
747 .iter()
748 .cloned()
749 .map(|row| Row::Message(Box::new(row))),
750 );
751 let receipts = self.receipts(&records, cx);
752 for row in rows.iter_mut() {
753 if let Row::Message(message) = row
754 && message.own
755 {
756 message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
757 }
758 }
759 if let Some(unread_id) = &first_unread {
760 for row in rows.iter_mut() {
761 if let Row::Message(message) = row
762 && &message.key == unread_id
763 {
764 message.new_marker = true;
765 }
766 }
767 }
768 assign_series(&mut rows);
769 self.apply_rows(rows, reset, cx);
770 }
771
772 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
773 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
774 let new_len = self.rows.borrow().len();
775 if reset {
776 let marker_index = self
777 .rows
778 .borrow()
779 .iter()
780 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
781 self.scroller.update(cx, |scroller, cx| {
782 scroller.reset(new_len, cx);
783 match marker_index {
784 Some(index) if !scroller.scroll_to_item(index, cx) => {
785 scroller.scroll_to_end(cx)
786 }
787 Some(_) => {}
788 None => scroller.scroll_to_end(cx),
789 }
790 });
791 cx.notify();
792 return;
793 }
794 let (splice, changed) = {
795 let new_rows = self.rows.borrow();
796 let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect();
797 let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect();
798 (
799 diff_keys(&old_keys, &new_keys),
800 changed_indices(&old_rows, &new_rows),
801 )
802 };
803 self.scroller.update(cx, |scroller, cx| {
804 if let Some(splice) = splice
805 && !scroller.splice(splice.range, splice.count, cx)
806 {
807 scroller.reset(new_len, cx);
808 }
809 for index in changed {
810 scroller.remeasure_items(index..index + 1, cx);
811 }
812 });
813 cx.notify();
814 }
815
816 fn start_fetch(&mut self, cx: &mut Context<Self>) {
817 let state = self.app.read(cx);
818 let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync);
819 if engine.is_none() && demo_sync.is_none() {
820 return;
821 }
822 let Some(current) = self.current.as_mut() else {
823 return;
824 };
825 if current.fetched {
826 return;
827 }
828 current.fetched = true;
829 let is_chat = matches!(current.selection, Selection::Chat(_));
830 let newest_cached = self.rows.borrow().iter().rev().find_map(|row| match row {
831 Row::Message(message) if !message.key.starts_with(PENDING_KEY_PREFIX) => {
832 Some(message.created_at)
833 }
834 _ => None,
835 });
836 let current = self.current.as_mut().expect("checked above");
837 if current.sync.failed {
838 self.notice = None;
839 }
840 current.sync = SyncProgress {
841 messages: true,
842 receipts: is_chat,
843 empty_cache: newest_cached.is_none(),
844 newest_cached,
845 ..SyncProgress::default()
846 };
847 self.sync_generation += 1;
848 let generation = self.sync_generation;
849 let conversation_id = current.selection.conversation_id().to_owned();
850 match (engine, demo_sync) {
851 (Some(engine), _) => {
852 let receiver =
853 runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
854 cx.spawn(async move |this, cx| {
855 let result = receiver.await;
856 this.update(cx, |this, cx| this.finish_fetch(generation, result, cx))
857 .ok();
858 })
859 .detach();
860 }
861 (None, Some(delay)) => self.simulate_sync(generation, delay, cx),
862 (None, None) => {}
863 }
864 self.schedule_progress(generation, cx);
865 self.rebuild(false, cx);
866 self.mark_read(ReadTrigger::Incoming, cx);
867 self.refresh_receipts(generation, cx);
868 }
869
870 fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) {
871 cx.spawn(async move |this, cx| {
872 cx.background_executor().timer(delay).await;
873 this.update(cx, |this, cx| {
874 if let Some(sync) = this.sync_of(generation) {
875 sync.receipts = false;
876 }
877 this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx)
878 })
879 .ok();
880 })
881 .detach();
882 }
883
884 fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> {
885 if generation != self.sync_generation {
886 return None;
887 }
888 self.current.as_mut().map(|current| &mut current.sync)
889 }
890
891 fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
892 cx.spawn(async move |this, cx| {
893 let stages = [
894 (PROGRESS_DELAY, Duration::ZERO),
895 (SKELETON_DELAY, PROGRESS_DELAY),
896 (SLOW_AFTER, SKELETON_DELAY),
897 ];
898 for (stage, (at, previous)) in stages.into_iter().enumerate() {
899 cx.background_executor().timer(at - previous).await;
900 let running = this
901 .update(cx, |this, cx| this.advance_progress(generation, stage, cx))
902 .unwrap_or(false);
903 if !running {
904 return;
905 }
906 }
907 })
908 .detach();
909 }
910
911 fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool {
912 let Some(sync) = self.sync_of(generation) else {
913 return false;
914 };
915 if !sync.running() {
916 return false;
917 }
918 match stage {
919 0 => sync.shown_at = Some(Instant::now()),
920 1 if sync.messages => {
921 sync.trailing_skeleton = true;
922 self.rebuild(false, cx);
923 }
924 1 => {}
925 _ => sync.slow = true,
926 }
927 cx.notify();
928 true
929 }
930
931 fn finish_fetch(
932 &mut self,
933 generation: u64,
934 result: Result<
935 teams_core::Result<teams_core::Delta>,
936 tokio::sync::oneshot::error::RecvError,
937 >,
938 cx: &mut Context<Self>,
939 ) {
940 let Some(sync) = self.sync_of(generation) else {
941 return;
942 };
943 sync.messages = false;
944 sync.trailing_skeleton = false;
945 let newest_cached = sync.newest_cached;
946 match result {
947 Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx),
948 Ok(Err(error)) => self.fail_sync(generation, short_error(&error)),
949 Err(error) => self.fail_sync(generation, short_error(&error)),
950 }
951 self.rebuild(false, cx);
952 self.settle_progress(generation, cx);
953 }
954
955 fn fail_sync(&mut self, generation: u64, error: String) {
956 if let Some(sync) = self.sync_of(generation) {
957 sync.failed = true;
958 sync.receipts = false;
959 }
960 self.notice = Some(format!("Could not refresh: {error}"));
961 }
962
963 fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) {
964 let Some(newest_cached) = newest_cached else {
965 return;
966 };
967 let Some(my_user_id) = self.row_context(cx).my_user_id else {
968 return;
969 };
970 let store = self.app.read(cx).store.clone();
971 let Some(current) = self.current.as_mut() else {
972 return;
973 };
974 if current.first_unread.is_some() || current.mode != ViewMode::Flat {
975 return;
976 }
977 let limit = current
978 .loaded_limit
979 .max(current.loaded_count + GROWTH_HEADROOM);
980 current.first_unread = store
981 .messages(current.selection.conversation_id(), None, limit)
982 .unwrap_or_default()
983 .into_iter()
984 .find(|record| {
985 record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id)
986 })
987 .map(|record| record.message_id);
988 }
989
990 fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
991 let Some(sync) = self.sync_of(generation) else {
992 return;
993 };
994 if sync.running() {
995 return;
996 }
997 let remaining = sync
998 .shown_at
999 .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed()))
1000 .unwrap_or_default();
1001 if remaining.is_zero() {
1002 sync.shown_at = None;
1003 sync.slow = false;
1004 cx.notify();
1005 return;
1006 }
1007 cx.spawn(async move |this, cx| {
1008 cx.background_executor().timer(remaining).await;
1009 this.update(cx, |this, cx| {
1010 if let Some(sync) = this.sync_of(generation) {
1011 sync.shown_at = None;
1012 sync.slow = false;
1013 cx.notify();
1014 }
1015 })
1016 .ok();
1017 })
1018 .detach();
1019 }
1020
1021 fn retry_fetch(&mut self, cx: &mut Context<Self>) {
1022 if let Some(current) = self.current.as_mut() {
1023 current.fetched = false;
1024 }
1025 self.start_fetch(cx);
1026 }
1027
1028 fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1029 let state = self.app.read(cx);
1030 let receipts_syncing = self
1031 .current
1032 .as_ref()
1033 .is_some_and(|current| current.sync.receipts);
1034 if state.mode.demo {
1035 let read_ids = crate::demo::read_message_ids(records);
1036 return records
1037 .iter()
1038 .map(|record| {
1039 let receipt = if receipts_syncing {
1040 Receipt::Pending
1041 } else if read_ids.contains(&record.message_id) {
1042 Receipt::Read
1043 } else {
1044 Receipt::Sent
1045 };
1046 (record.message_id.clone(), receipt)
1047 })
1048 .collect();
1049 }
1050 let Some(engine) = state.engine.as_ref() else {
1051 return HashMap::new();
1052 };
1053 let unknown = if receipts_syncing {
1054 Receipt::Pending
1055 } else {
1056 Receipt::Hidden
1057 };
1058 records
1059 .iter()
1060 .map(|record| {
1061 let receipt = match engine.receipt_state_for(record) {
1062 teams_core::ReceiptState::Read { .. } => Receipt::Read,
1063 teams_core::ReceiptState::Sent => Receipt::Sent,
1064 teams_core::ReceiptState::Unknown => unknown,
1065 };
1066 (record.message_id.clone(), receipt)
1067 })
1068 .collect()
1069 }
1070
1071 fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {
1072 let state = self.app.read(cx);
1073 let (Some(engine), Some(Selection::Chat(chat_id))) = (
1074 state.engine.clone(),
1075 self.current.as_ref().map(|c| c.selection.clone()),
1076 ) else {
1077 return;
1078 };
1079 let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await });
1080 cx.spawn(async move |this, cx| {
1081 receiver.await.ok();
1082 this.update(cx, |this, cx| {
1083 let Some(sync) = this.sync_of(generation) else {
1084 return;
1085 };
1086 sync.receipts = false;
1087 this.rebuild(false, cx);
1088 this.settle_progress(generation, cx);
1089 })
1090 .ok();
1091 })
1092 .detach();
1093 }
1094
1095 fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) {
1096 if self.draft_active {
1097 return;
1098 }
1099 let state = self.app.read(cx);
1100 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
1101 else {
1102 return;
1103 };
1104 if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only {
1105 return;
1106 }
1107 let unread = state
1108 .sidebar
1109 .chats
1110 .iter()
1111 .any(|chat| chat.id == chat_id && chat.unread);
1112 let Some(plan) = plan_read(self.window_active, unread, trigger) else {
1113 return;
1114 };
1115 self.app
1116 .update(cx, |state, cx| state.mark_chat_read(&chat_id, cx));
1117 if plan.clear_divider
1118 && let Some(current) = self.current.as_mut()
1119 && current.first_unread.take().is_some()
1120 {
1121 self.rebuild(false, cx);
1122 }
1123 }
1124
1125 fn request_older(&mut self, cx: &mut Context<Self>) {
1126 let Some(engine) = self.app.read(cx).engine.clone() else {
1127 return;
1128 };
1129 let Some(current) = self.current.as_mut() else {
1130 return;
1131 };
1132 if current.loading_older || current.older_blocked || !current.has_older {
1133 return;
1134 }
1135 current.loading_older = true;
1136 let conversation_id = current.selection.conversation_id().to_owned();
1137 let task_id = conversation_id.clone();
1138 let receiver = runtime::spawn(async move { engine.load_older(&task_id).await });
1139 cx.spawn(async move |this, cx| {
1140 let result = receiver.await;
1141 this.update(cx, |this, cx| {
1142 this.finish_older(&conversation_id, result, cx)
1143 })
1144 .ok();
1145 })
1146 .detach();
1147 }
1148
1149 fn finish_older(
1150 &mut self,
1151 conversation_id: &str,
1152 result: Result<
1153 teams_core::Result<Vec<MessageRecord>>,
1154 tokio::sync::oneshot::error::RecvError,
1155 >,
1156 cx: &mut Context<Self>,
1157 ) {
1158 let Some(current) = self.current.as_mut() else {
1159 return;
1160 };
1161 if current.selection.conversation_id() != conversation_id {
1162 return;
1163 }
1164 current.loading_older = false;
1165 match result {
1166 Ok(Ok(records)) if !records.is_empty() => {
1167 current.loaded_limit = current.loaded_count + records.len();
1168 }
1169 Ok(Ok(_)) => current.older_blocked = true,
1170 Ok(Err(error)) => {
1171 current.older_blocked = true;
1172 self.notice = Some(format!(
1173 "Could not load older messages: {}",
1174 short_error(&error)
1175 ));
1176 }
1177 Err(_) => current.older_blocked = true,
1178 }
1179 self.rebuild(false, cx);
1180 }
1181
1182 fn clear_pending(&mut self) {
1183 self.pending.clear();
1184 self.pending_outgoing.clear();
1185 }
1186
1187 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1188 if let Some(current) = self.current.as_mut() {
1189 current.mode = ViewMode::Thread(root_id);
1190 }
1191 self.clear_pending();
1192 self.rebuild(true, cx);
1193 }
1194
1195 fn back_to_threads(&mut self, cx: &mut Context<Self>) {
1196 if let Some(current) = self.current.as_mut() {
1197 current.mode = ViewMode::ThreadList;
1198 }
1199 self.clear_pending();
1200 self.rebuild(true, cx);
1201 }
1202
1203 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1204 let state = self.app.read(cx);
1205 let (mode, engine) = (state.mode, state.engine.clone());
1206 let Some(current) = self.current.as_ref() else {
1207 return;
1208 };
1209 if mode.read_only || mode.demo {
1210 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1211 return;
1212 }
1213 let Some(engine) = engine else {
1214 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1215 return;
1216 };
1217 let conversation_id = current.selection.conversation_id().to_owned();
1218 let view_mode = current.mode.clone();
1219 let key = self.push_pending(&outgoing, cx);
1220 self.notice = None;
1221 self.rebuild(false, cx);
1222 self.scroller
1223 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
1224
1225 let sent = outgoing.clone();
1226 let receiver = runtime::spawn(async move {
1227 let extras = sent.extras();
1228 let Outgoing {
1229 text,
1230 mentions,
1231 reply,
1232 ..
1233 } = &sent;
1234 match (&view_mode, reply) {
1235 (_, Some(reply)) => {
1236 engine
1237 .reply_to_with_extras(
1238 &conversation_id,
1239 &reply.message_id,
1240 text,
1241 mentions,
1242 &extras,
1243 )
1244 .await
1245 }
1246 (ViewMode::Flat, None) => {
1247 engine
1248 .send_message_with_extras(&conversation_id, text, None, mentions, &extras)
1249 .await
1250 }
1251 (ViewMode::ThreadList, None) => {
1252 engine
1253 .post_to_channel_with_extras(
1254 &conversation_id,
1255 text,
1256 None,
1257 mentions,
1258 &extras,
1259 )
1260 .await
1261 }
1262 (ViewMode::Thread(root_id), None) => {
1263 engine
1264 .send_message_with_extras(
1265 &conversation_id,
1266 text,
1267 Some(root_id),
1268 mentions,
1269 &extras,
1270 )
1271 .await
1272 }
1273 }
1274 .map(|_| ())
1275 });
1276 cx.spawn_in(window, async move |this, cx| {
1277 let result = receiver.await;
1278 this.update(cx, |this, cx| this.finish_send(&key, result, cx))
1279 .ok();
1280 })
1281 .detach();
1282 }
1283
1284 fn restore_unsent(
1285 &mut self,
1286 message: &str,
1287 outgoing: &Outgoing,
1288 window: &mut Window,
1289 cx: &mut Context<Self>,
1290 ) {
1291 self.notice = Some(message.to_owned());
1292 self.composer
1293 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
1294 cx.notify();
1295 }
1296
1297 fn push_pending(&mut self, outgoing: &Outgoing, cx: &App) -> String {
1298 self.pending_counter += 1;
1299 let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
1300 let my_user_id = self.row_context(cx).my_user_id;
1301 self.pending_outgoing.insert(key.clone(), outgoing.clone());
1302 self.pending.push(MessageRow {
1303 key: key.clone(),
1304 author: "You".to_owned(),
1305 sender_id: my_user_id,
1306 created_at: Utc::now(),
1307 series: Series::default(),
1308 card: false,
1309 time: chrono::Local::now().format("%H:%M").to_string(),
1310 day_header: None,
1311 blocks: if outgoing.text.is_empty() {
1312 Vec::new()
1313 } else {
1314 vec![Block::Paragraph(Inline::plain(&outgoing.text))]
1315 },
1316 edited: false,
1317 deleted: false,
1318 reactions: Vec::new(),
1319 images: Vec::new(),
1320 local_images: outgoing
1321 .images
1322 .iter()
1323 .map(|image| LocalImage {
1324 image: image.image.clone(),
1325 size: image.dimensions,
1326 })
1327 .collect(),
1328 files: outgoing
1329 .files
1330 .iter()
1331 .map(|file| FileCard {
1332 name: file.name.clone(),
1333 kind: file.kind,
1334 content_type: None,
1335 size: Some(file.size),
1336 open_url: file.reference.content_url.clone(),
1337 })
1338 .collect(),
1339 reply_count: None,
1340 new_marker: false,
1341 reply_faces: Vec::new(),
1342 last_reply_time: None,
1343 open_thread: None,
1344 is_reply: false,
1345 delivery: Delivery::Sending,
1346 receipt: Receipt::Hidden,
1347 own: true,
1348 });
1349 key
1350 }
1351
1352 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1353 let (recipients, topic) = {
1354 let draft = self.draft.read(cx);
1355 let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty());
1356 (draft.chips().to_vec(), topic)
1357 };
1358 if recipients.is_empty() {
1359 self.restore_unsent("Add at least one person first", &outgoing, window, cx);
1360 self.draft
1361 .update(cx, |draft, cx| draft.focus_query(window, cx));
1362 return;
1363 }
1364 if self
1365 .pending
1366 .iter()
1367 .any(|row| matches!(row.delivery, Delivery::Sending))
1368 {
1369 self.restore_unsent("Still creating the chat", &outgoing, window, cx);
1370 return;
1371 }
1372 let state = self.app.read(cx);
1373 let (mode, engine) = (state.mode, state.engine.clone());
1374 if mode.read_only {
1375 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1376 return;
1377 }
1378 if mode.demo && outgoing.has_attachments() {
1379 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1380 return;
1381 }
1382 if mode.demo {
1383 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
1384 return;
1385 }
1386 let Some(engine) = engine else {
1387 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1388 return;
1389 };
1390 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
1391 let known_chat = self
1392 .draft_created
1393 .as_ref()
1394 .filter(|(created_for, _)| *created_for == user_ids)
1395 .map(|(_, chat_id)| chat_id.clone())
1396 .or_else(|| self.draft_target_chat(cx));
1397 self.pending.clear();
1398 self.pending_outgoing.clear();
1399 self.draft_error = None;
1400 self.notice = None;
1401 let key = self.push_pending(&outgoing, cx);
1402 self.rebuild(true, cx);
1403 let recipients_for_finish = user_ids.clone();
1404 let receiver = runtime::spawn(async move {
1405 let chat_id = match known_chat {
1406 Some(chat_id) => chat_id,
1407 None => {
1408 let created = match user_ids.as_slice() {
1409 [user_id] => engine.create_one_on_one(user_id).await,
1410 _ => engine.create_group(&user_ids, topic.as_deref()).await,
1411 };
1412 match created {
1413 Ok(chat_id) => chat_id,
1414 Err(error) => return (None, Some(short_error(&error))),
1415 }
1416 }
1417 };
1418 let sent = engine
1419 .send_message_with_extras(
1420 &chat_id,
1421 &outgoing.text,
1422 None,
1423 &outgoing.mentions,
1424 &outgoing.extras(),
1425 )
1426 .await;
1427 (Some(chat_id), sent.err().map(|error| short_error(&error)))
1428 });
1429 cx.spawn_in(window, async move |this, cx| {
1430 let result = receiver.await;
1431 this.update_in(cx, |this, _, cx| {
1432 this.finish_new_chat(&key, recipients_for_finish, result, cx)
1433 })
1434 .ok();
1435 })
1436 .detach();
1437 }
1438
1439 fn finish_new_chat(
1440 &mut self,
1441 key: &str,
1442 user_ids: Vec<String>,
1443 result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>,
1444 cx: &mut Context<Self>,
1445 ) {
1446 if !self.draft_active || !self.pending.iter().any(|row| row.key == key) {
1447 return;
1448 }
1449 let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned())));
1450 self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id));
1451 match (chat_id, error) {
1452 (Some(chat_id), None) => {
1453 self.app.update(cx, |state, cx| {
1454 state.reload_sidebar(cx);
1455 state.select(Selection::Chat(chat_id), cx);
1456 });
1457 }
1458 (created, error) => {
1459 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
1460 row.delivery = Delivery::Failed(error.unwrap_or_default());
1461 }
1462 self.draft_error = Some(
1463 if created.is_some() {
1464 "Couldn't send the message."
1465 } else {
1466 "Couldn't create the chat."
1467 }
1468 .to_owned(),
1469 );
1470 self.rebuild(false, cx);
1471 }
1472 }
1473 }
1474
1475 fn send_demo_new_chat(
1476 &mut self,
1477 outgoing: &Outgoing,
1478 recipients: &[super::new_chat::Pick],
1479 topic: Option<&str>,
1480 cx: &mut Context<Self>,
1481 ) {
1482 let (store, chats) = {
1483 let state = self.app.read(cx);
1484 (state.store.clone(), state.sidebar.chats.clone())
1485 };
1486 let people: Vec<(String, String)> = recipients
1487 .iter()
1488 .map(|pick| (pick.user_id.clone(), pick.name.clone()))
1489 .collect();
1490 let (chat, message) = match self.draft_target_chat(cx) {
1491 Some(chat_id) => {
1492 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
1493 return;
1494 };
1495 crate::demo::send_in_chat(chat, &outgoing.text, Utc::now())
1496 }
1497 None => crate::demo::new_chat(&chats, &people, topic, &outgoing.text, Utc::now()),
1498 };
1499 let _ = store.upsert_chats(std::slice::from_ref(&chat));
1500 let _ = store.upsert_messages(std::slice::from_ref(&message));
1501 self.app.update(cx, |state, cx| {
1502 state.reload_sidebar(cx);
1503 state.select(Selection::Chat(chat.id.clone()), cx);
1504 });
1505 }
1506
1507 fn conversation_id(&self) -> Option<String> {
1508 self.current
1509 .as_ref()
1510 .map(|current| current.selection.conversation_id().to_owned())
1511 }
1512
1513 fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
1514 let conversation_id = self.conversation_id()?;
1515 let my_user_id = self.row_context(cx).my_user_id?;
1516 self.app
1517 .read(cx)
1518 .store
1519 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1520 .ok()?
1521 .remove(message_id)
1522 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
1523 }
1524
1525 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
1526 let target = match slot {
1527 HoverSlot::Row => &mut self.hovered_message,
1528 HoverSlot::Toolbar => &mut self.toolbar_hovered,
1529 };
1530 if hovered {
1531 *target = Some(key.to_owned());
1532 } else if target.as_deref() == Some(key) {
1533 *target = None;
1534 }
1535 cx.notify();
1536 }
1537
1538 fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) {
1539 if open {
1540 self.toolbar_pinned = Some(key.to_owned());
1541 } else if self.toolbar_pinned.as_deref() == Some(key) {
1542 self.toolbar_pinned = None;
1543 }
1544 cx.notify();
1545 }
1546
1547 fn toolbar_visible(&self, key: &str) -> bool {
1548 self.toolbar_pinned
1549 .as_deref()
1550 .or(self.toolbar_hovered.as_deref())
1551 .or(self.hovered_message.as_deref())
1552 == Some(key)
1553 }
1554
1555 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
1556 let Some(conversation_id) = self.conversation_id() else {
1557 return;
1558 };
1559 let reaction_type = reaction_type_for(glyph);
1560 let state = self.app.read(cx);
1561 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1562 let my_user_id = self.row_context(cx).my_user_id;
1563 let Some(mut record) = store
1564 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1565 .ok()
1566 .and_then(|mut found| found.remove(message_id))
1567 else {
1568 return;
1569 };
1570 let mut reactions = teams_core::reactions(&record);
1571 let mine = |reaction: &teams_core::ReactionInfo| {
1572 reaction.reaction_type == reaction_type
1573 && my_user_id.is_some()
1574 && reaction.user_id == my_user_id
1575 };
1576 let remove = reactions.iter().any(mine);
1577 if mode.demo {
1578 if remove {
1579 reactions.retain(|reaction| !mine(reaction));
1580 } else {
1581 reactions.push(teams_core::ReactionInfo {
1582 reaction_type: reaction_type.clone(),
1583 user_id: my_user_id.clone(),
1584 user_name: Some("You".to_owned()),
1585 });
1586 }
1587 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
1588 let _ = store.upsert_messages(std::slice::from_ref(&record));
1589 self.rebuild(false, cx);
1590 return;
1591 }
1592 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1593 self.show_notice("Read-only mode: reaction not sent", cx);
1594 return;
1595 };
1596 let message_id = message_id.to_owned();
1597 let receiver = runtime::spawn(async move {
1598 if remove {
1599 engine
1600 .unset_reaction(&conversation_id, &message_id, &reaction_type)
1601 .await
1602 } else {
1603 engine
1604 .set_reaction(&conversation_id, &message_id, &reaction_type)
1605 .await
1606 }
1607 });
1608 self.report_failure(receiver, "Reaction failed", cx);
1609 }
1610
1611 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
1612 let Some(record) = self.own_record(message_id, cx) else {
1613 return;
1614 };
1615 let edit = EditPreview {
1616 message_id: record.message_id.clone(),
1617 excerpt: reply_excerpt(&record),
1618 };
1619 let in_chat = matches!(
1620 self.current.as_ref().map(|current| &current.selection),
1621 Some(Selection::Chat(_))
1622 );
1623 let mentions = if in_chat {
1624 teams_core::mentions(&record)
1625 .into_iter()
1626 .filter_map(|mention| {
1627 let user_id = mention.user_id?;
1628 Some(MentionInput::user(&user_id, &mention.name))
1629 })
1630 .collect()
1631 } else {
1632 Vec::new()
1633 };
1634 let draft = Outgoing {
1635 text: message_text(&record),
1636 mentions,
1637 reply: None,
1638 edit: Some(edit),
1639 images: Vec::new(),
1640 files: Vec::new(),
1641 };
1642 self.composer
1643 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
1644 }
1645
1646 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1647 if self.draft_active {
1648 return;
1649 }
1650 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
1651 Row::Message(message)
1652 if message.own
1653 && !message.deleted
1654 && !message.key.starts_with(PENDING_KEY_PREFIX) =>
1655 {
1656 Some(message.key.clone())
1657 }
1658 _ => None,
1659 });
1660 if let Some(key) = key {
1661 self.begin_edit(&key, window, cx);
1662 }
1663 }
1664
1665 fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1666 let Some(edit) = outgoing.edit.clone() else {
1667 return;
1668 };
1669 let Some(conversation_id) = self.conversation_id() else {
1670 return;
1671 };
1672 let state = self.app.read(cx);
1673 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1674 if mode.demo {
1675 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
1676 record.body_html = teams_core::markdown_to_html(&outgoing.text);
1677 record.edited_at = Some(Utc::now());
1678 let _ = store.upsert_messages(std::slice::from_ref(&record));
1679 self.rebuild(false, cx);
1680 }
1681 return;
1682 }
1683 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1684 self.notice = Some("Read-only mode: edit not saved".to_owned());
1685 self.composer
1686 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1687 cx.notify();
1688 return;
1689 };
1690 let sent = outgoing.clone();
1691 let receiver = runtime::spawn(async move {
1692 engine
1693 .edit_message_with_mentions(
1694 &conversation_id,
1695 &edit.message_id,
1696 &sent.text,
1697 &sent.mentions,
1698 )
1699 .await
1700 });
1701 cx.spawn_in(window, async move |this, cx| {
1702 let failed = !matches!(receiver.await, Ok(Ok(())));
1703 this.update_in(cx, |this, window, cx| {
1704 if failed {
1705 if this.composer.read(cx).is_empty(cx) {
1706 this.notice =
1707 Some("Edit failed: your text is back in the composer".to_owned());
1708 this.composer
1709 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1710 } else {
1711 this.notice = Some("Edit failed".to_owned());
1712 }
1713 cx.notify();
1714 }
1715 })
1716 .ok();
1717 })
1718 .detach();
1719 }
1720
1721 fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
1722 let Some(mut record) = self.own_record(message_id, cx) else {
1723 return;
1724 };
1725 let state = self.app.read(cx);
1726 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1727 if mode.demo {
1728 record.deleted = true;
1729 let _ = store.upsert_messages(std::slice::from_ref(&record));
1730 self.rebuild(false, cx);
1731 return;
1732 }
1733 let Some(engine) = engine.filter(|_| !mode.read_only) else {
1734 self.show_notice("Read-only mode: message not deleted", cx);
1735 return;
1736 };
1737 let conversation_id = record.conversation_id.clone();
1738 let receiver = runtime::spawn(async move {
1739 engine
1740 .soft_delete_message(&conversation_id, &record.message_id)
1741 .await
1742 });
1743 self.report_failure(receiver, "Delete failed", cx);
1744 }
1745
1746 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
1747 let Some(conversation_id) = self.conversation_id() else {
1748 return;
1749 };
1750 let record = self
1751 .app
1752 .read(cx)
1753 .store
1754 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1755 .ok()
1756 .and_then(|mut found| found.remove(message_id));
1757 if let Some(record) = record {
1758 cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record)));
1759 }
1760 }
1761
1762 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
1763 self.notice = Some(message.to_owned());
1764 cx.notify();
1765 }
1766
1767 fn report_failure(
1768 &mut self,
1769 receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>,
1770 label: &'static str,
1771 cx: &mut Context<Self>,
1772 ) {
1773 cx.spawn(async move |this, cx| {
1774 let error = match receiver.await {
1775 Ok(Ok(())) => return,
1776 Ok(Err(error)) => short_error(&error),
1777 Err(_) => "cancelled".to_owned(),
1778 };
1779 this.update(cx, |this, cx| {
1780 this.show_notice(&format!("{label}: {error}"), cx)
1781 })
1782 .ok();
1783 })
1784 .detach();
1785 }
1786
1787 fn message_menu(&self, key: &str, own: bool, view: WeakEntity<Self>) -> MessageMenu {
1788 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
1789 let (view, key) = (view.clone(), key.to_owned());
1790 Rc::new(move |window, cx| {
1791 view.update(cx, |this, cx| run(this, &key, window, cx)).ok();
1792 })
1793 };
1794 let react: PickHandler = {
1795 let (view, key) = (view.clone(), key.to_owned());
1796 Rc::new(move |glyph, _, cx| {
1797 view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx))
1798 .ok();
1799 })
1800 };
1801 let hover = {
1802 let (view, key) = (view.clone(), key.to_owned());
1803 Rc::new(move |hovered: bool, cx: &mut App| {
1804 view.update(cx, |this, cx| {
1805 this.set_hover(HoverSlot::Toolbar, &key, hovered, cx)
1806 })
1807 .ok();
1808 })
1809 };
1810 let pin = {
1811 let (view, key) = (view.clone(), key.to_owned());
1812 Rc::new(move |open: bool, _: &mut Window, cx: &mut App| {
1813 view.update(cx, |this, cx| this.set_pinned(&key, open, cx))
1814 .ok();
1815 })
1816 };
1817 MessageMenu {
1818 key: key.to_owned(),
1819 react,
1820 reply: Some(action(|this, key, window, cx| {
1821 this.begin_reply(key, window, cx)
1822 })),
1823 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
1824 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
1825 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
1826 pin,
1827 hover,
1828 picker: self.picker.clone(),
1829 }
1830 }
1831
1832 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
1833 let Some(outgoing) = self.pending_outgoing.remove(key) else {
1834 return;
1835 };
1836 self.pending.retain(|row| row.key != key);
1837 if self.draft_active {
1838 self.send_new_chat(outgoing, window, cx);
1839 } else {
1840 self.send(outgoing, window, cx);
1841 }
1842 }
1843
1844 fn finish_send(
1845 &mut self,
1846 key: &str,
1847 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
1848 cx: &mut Context<Self>,
1849 ) {
1850 let failure = match result {
1851 Ok(Ok(())) => None,
1852 Ok(Err(error)) => Some(short_error(&error)),
1853 Err(error) => Some(short_error(&error)),
1854 };
1855 match failure {
1856 None => {
1857 self.pending.retain(|row| row.key != key);
1858 self.pending_outgoing.remove(key);
1859 }
1860 Some(error) => {
1861 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
1862 row.delivery = Delivery::Failed(error.clone());
1863 self.notice = Some(format!("Not sent: {error}"));
1864 }
1865 }
1866 }
1867 self.rebuild(false, cx);
1868 }
1869
1870 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
1871 let target = match self.current.as_ref().map(|current| &current.selection) {
1872 Some(Selection::Chat(_)) => DropTarget::Chat,
1873 Some(Selection::Channel(_)) => DropTarget::Channel,
1874 None => DropTarget::NewChat,
1875 };
1876 let title = self
1877 .current
1878 .as_ref()
1879 .map(|current| current.title.as_str())
1880 .unwrap_or_default();
1881 let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1));
1882 let composer = self.composer.clone();
1883 div()
1884 .id("drop-overlay")
1885 .absolute()
1886 .top_0()
1887 .left_0()
1888 .size_full()
1889 .opacity(0.)
1890 .bg(theme::drop_background())
1891 .drag_over::<ExternalPaths>(move |style, _, _, cx| {
1892 if composer.read(cx).is_editing() {
1893 style
1894 } else {
1895 style.opacity(1.)
1896 }
1897 })
1898 .on_drag_move(
1899 cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
1900 let count = event.drag(cx).paths().len();
1901 if this.drag_file_count != count {
1902 this.drag_file_count = count;
1903 cx.notify();
1904 }
1905 }),
1906 )
1907 .on_drop(cx.listener(|this, dropped: &ExternalPaths, _, cx| {
1908 let paths = dropped.paths().to_vec();
1909 this.composer
1910 .update(cx, |composer, cx| composer.add_paths(paths, cx));
1911 }))
1912 .child(
1913 div()
1914 .absolute()
1915 .inset(px(12.))
1916 .rounded(px(12.))
1917 .border_2()
1918 .border_dashed()
1919 .border_color(theme::accent())
1920 .flex()
1921 .items_center()
1922 .justify_center()
1923 .child(
1924 v_flex()
1925 .items_center()
1926 .gap(px(6.))
1927 .px(px(28.))
1928 .py(px(18.))
1929 .rounded(px(12.))
1930 .bg(black().opacity(0.55))
1931 .child(symbol("upload", 28., theme::accent_text()))
1932 .child(
1933 div()
1934 .text_size(px(15.))
1935 .font_weight(FontWeight::SEMIBOLD)
1936 .text_color(theme::text_strong())
1937 .child(heading),
1938 )
1939 .child(
1940 div()
1941 .text_size(px(12.))
1942 .text_color(theme::text_muted())
1943 .child(detail),
1944 ),
1945 ),
1946 )
1947 }
1948
1949 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
1950 let message = self.draft_error.clone()?;
1951 let failed_key = self
1952 .pending
1953 .iter()
1954 .find(|row| matches!(row.delivery, Delivery::Failed(_)))
1955 .map(|row| row.key.clone())?;
1956 Some(
1957 h_flex()
1958 .w_full()
1959 .flex_none()
1960 .px(px(24.))
1961 .py(px(4.))
1962 .gap(px(8.))
1963 .items_center()
1964 .text_size(px(12.))
1965 .text_color(theme::red_soft())
1966 .child(message)
1967 .child(
1968 Button::new("retry-new-chat")
1969 .ghost()
1970 .compact()
1971 .label("Retry")
1972 .on_click(cx.listener(move |this, _, window, cx| {
1973 this.retry(&failed_key, window, cx)
1974 })),
1975 ),
1976 )
1977 }
1978
1979 fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement {
1980 let app = self.app.read(cx);
1981 let directory = &app.directory;
1982 let me = directory.me.as_ref();
1983 let mut lead: Option<AnyElement> = None;
1984 let mut subline = String::new();
1985 let mut stack: Option<Div> = None;
1986 match &current.selection {
1987 Selection::Chat(chat_id) => {
1988 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
1989 let faces = others(chat, me);
1990 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
1991 let first = faces.first().cloned().map(face);
1992 if is_one_on_one(chat) || faces.len() < 2 {
1993 let name = first
1994 .as_ref()
1995 .map_or(current.title.as_str(), |face| face.name.as_str());
1996 let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
1997 let avatar = person_avatar(directory, user_id, name, 36.);
1998 let presence = user_id.map(|id| directory.presence_of(id));
1999 lead = Some(match presence {
2000 Some(kind) => with_presence(avatar, kind, 36., theme::background())
2001 .into_any_element(),
2002 None => avatar,
2003 });
2004 subline = presence
2005 .map(|presence| presence.kind().label().to_owned())
2006 .unwrap_or_default();
2007 } else {
2008 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
2009 lead = Some(spec_avatar(directory, &pair, 36., theme::background()));
2010 subline = format!("{} participants", chat.members.len());
2011 let shown: Vec<Face> = faces.iter().cloned().map(face).collect();
2012 stack = Some(member_stack(directory, &shown, shown.len()));
2013 }
2014 }
2015 }
2016 Selection::Channel(channel_id) => {
2017 let team = app.sidebar.teams.iter().find(|entry| {
2018 entry
2019 .channels
2020 .iter()
2021 .any(|channel| &channel.id == channel_id)
2022 });
2023 let (name, key) = team
2024 .map_or((current.title.as_str(), current.title.as_str()), |entry| {
2025 (entry.team.name.as_str(), entry.team.id.as_str())
2026 });
2027 lead = Some(square_avatar(name, key, 36., 9.).into_any_element());
2028 }
2029 }
2030 let mut header = h_flex()
2031 .w_full()
2032 .h(px(60.))
2033 .flex_none()
2034 .px(px(20.))
2035 .gap(px(12.))
2036 .items_center()
2037 .border_b_1()
2038 .border_color(theme::border());
2039 if matches!(current.mode, ViewMode::Thread(_)) {
2040 header = header.child(
2041 Button::new("back-to-threads")
2042 .ghost()
2043 .compact()
2044 .label("Threads")
2045 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx))),
2046 );
2047 }
2048 let channel_note = match current.mode {
2049 ViewMode::Flat => None,
2050 ViewMode::ThreadList => Some("Threads"),
2051 ViewMode::Thread(_) => Some("Thread"),
2052 };
2053 if let Some(note) = channel_note {
2054 subline = note.to_owned();
2055 }
2056 let sync = &current.sync;
2057 if sync.failed {
2058 subline = "Not up to date".to_owned();
2059 } else if sync.shown_at.is_some() {
2060 subline = if sync.slow {
2061 "Taking longer than usual ..."
2062 } else if sync.empty_cache {
2063 "Loading messages ..."
2064 } else {
2065 "Updating ..."
2066 }
2067 .to_owned();
2068 }
2069 header
2070 .relative()
2071 .when(sync.shown_at.is_some(), |header| {
2072 header.child(progress_bar())
2073 })
2074 .children(lead)
2075 .child(
2076 v_flex()
2077 .flex_1()
2078 .min_w_0()
2079 .overflow_hidden()
2080 .gap(px(1.))
2081 .child(
2082 div()
2083 .truncate()
2084 .text_size(px(15.))
2085 .font_weight(FontWeight::SEMIBOLD)
2086 .text_color(theme::text())
2087 .child(current.title.clone()),
2088 )
2089 .when(!subline.is_empty(), |column| {
2090 column.child(
2091 div()
2092 .text_size(px(12.))
2093 .text_color(theme::text_muted())
2094 .child(subline),
2095 )
2096 }),
2097 )
2098 .children(stack)
2099 }
2100}
2101
2102impl Render for ConversationView {
2103 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2104 let background = theme::background();
2105 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2106 let drafting = self.draft_active;
2107 if self.current.is_none() && !drafting {
2108 return root
2109 .items_center()
2110 .justify_center()
2111 .text_color(theme::text_muted())
2112 .child("Select a chat or channel")
2113 .into_any_element();
2114 }
2115 let rows = self.rows.clone();
2116 let view = cx.weak_entity();
2117 let app = self.app.clone();
2118 let highlighted = self.highlighted_message.clone();
2119 let scroller = MessageScroller::new(
2120 "messages",
2121 self.scroller.clone(),
2122 move |index, window, cx| {
2123 let rows = rows.borrow();
2124 match rows.get(index) {
2125 Some(Row::Message(message)) => {
2126 let open_thread = message.open_thread.clone().map(|root_id| {
2127 let view = view.clone();
2128 Box::new(move |cx: &mut App| {
2129 let root_id = root_id.clone();
2130 view.update(cx, |this, cx| this.open_thread(root_id, cx))
2131 .ok();
2132 }) as Box<dyn Fn(&mut App)>
2133 });
2134 let retry = matches!(message.delivery, Delivery::Failed(_)).then(|| {
2135 let (view, key, handle) =
2136 (view.clone(), message.key.clone(), window.window_handle());
2137 Box::new(move |cx: &mut App| {
2138 let (view, key) = (view.clone(), key.clone());
2139 handle
2140 .update(cx, move |_, window, cx| {
2141 view.update(cx, |this, cx| this.retry(&key, window, cx))
2142 .ok();
2143 })
2144 .ok();
2145 }) as Box<dyn Fn(&mut App)>
2146 });
2147 let sender = (!message.own && !message.series.has_prev)
2148 .then(|| message.sender_id.clone())
2149 .flatten()
2150 .filter(|sender| app.read(cx).directory.avatar(sender).is_none());
2151 if let Some(sender) = sender {
2152 let app = app.clone();
2153 cx.defer(move |cx| {
2154 app.update(cx, |state, cx| state.request_avatars(vec![sender], cx));
2155 });
2156 }
2157 let missing_images: Vec<ImageRef> = message
2158 .images
2159 .iter()
2160 .filter(|image| app.read(cx).directory.image(&image.url).is_none())
2161 .cloned()
2162 .collect();
2163 if !missing_images.is_empty() {
2164 let app = app.clone();
2165 cx.defer(move |cx| {
2166 app.update(cx, |state, cx| {
2167 state.request_images(missing_images, cx)
2168 });
2169 });
2170 }
2171 let is_real = !drafting && !message.key.starts_with(PENDING_KEY_PREFIX);
2172 let hovered = is_real.then(|| {
2173 let (view, key) = (view.clone(), message.key.clone());
2174 Rc::new(move |hovered: bool, cx: &mut App| {
2175 view.update(cx, |this, cx| {
2176 this.set_hover(HoverSlot::Row, &key, hovered, cx)
2177 })
2178 .ok();
2179 }) as Rc<dyn Fn(bool, &mut App)>
2180 });
2181 let actionable = is_real && !message.deleted && !message.card;
2182 let (menu, react) = view
2183 .upgrade()
2184 .filter(|_| actionable)
2185 .map(|entity| {
2186 let this = entity.read(cx);
2187 let menu =
2188 this.message_menu(&message.key, message.own, view.clone());
2189 let react = menu.react.clone();
2190 let visible = this.toolbar_visible(&message.key);
2191 (visible.then_some(menu), Some(react))
2192 })
2193 .unwrap_or((None, None));
2194 let reply = (is_real && !message.deleted).then(|| {
2195 let (view, key, handle) =
2196 (view.clone(), message.key.clone(), window.window_handle());
2197 Box::new(move |cx: &mut App| {
2198 let (view, key) = (view.clone(), key.clone());
2199 handle
2200 .update(cx, move |_, window, cx| {
2201 view.update(cx, |this, cx| {
2202 this.begin_reply(&key, window, cx)
2203 })
2204 .ok();
2205 })
2206 .ok();
2207 }) as Box<dyn Fn(&mut App)>
2208 });
2209 let state = app.read(cx);
2210 render_message_row(
2211 message,
2212 index,
2213 RowActions {
2214 open_thread,
2215 retry,
2216 reply,
2217 hovered,
2218 menu,
2219 react,
2220 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
2221 },
2222 &state.directory,
2223 cx,
2224 )
2225 }
2226 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
2227 Some(Row::LoadOlder) => {
2228 let view = view.clone();
2229 cx.defer(move |cx| {
2230 view.update(cx, |this, cx| this.request_older(cx)).ok();
2231 });
2232 h_flex()
2233 .w_full()
2234 .py_2()
2235 .gap(px(6.))
2236 .justify_center()
2237 .text_size(px(12.))
2238 .text_color(theme::text_muted())
2239 .child(icon(IconName::Loader, 12., theme::text_muted()))
2240 .child("Loading older messages")
2241 .into_any_element()
2242 }
2243 Some(Row::Start(start)) => {
2244 let state = app.read(cx);
2245 v_flex()
2246 .w_full()
2247 .items_center()
2248 .gap(px(8.))
2249 .pt(px(32.))
2250 .pb(px(16.))
2251 .child(person_avatar(
2252 &state.directory,
2253 start.user_id.as_deref(),
2254 &start.title,
2255 56.,
2256 ))
2257 .child(
2258 div()
2259 .text_size(px(16.))
2260 .font_weight(FontWeight::SEMIBOLD)
2261 .text_color(theme::text())
2262 .child(start.title.clone()),
2263 )
2264 .child(
2265 div()
2266 .text_size(px(12.))
2267 .text_color(theme::text_muted())
2268 .child("This is the beginning of the conversation"),
2269 )
2270 .into_any_element()
2271 }
2272 None => div().into_any_element(),
2273 }
2274 },
2275 )
2276 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
2277 .with_bottom_fade(background);
2278
2279 root = match self.current.as_ref().filter(|_| !drafting) {
2280 Some(current) => root.child(self.render_header(current, cx)),
2281 None => root.child(self.draft.clone()),
2282 };
2283 let sync_failed = self
2284 .current
2285 .as_ref()
2286 .is_some_and(|current| current.sync.failed);
2287 if let Some(notice) = &self.notice {
2288 root = root.child(
2289 h_flex()
2290 .px_4()
2291 .py_1()
2292 .gap(px(8.))
2293 .items_center()
2294 .text_xs()
2295 .bg(theme::amber().opacity(0.15))
2296 .text_color(theme::amber())
2297 .child(div().flex_1().min_w_0().child(notice.clone()))
2298 .when(sync_failed, |bar| {
2299 bar.child(
2300 Button::new("retry-fetch")
2301 .ghost()
2302 .compact()
2303 .label("Retry")
2304 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
2305 )
2306 }),
2307 );
2308 }
2309 let empty_channel = self
2310 .current
2311 .as_ref()
2312 .is_some_and(|current| current.mode == ViewMode::ThreadList)
2313 && self.rows.borrow().is_empty();
2314 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
2315 let draft = self.draft.read(cx);
2316 let group_name = draft.group_name(cx);
2317 draft.render_empty(&self.app.read(cx).directory, &group_name)
2318 } else if empty_channel {
2319 div()
2320 .size_full()
2321 .flex()
2322 .items_center()
2323 .justify_center()
2324 .text_size(px(13.))
2325 .text_color(theme::text_muted())
2326 .child("No posts in this channel yet")
2327 .into_any_element()
2328 } else {
2329 scroller.into_any_element()
2330 };
2331 root.child(
2332 v_flex()
2333 .relative()
2334 .flex_1()
2335 .min_h_0()
2336 .child(div().flex_1().min_h_0().child(body))
2337 .children(self.render_draft_error(cx))
2338 .child(self.composer.clone())
2339 .child(self.render_drop_overlay(cx)),
2340 )
2341 .when(drafting, |root| {
2342 root.on_action(cx.listener(|this, _: &Escape, window, cx| {
2343 if this.draft.read(cx).has_focus(window, cx) {
2344 this.draft.update(cx, |draft, cx| draft.escape(cx));
2345 }
2346 }))
2347 })
2348 .into_any_element()
2349 }
2350}
2351
2352fn progress_bar() -> impl IntoElement {
2353 div()
2354 .absolute()
2355 .left_0()
2356 .right_0()
2357 .bottom(px(-1.))
2358 .h(px(2.))
2359 .overflow_hidden()
2360 .bg(theme::border())
2361 .child(
2362 div()
2363 .absolute()
2364 .top_0()
2365 .h_full()
2366 .w(relative(PROGRESS_BAR_WIDTH))
2367 .bg(theme::own_read())
2368 .with_animation(
2369 "sync-progress",
2370 Animation::new(PROGRESS_BAR_PERIOD).repeat(),
2371 |bar, delta| {
2372 let travel = 1. + PROGRESS_BAR_WIDTH;
2373 // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).
2374 bar.left(relative(
2375 (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,
2376 ))
2377 },
2378 ),
2379 )
2380}
2381
2382#[cfg(test)]
2383mod tests {
2384 use std::sync::Arc;
2385
2386 use super::{DropTarget, drop_overlay_text};
2387
2388 use gpui_kit::test::TestWindowExt as _;
2389 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
2390 use store::Store;
2391
2392 use super::ConversationView;
2393 use crate::app_state::{AppState, Mode, Selection};
2394
2395 #[test]
2396 fn chat_overlay_names_the_chat_and_the_onedrive() {
2397 assert_eq!(
2398 drop_overlay_text("Mara Lin", DropTarget::Chat, 3),
2399 (
2400 "Drop to attach to Mara Lin".to_owned(),
2401 "3 files. Images go into the message, other files to your OneDrive.".to_owned()
2402 )
2403 );
2404 }
2405
2406 #[test]
2407 fn channel_overlay_points_to_the_channel_files() {
2408 let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1);
2409 assert_eq!(
2410 detail,
2411 "1 file. Images go into the message, other files to the channel's Files."
2412 );
2413 }
2414
2415 #[test]
2416 fn new_chat_overlay_says_files_wait_for_the_chat() {
2417 let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2);
2418 assert_eq!(heading, "Drop to attach to the new chat");
2419 assert_eq!(
2420 detail,
2421 "2 files. Images go into the message. Files can be added once the chat exists."
2422 );
2423 }
2424
2425 #[gpui_kit::test]
2426 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
2427 cx.update(gpui_kit::init);
2428 let store = Arc::new(Store::open_in_memory().unwrap());
2429 crate::demo::seed(&store);
2430 let mode = Mode {
2431 demo: true,
2432 read_only: false,
2433 demo_sync: None,
2434 };
2435 let (handle, app, _view) = cx.update(|cx| {
2436 let app = cx.new(|_| {
2437 let mut state = AppState::new(store, mode);
2438 crate::demo::seed_directory(&mut state);
2439 state.selection = Some(crate::demo::first_selection());
2440 state
2441 });
2442 let shared = app.clone();
2443 let (handle, view) =
2444 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2445 cx.new(|cx| ConversationView::new(shared, window, cx))
2446 })
2447 .unwrap();
2448 (handle, app, view)
2449 });
2450 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
2451 let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| {
2452 cx.update_window(handle, move |_, window, cx| {
2453 run(window, cx);
2454 window.render_frame(cx);
2455 })
2456 .unwrap();
2457 };
2458 step(cx, |window, cx| window.render_frame(cx));
2459 step(cx, |window, cx| window.input("lea", cx));
2460 step(cx, |window, cx| window.press("enter", cx));
2461 step(cx, |window, cx| window.press("enter", cx));
2462 step(cx, |window, cx| window.input("Hello Lea", cx));
2463 step(cx, |window, cx| window.press("enter", cx));
2464 cx.update(|cx| {
2465 let state = app.read(cx);
2466 assert!(!state.new_chat);
2467 assert_eq!(
2468 state.selection,
2469 Some(Selection::Chat("demo-chat-new-1".to_owned()))
2470 );
2471 let chat = state
2472 .sidebar
2473 .chats
2474 .iter()
2475 .find(|chat| chat.id == "demo-chat-new-1")
2476 .expect("new chat in the sidebar");
2477 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea"));
2478 });
2479 }
2480
2481 #[gpui_kit::test]
2482 fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) {
2483 cx.update(gpui_kit::init);
2484 let store = Arc::new(Store::open_in_memory().unwrap());
2485 crate::demo::seed(&store);
2486 let mode = Mode {
2487 demo: true,
2488 read_only: false,
2489 demo_sync: None,
2490 };
2491 let (handle, app) = cx.update(|cx| {
2492 let app = cx.new(|_| {
2493 let mut state = AppState::new(store, mode);
2494 crate::demo::seed_directory(&mut state);
2495 state.selection = Some(crate::demo::first_selection());
2496 state
2497 });
2498 let shared = app.clone();
2499 let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2500 cx.new(|cx| ConversationView::new(shared, window, cx))
2501 })
2502 .unwrap();
2503 (handle, app)
2504 });
2505 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
2506 cx.update_window(handle, |_, window, cx| {
2507 window.render_frame(cx);
2508 window.press("escape", cx);
2509 window.render_frame(cx);
2510 window.press("escape", cx);
2511 window.render_frame(cx);
2512 })
2513 .unwrap();
2514 cx.update(|cx| {
2515 let state = app.read(cx);
2516 assert!(!state.new_chat);
2517 assert_eq!(state.selection, Some(crate::demo::first_selection()));
2518 });
2519 }
2520}