BlueGit

ict rusty-teams

Files

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

conversation.rs

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