BlueGit

ict rusty-teams

Files

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

conversation.rs

396af7fa History
conversation.rs 53.6 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 message_scroller::{MessageScroller, MessageScrollerState},
12 v_flex,
13};
14use gpui_kit::prelude::FluentBuilder as _;
15use gpui_kit::*;
16use store::MessageRecord;
17use teams_core::ImageRef;
18
19use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
20use super::composer::{Composer, ComposerEvent, Outgoing, ReplyPreview};
21use super::message_row::{RowActions, render_message_row, render_skeleton_row};
22use super::widgets::icon;
23use crate::app_state::{AppEvent, AppState, Selection, selection_title};
24use crate::data::{is_one_on_one, others};
25use crate::render::Block;
26use crate::render::blocks::Inline;
27use crate::rows::{
28 Delivery, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,
29 changed_indices, diff_keys, flat_rows, placeholder_rows, reply_excerpt, thread_list_rows,
30 thread_rows, trailing_skeleton,
31};
32use crate::runtime;
33use crate::sidebar_model::{AvatarSpec, Face};
34use crate::theme;
35
36const CHAT_OPEN_LIMIT: usize = 60;
37const CHANNEL_OPEN_LIMIT: usize = 300;
38const GROWTH_HEADROOM: usize = 20;
39const META_USER_ID: &str = "me_user_id";
40const PENDING_KEY_PREFIX: &str = "pending-";
41const MAX_NOTICE_CHARS: usize = 140;
42const JUMP_SCAN_LIMIT: usize = 5000;
43const JUMP_CONTEXT_MESSAGES: usize = 12;
44const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
45const PROGRESS_DELAY: Duration = Duration::from_millis(400);
46const SKELETON_DELAY: Duration = Duration::from_millis(1000);
47const SLOW_AFTER: Duration = Duration::from_secs(8);
48const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
49const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
50const PROGRESS_BAR_WIDTH: f32 = 0.35;
51
52actions!(teams, [ReplyToHovered]);
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55enum ViewMode {
56 Flat,
57 ThreadList,
58 Thread(String),
59}
60
61#[derive(Default)]
62struct SyncProgress {
63 messages: bool,
64 receipts: bool,
65 empty_cache: bool,
66 newest_cached: Option<DateTime<Utc>>,
67 shown_at: Option<Instant>,
68 trailing_skeleton: bool,
69 slow: bool,
70 failed: bool,
71}
72
73impl SyncProgress {
74 fn running(&self) -> bool {
75 self.messages || self.receipts
76 }
77}
78
79struct Current {
80 selection: Selection,
81 title: String,
82 mode: ViewMode,
83 loaded_limit: usize,
84 loaded_count: usize,
85 has_older: bool,
86 loading_older: bool,
87 older_blocked: bool,
88 fetched: bool,
89 first_unread: Option<String>,
90 sync: SyncProgress,
91}
92
93pub struct ConversationView {
94 app: Entity<AppState>,
95 scroller: Entity<MessageScrollerState>,
96 composer: Entity<Composer>,
97 rows: Rc<RefCell<Vec<Row>>>,
98 current: Option<Current>,
99 pending: Vec<MessageRow>,
100 pending_counter: usize,
101 pending_outgoing: HashMap<String, Outgoing>,
102 hovered_message: Option<String>,
103 highlighted_message: Option<String>,
104 notice: Option<String>,
105 sync_generation: u64,
106 _subscriptions: Vec<Subscription>,
107}
108
109fn open_limit(selection: &Selection) -> usize {
110 match selection {
111 Selection::Chat(_) => CHAT_OPEN_LIMIT,
112 Selection::Channel(_) => CHANNEL_OPEN_LIMIT,
113 }
114}
115
116fn short_error(error: &dyn std::fmt::Display) -> String {
117 error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
118}
119
120impl ConversationView {
121 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
122 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
123 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
124 let subscriptions = vec![
125 cx.subscribe_in(&app, window, Self::on_app_event),
126 cx.subscribe_in(&composer, window, Self::on_composer_event),
127 ];
128 let mut view = ConversationView {
129 app,
130 scroller,
131 composer,
132 rows: Rc::new(RefCell::new(Vec::new())),
133 current: None,
134 pending: Vec::new(),
135 pending_counter: 0,
136 pending_outgoing: HashMap::new(),
137 hovered_message: None,
138 highlighted_message: None,
139 notice: None,
140 sync_generation: 0,
141 _subscriptions: subscriptions,
142 };
143 if let Some(selection) = view.app.read(cx).selection.clone() {
144 view.open(selection, window, cx);
145 }
146 view
147 }
148
149 #[cfg_attr(not(windows), allow(dead_code))]
150 pub fn composer_is_empty(&self, cx: &App) -> bool {
151 self.composer.read(cx).is_empty(cx)
152 }
153
154 #[cfg_attr(not(windows), allow(dead_code))]
155 pub fn send_in_flight(&self) -> bool {
156 self.pending
157 .iter()
158 .any(|row| matches!(row.delivery, Delivery::Sending))
159 }
160
161 fn on_app_event(
162 &mut self,
163 _: &Entity<AppState>,
164 event: &AppEvent,
165 window: &mut Window,
166 cx: &mut Context<Self>,
167 ) {
168 match event {
169 AppEvent::Selection => {
170 if let Some(selection) = self.app.read(cx).selection.clone() {
171 self.open(selection, window, cx);
172 }
173 }
174 AppEvent::Messages(conversation_id) => {
175 let is_current = self
176 .current
177 .as_ref()
178 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
179 if is_current {
180 self.rebuild(false, cx);
181 self.mark_read(cx);
182 }
183 }
184 AppEvent::Images(keys) => self.remeasure_images(keys, cx),
185 AppEvent::Jump => self.apply_pending_jump(cx),
186 AppEvent::Status => {
187 if let Some(current) = self.current.as_mut()
188 && current.sync.failed
189 {
190 current.fetched = false;
191 }
192 self.start_fetch(cx)
193 }
194 AppEvent::Directory => cx.notify(),
195 AppEvent::Sidebar => {
196 if let Some(current) = self.current.as_mut() {
197 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
198 if current.title != title {
199 current.title = title.clone();
200 let conversation_id = current.selection.conversation_id().to_owned();
201 self.composer.update(cx, |composer, cx| {
202 composer.set_conversation(&conversation_id, &title, window, cx)
203 });
204 cx.notify();
205 }
206 }
207 }
208 }
209 }
210
211 fn on_composer_event(
212 &mut self,
213 _: &Entity<Composer>,
214 event: &ComposerEvent,
215 window: &mut Window,
216 cx: &mut Context<Self>,
217 ) {
218 let ComposerEvent::Submit(outgoing) = event;
219 self.send(outgoing.clone(), window, cx);
220 }
221
222 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
223 let title = selection_title(&self.app.read(cx).sidebar, &selection);
224 let mode = match selection {
225 Selection::Chat(_) => ViewMode::Flat,
226 Selection::Channel(_) => ViewMode::ThreadList,
227 };
228 let first_unread = self.first_unread_id(&selection, cx);
229 self.current = Some(Current {
230 loaded_limit: open_limit(&selection),
231 selection,
232 title,
233 mode,
234 loaded_count: 0,
235 has_older: false,
236 loading_older: false,
237 older_blocked: false,
238 fetched: false,
239 first_unread,
240 sync: SyncProgress::default(),
241 });
242 self.sync_generation += 1;
243 self.pending.clear();
244 self.notice = None;
245 self.rebuild(true, cx);
246 self.start_fetch(cx);
247 self.mark_read(cx);
248 let target = self
249 .current
250 .as_ref()
251 .map(|current| {
252 (
253 current.selection.conversation_id().to_owned(),
254 current.title.clone(),
255 )
256 })
257 .unwrap_or_default();
258 self.composer.update(cx, |composer, cx| {
259 composer.set_conversation(&target.0, &target.1, window, cx);
260 composer.focus(window, cx);
261 });
262 self.hovered_message = None;
263 self.apply_pending_jump(cx);
264 }
265
266 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
267 let indices: Vec<usize> = self
268 .rows
269 .borrow()
270 .iter()
271 .enumerate()
272 .filter_map(|(index, row)| match row {
273 Row::Message(message)
274 if message.images.iter().any(|image| keys.contains(&image.url)) =>
275 {
276 Some(index)
277 }
278 _ => None,
279 })
280 .collect();
281 self.scroller.update(cx, |scroller, cx| {
282 for index in indices {
283 scroller.remeasure_items(index..index + 1, cx);
284 }
285 });
286 cx.notify();
287 }
288
289 fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {
290 let Some(conversation_id) = self
291 .current
292 .as_ref()
293 .map(|current| current.selection.conversation_id().to_owned())
294 else {
295 return;
296 };
297 let jump = self
298 .app
299 .update(cx, |state, _| match state.pending_jump.take() {
300 Some((target, message_id)) if target == conversation_id => Some(message_id),
301 other => {
302 state.pending_jump = other;
303 None
304 }
305 });
306 if let Some(message_id) = jump {
307 self.jump_to_message(&conversation_id, &message_id, cx);
308 }
309 }
310
311 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
312 let store = self.app.read(cx).store.clone();
313 let Some(record) = store
314 .messages_by_id(conversation_id, &[message_id.to_owned()])
315 .ok()
316 .and_then(|mut found| found.remove(message_id))
317 else {
318 return;
319 };
320 let messages_from_target = store
321 .messages(conversation_id, None, JUMP_SCAN_LIMIT)
322 .ok()
323 .and_then(|all| {
324 all.iter()
325 .position(|candidate| candidate.message_id == message_id)
326 .map(|position| all.len() - position)
327 })
328 .unwrap_or_default();
329 let row_key = record
330 .reply_to_id
331 .clone()
332 .unwrap_or_else(|| message_id.to_owned());
333 let Some(current) = self.current.as_mut() else {
334 return;
335 };
336 current.loaded_limit = current
337 .loaded_limit
338 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
339 current.first_unread = None;
340 if matches!(current.selection, Selection::Channel(_)) {
341 current.mode = match record.reply_to_id {
342 Some(root_id) => ViewMode::Thread(root_id),
343 None => ViewMode::ThreadList,
344 };
345 }
346 let target_key = if matches!(current.mode, ViewMode::Thread(_)) {
347 message_id.to_owned()
348 } else {
349 row_key
350 };
351 self.pending.clear();
352 self.rebuild(true, cx);
353 let index = self
354 .rows
355 .borrow()
356 .iter()
357 .position(|row| row.key() == target_key);
358 if let Some(index) = index {
359 self.scroller
360 .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx));
361 self.highlight(target_key, cx);
362 }
363 }
364
365 fn highlight(&mut self, key: String, cx: &mut Context<Self>) {
366 self.highlighted_message = Some(key.clone());
367 cx.notify();
368 cx.spawn(async move |this, cx| {
369 cx.background_executor().timer(HIGHLIGHT_DURATION).await;
370 this.update(cx, |this, cx| {
371 if this.highlighted_message.as_deref() == Some(key.as_str()) {
372 this.highlighted_message = None;
373 cx.notify();
374 }
375 })
376 .ok();
377 })
378 .detach();
379 }
380
381 pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
382 self.composer
383 .update(cx, |composer, cx| composer.set_text(text, window, cx));
384 self.composer
385 .update(cx, |composer, cx| composer.focus(window, cx));
386 }
387
388 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
389 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
390 Row::Message(message) if !message.own => Some(message.key.clone()),
391 _ => None,
392 });
393 if let Some(key) = key {
394 self.begin_reply(&key, window, cx);
395 }
396 }
397
398 pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) {
399 if let Some(message_id) = self.hovered_message.clone() {
400 self.begin_reply(&message_id, window, cx);
401 }
402 }
403
404 fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
405 let Some(conversation_id) = self
406 .current
407 .as_ref()
408 .map(|current| current.selection.conversation_id().to_owned())
409 else {
410 return;
411 };
412 let store = self.app.read(cx).store.clone();
413 let record = store
414 .messages_by_id(&conversation_id, &[message_id.to_owned()])
415 .ok()
416 .and_then(|mut found| found.remove(message_id))
417 .filter(|record| !record.deleted);
418 let Some(record) = record else {
419 return;
420 };
421 let preview = ReplyPreview {
422 message_id: record.message_id.clone(),
423 author: record
424 .sender_name
425 .clone()
426 .unwrap_or_else(|| "Unknown".to_owned()),
427 excerpt: reply_excerpt(&record),
428 };
429 self.composer.update(cx, |composer, cx| {
430 composer.set_reply(Some(preview), cx);
431 composer.focus(window, cx);
432 });
433 }
434
435 fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> {
436 let Selection::Chat(chat_id) = selection else {
437 return None;
438 };
439 let state = self.app.read(cx);
440 if state.mode.demo {
441 return crate::demo::first_unread(chat_id);
442 }
443 state.engine.as_ref()?.first_unread_message_id(chat_id)
444 }
445
446 fn row_context(&self, cx: &App) -> RowContext {
447 let now = Local::now();
448 RowContext {
449 offset: now.offset().fix(),
450 today: now.date_naive(),
451 my_user_id: self.app.read(cx).store.meta(META_USER_ID).ok().flatten(),
452 }
453 }
454
455 fn start_info(&self, cx: &App) -> Option<StartInfo> {
456 let current = self.current.as_ref()?;
457 let app = self.app.read(cx);
458 let user_id = match &current.selection {
459 Selection::Chat(chat_id) => app
460 .sidebar
461 .chats
462 .iter()
463 .find(|chat| &chat.id == chat_id)
464 .filter(|chat| is_one_on_one(chat))
465 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next())
466 .and_then(|(user_id, _)| user_id),
467 Selection::Channel(_) => None,
468 };
469 Some(StartInfo {
470 title: current.title.clone(),
471 user_id,
472 })
473 }
474
475 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
476 let Some(current) = self.current.as_ref() else {
477 self.apply_rows(Vec::new(), true, cx);
478 return;
479 };
480 let conversation_id = current.selection.conversation_id().to_owned();
481 let limit = if reset {
482 current.loaded_limit
483 } else {
484 current
485 .loaded_limit
486 .max(current.loaded_count + GROWTH_HEADROOM)
487 };
488 let store = self.app.read(cx).store.clone();
489 let records: Vec<MessageRecord> = store
490 .messages(&conversation_id, None, limit)
491 .unwrap_or_default();
492 let sync_has_more = store
493 .sync_state(&conversation_id)
494 .ok()
495 .flatten()
496 .is_none_or(|state| state.has_more);
497 let context = self.row_context(cx);
498 let can_load_older = self.app.read(cx).engine.is_some();
499 let start = self.start_info(cx);
500 let current = self.current.as_mut().expect("checked above");
501 let first_unread = current.first_unread.clone();
502 current.loaded_limit = limit;
503 current.loaded_count = records.len();
504 let has_older = sync_has_more && !current.older_blocked && can_load_older;
505 let placeholders = current.sync.messages
506 && records.is_empty()
507 && !matches!(current.mode, ViewMode::Thread(_));
508 let trailing = current.sync.trailing_skeleton && current.mode == ViewMode::Flat;
509 let mut rows = match &current.mode {
510 _ if placeholders => {
511 current.has_older = false;
512 placeholder_rows()
513 }
514 ViewMode::Flat => {
515 current.has_older = has_older;
516 let mut rows = flat_rows(&records, &context, has_older);
517 if !has_older && let Some(start) = start {
518 rows.insert(0, Row::Start(start));
519 }
520 rows
521 }
522 ViewMode::ThreadList => {
523 current.has_older = has_older;
524 thread_list_rows(&records, &context, has_older)
525 }
526 ViewMode::Thread(root_id) => {
527 current.has_older = false;
528 thread_rows(&records, root_id, &context)
529 }
530 };
531 if trailing && !placeholders {
532 rows.push(trailing_skeleton());
533 }
534 rows.extend(
535 self.pending
536 .iter()
537 .cloned()
538 .map(|row| Row::Message(Box::new(row))),
539 );
540 let receipts = self.receipts(&records, cx);
541 for row in rows.iter_mut() {
542 if let Row::Message(message) = row
543 && message.own
544 {
545 message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
546 }
547 }
548 if let Some(unread_id) = &first_unread {
549 for row in rows.iter_mut() {
550 if let Row::Message(message) = row
551 && &message.key == unread_id
552 {
553 message.new_marker = true;
554 }
555 }
556 }
557 assign_series(&mut rows);
558 self.apply_rows(rows, reset, cx);
559 }
560
561 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
562 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
563 let new_len = self.rows.borrow().len();
564 if reset {
565 let marker_index = self
566 .rows
567 .borrow()
568 .iter()
569 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
570 self.scroller.update(cx, |scroller, cx| {
571 scroller.reset(new_len, cx);
572 match marker_index {
573 Some(index) if !scroller.scroll_to_item(index, cx) => {
574 scroller.scroll_to_end(cx)
575 }
576 Some(_) => {}
577 None => scroller.scroll_to_end(cx),
578 }
579 });
580 cx.notify();
581 return;
582 }
583 let (splice, changed) = {
584 let new_rows = self.rows.borrow();
585 let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect();
586 let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect();
587 (
588 diff_keys(&old_keys, &new_keys),
589 changed_indices(&old_rows, &new_rows),
590 )
591 };
592 self.scroller.update(cx, |scroller, cx| {
593 if let Some(splice) = splice
594 && !scroller.splice(splice.range, splice.count, cx)
595 {
596 scroller.reset(new_len, cx);
597 }
598 for index in changed {
599 scroller.remeasure_items(index..index + 1, cx);
600 }
601 });
602 cx.notify();
603 }
604
605 fn start_fetch(&mut self, cx: &mut Context<Self>) {
606 let state = self.app.read(cx);
607 let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync);
608 if engine.is_none() && demo_sync.is_none() {
609 return;
610 }
611 let Some(current) = self.current.as_mut() else {
612 return;
613 };
614 if current.fetched {
615 return;
616 }
617 current.fetched = true;
618 let is_chat = matches!(current.selection, Selection::Chat(_));
619 let newest_cached = self.rows.borrow().iter().rev().find_map(|row| match row {
620 Row::Message(message) if !message.key.starts_with(PENDING_KEY_PREFIX) => {
621 Some(message.created_at)
622 }
623 _ => None,
624 });
625 let current = self.current.as_mut().expect("checked above");
626 if current.sync.failed {
627 self.notice = None;
628 }
629 current.sync = SyncProgress {
630 messages: true,
631 receipts: is_chat,
632 empty_cache: newest_cached.is_none(),
633 newest_cached,
634 ..SyncProgress::default()
635 };
636 self.sync_generation += 1;
637 let generation = self.sync_generation;
638 let conversation_id = current.selection.conversation_id().to_owned();
639 match (engine, demo_sync) {
640 (Some(engine), _) => {
641 let receiver =
642 runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
643 cx.spawn(async move |this, cx| {
644 let result = receiver.await;
645 this.update(cx, |this, cx| this.finish_fetch(generation, result, cx))
646 .ok();
647 })
648 .detach();
649 }
650 (None, Some(delay)) => self.simulate_sync(generation, delay, cx),
651 (None, None) => {}
652 }
653 self.schedule_progress(generation, cx);
654 self.rebuild(false, cx);
655 self.mark_read(cx);
656 self.refresh_receipts(generation, cx);
657 }
658
659 fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) {
660 cx.spawn(async move |this, cx| {
661 cx.background_executor().timer(delay).await;
662 this.update(cx, |this, cx| {
663 if let Some(sync) = this.sync_of(generation) {
664 sync.receipts = false;
665 }
666 this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx)
667 })
668 .ok();
669 })
670 .detach();
671 }
672
673 fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> {
674 if generation != self.sync_generation {
675 return None;
676 }
677 self.current.as_mut().map(|current| &mut current.sync)
678 }
679
680 fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
681 cx.spawn(async move |this, cx| {
682 let stages = [
683 (PROGRESS_DELAY, Duration::ZERO),
684 (SKELETON_DELAY, PROGRESS_DELAY),
685 (SLOW_AFTER, SKELETON_DELAY),
686 ];
687 for (stage, (at, previous)) in stages.into_iter().enumerate() {
688 cx.background_executor().timer(at - previous).await;
689 let running = this
690 .update(cx, |this, cx| this.advance_progress(generation, stage, cx))
691 .unwrap_or(false);
692 if !running {
693 return;
694 }
695 }
696 })
697 .detach();
698 }
699
700 fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool {
701 let Some(sync) = self.sync_of(generation) else {
702 return false;
703 };
704 if !sync.running() {
705 return false;
706 }
707 match stage {
708 0 => sync.shown_at = Some(Instant::now()),
709 1 if sync.messages => {
710 sync.trailing_skeleton = true;
711 self.rebuild(false, cx);
712 }
713 1 => {}
714 _ => sync.slow = true,
715 }
716 cx.notify();
717 true
718 }
719
720 fn finish_fetch(
721 &mut self,
722 generation: u64,
723 result: Result<
724 teams_core::Result<teams_core::Delta>,
725 tokio::sync::oneshot::error::RecvError,
726 >,
727 cx: &mut Context<Self>,
728 ) {
729 let Some(sync) = self.sync_of(generation) else {
730 return;
731 };
732 sync.messages = false;
733 sync.trailing_skeleton = false;
734 let newest_cached = sync.newest_cached;
735 match result {
736 Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx),
737 Ok(Err(error)) => self.fail_sync(generation, short_error(&error)),
738 Err(error) => self.fail_sync(generation, short_error(&error)),
739 }
740 self.rebuild(false, cx);
741 self.settle_progress(generation, cx);
742 }
743
744 fn fail_sync(&mut self, generation: u64, error: String) {
745 if let Some(sync) = self.sync_of(generation) {
746 sync.failed = true;
747 sync.receipts = false;
748 }
749 self.notice = Some(format!("Could not refresh: {error}"));
750 }
751
752 fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) {
753 let Some(newest_cached) = newest_cached else {
754 return;
755 };
756 let Some(my_user_id) = self.row_context(cx).my_user_id else {
757 return;
758 };
759 let store = self.app.read(cx).store.clone();
760 let Some(current) = self.current.as_mut() else {
761 return;
762 };
763 if current.first_unread.is_some() || current.mode != ViewMode::Flat {
764 return;
765 }
766 let limit = current
767 .loaded_limit
768 .max(current.loaded_count + GROWTH_HEADROOM);
769 current.first_unread = store
770 .messages(current.selection.conversation_id(), None, limit)
771 .unwrap_or_default()
772 .into_iter()
773 .find(|record| {
774 record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id)
775 })
776 .map(|record| record.message_id);
777 }
778
779 fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
780 let Some(sync) = self.sync_of(generation) else {
781 return;
782 };
783 if sync.running() {
784 return;
785 }
786 let remaining = sync
787 .shown_at
788 .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed()))
789 .unwrap_or_default();
790 if remaining.is_zero() {
791 sync.shown_at = None;
792 sync.slow = false;
793 cx.notify();
794 return;
795 }
796 cx.spawn(async move |this, cx| {
797 cx.background_executor().timer(remaining).await;
798 this.update(cx, |this, cx| {
799 if let Some(sync) = this.sync_of(generation) {
800 sync.shown_at = None;
801 sync.slow = false;
802 cx.notify();
803 }
804 })
805 .ok();
806 })
807 .detach();
808 }
809
810 fn retry_fetch(&mut self, cx: &mut Context<Self>) {
811 if let Some(current) = self.current.as_mut() {
812 current.fetched = false;
813 }
814 self.start_fetch(cx);
815 }
816
817 fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
818 let state = self.app.read(cx);
819 let receipts_syncing = self
820 .current
821 .as_ref()
822 .is_some_and(|current| current.sync.receipts);
823 if state.mode.demo {
824 let read_ids = crate::demo::read_message_ids(records);
825 return records
826 .iter()
827 .map(|record| {
828 let receipt = if receipts_syncing {
829 Receipt::Pending
830 } else if read_ids.contains(&record.message_id) {
831 Receipt::Read
832 } else {
833 Receipt::Sent
834 };
835 (record.message_id.clone(), receipt)
836 })
837 .collect();
838 }
839 let Some(engine) = state.engine.as_ref() else {
840 return HashMap::new();
841 };
842 let unknown = if receipts_syncing {
843 Receipt::Pending
844 } else {
845 Receipt::Hidden
846 };
847 records
848 .iter()
849 .map(|record| {
850 let receipt = match engine.receipt_state_for(record) {
851 teams_core::ReceiptState::Read { .. } => Receipt::Read,
852 teams_core::ReceiptState::Sent => Receipt::Sent,
853 teams_core::ReceiptState::Unknown => unknown,
854 };
855 (record.message_id.clone(), receipt)
856 })
857 .collect()
858 }
859
860 fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {
861 let state = self.app.read(cx);
862 let (Some(engine), Some(Selection::Chat(chat_id))) = (
863 state.engine.clone(),
864 self.current.as_ref().map(|c| c.selection.clone()),
865 ) else {
866 return;
867 };
868 let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await });
869 cx.spawn(async move |this, cx| {
870 receiver.await.ok();
871 this.update(cx, |this, cx| {
872 let Some(sync) = this.sync_of(generation) else {
873 return;
874 };
875 sync.receipts = false;
876 this.rebuild(false, cx);
877 this.settle_progress(generation, cx);
878 })
879 .ok();
880 })
881 .detach();
882 }
883
884 fn mark_read(&mut self, cx: &mut Context<Self>) {
885 let state = self.app.read(cx);
886 let (Some(engine), Some(Selection::Chat(chat_id))) = (
887 state.engine.clone(),
888 self.current.as_ref().map(|c| c.selection.clone()),
889 ) else {
890 return;
891 };
892 if state.mode.read_only || state.mode.demo {
893 return;
894 }
895 let unread = state
896 .sidebar
897 .chats
898 .iter()
899 .any(|chat| chat.id == chat_id && chat.unread);
900 if !unread {
901 return;
902 }
903 drop(runtime::spawn(
904 async move { engine.mark_read(&chat_id).await },
905 ));
906 }
907
908 fn request_older(&mut self, cx: &mut Context<Self>) {
909 let Some(engine) = self.app.read(cx).engine.clone() else {
910 return;
911 };
912 let Some(current) = self.current.as_mut() else {
913 return;
914 };
915 if current.loading_older || current.older_blocked || !current.has_older {
916 return;
917 }
918 current.loading_older = true;
919 let conversation_id = current.selection.conversation_id().to_owned();
920 let task_id = conversation_id.clone();
921 let receiver = runtime::spawn(async move { engine.load_older(&task_id).await });
922 cx.spawn(async move |this, cx| {
923 let result = receiver.await;
924 this.update(cx, |this, cx| {
925 this.finish_older(&conversation_id, result, cx)
926 })
927 .ok();
928 })
929 .detach();
930 }
931
932 fn finish_older(
933 &mut self,
934 conversation_id: &str,
935 result: Result<
936 teams_core::Result<Vec<MessageRecord>>,
937 tokio::sync::oneshot::error::RecvError,
938 >,
939 cx: &mut Context<Self>,
940 ) {
941 let Some(current) = self.current.as_mut() else {
942 return;
943 };
944 if current.selection.conversation_id() != conversation_id {
945 return;
946 }
947 current.loading_older = false;
948 match result {
949 Ok(Ok(records)) if !records.is_empty() => {
950 current.loaded_limit = current.loaded_count + records.len();
951 }
952 Ok(Ok(_)) => current.older_blocked = true,
953 Ok(Err(error)) => {
954 current.older_blocked = true;
955 self.notice = Some(format!(
956 "Could not load older messages: {}",
957 short_error(&error)
958 ));
959 }
960 Err(_) => current.older_blocked = true,
961 }
962 self.rebuild(false, cx);
963 }
964
965 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
966 if let Some(current) = self.current.as_mut() {
967 current.mode = ViewMode::Thread(root_id);
968 }
969 self.pending.clear();
970 self.rebuild(true, cx);
971 }
972
973 fn back_to_threads(&mut self, cx: &mut Context<Self>) {
974 if let Some(current) = self.current.as_mut() {
975 current.mode = ViewMode::ThreadList;
976 }
977 self.pending.clear();
978 self.rebuild(true, cx);
979 }
980
981 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
982 let state = self.app.read(cx);
983 let (mode, engine) = (state.mode, state.engine.clone());
984 let Some(current) = self.current.as_ref() else {
985 return;
986 };
987 let restore =
988 |this: &mut Self, message: &str, window: &mut Window, cx: &mut Context<Self>| {
989 this.notice = Some(message.to_owned());
990 this.composer
991 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
992 cx.notify();
993 };
994 if mode.read_only || mode.demo {
995 restore(self, "Read-only mode: nothing was sent", window, cx);
996 return;
997 }
998 let Some(engine) = engine else {
999 restore(self, "Not connected yet: nothing was sent", window, cx);
1000 return;
1001 };
1002 let conversation_id = current.selection.conversation_id().to_owned();
1003 let view_mode = current.mode.clone();
1004 self.pending_counter += 1;
1005 let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
1006 let my_user_id = self.row_context(cx).my_user_id;
1007 self.pending_outgoing.insert(key.clone(), outgoing.clone());
1008 self.pending.push(MessageRow {
1009 key: key.clone(),
1010 author: "You".to_owned(),
1011 sender_id: my_user_id,
1012 created_at: Utc::now(),
1013 series: Series::default(),
1014 card: false,
1015 time: chrono::Local::now().format("%H:%M").to_string(),
1016 day_header: None,
1017 blocks: vec![Block::Paragraph(Inline::plain(&outgoing.text))],
1018 edited: false,
1019 deleted: false,
1020 reactions: Vec::new(),
1021 images: Vec::new(),
1022 files: Vec::new(),
1023 reply_count: None,
1024 new_marker: false,
1025 reply_faces: Vec::new(),
1026 last_reply_time: None,
1027 open_thread: None,
1028 is_reply: false,
1029 delivery: Delivery::Sending,
1030 receipt: Receipt::Hidden,
1031 own: true,
1032 });
1033 self.notice = None;
1034 self.rebuild(false, cx);
1035 self.scroller
1036 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
1037
1038 let sent = outgoing.clone();
1039 let receiver = runtime::spawn(async move {
1040 let Outgoing {
1041 text,
1042 mentions,
1043 reply,
1044 } = &sent;
1045 match (&view_mode, reply) {
1046 (_, Some(reply)) => {
1047 engine
1048 .reply_to_with_mentions(&conversation_id, &reply.message_id, text, mentions)
1049 .await
1050 }
1051 (ViewMode::Flat, None) => {
1052 engine
1053 .send_message_with_mentions(&conversation_id, text, None, mentions)
1054 .await
1055 }
1056 (ViewMode::ThreadList, None) => {
1057 engine
1058 .post_to_channel_with_mentions(&conversation_id, text, None, mentions)
1059 .await
1060 }
1061 (ViewMode::Thread(root_id), None) => {
1062 engine
1063 .send_message_with_mentions(&conversation_id, text, Some(root_id), mentions)
1064 .await
1065 }
1066 }
1067 .map(|_| ())
1068 });
1069 cx.spawn_in(window, async move |this, cx| {
1070 let result = receiver.await;
1071 this.update_in(cx, |this, window, cx| {
1072 this.finish_send(&key, result, window, cx)
1073 })
1074 .ok();
1075 })
1076 .detach();
1077 }
1078
1079 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
1080 let Some(outgoing) = self.pending_outgoing.remove(key) else {
1081 return;
1082 };
1083 self.pending.retain(|row| row.key != key);
1084 self.send(outgoing, window, cx);
1085 }
1086
1087 fn finish_send(
1088 &mut self,
1089 key: &str,
1090 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
1091 window: &mut Window,
1092 cx: &mut Context<Self>,
1093 ) {
1094 let failure = match result {
1095 Ok(Ok(())) => None,
1096 Ok(Err(error)) => Some(short_error(&error)),
1097 Err(error) => Some(short_error(&error)),
1098 };
1099 match failure {
1100 None => {
1101 self.pending.retain(|row| row.key != key);
1102 self.pending_outgoing.remove(key);
1103 }
1104 Some(error) => {
1105 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
1106 row.delivery = Delivery::Failed(error.clone());
1107 }
1108 self.notice = Some(format!("Not sent: {error}"));
1109 if self.composer.read(cx).is_empty(cx)
1110 && let Some(outgoing) = self.pending_outgoing.get(key).cloned()
1111 {
1112 self.composer
1113 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1114 }
1115 }
1116 }
1117 self.rebuild(false, cx);
1118 }
1119
1120 fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement {
1121 let app = self.app.read(cx);
1122 let directory = &app.directory;
1123 let me = directory.me.as_ref();
1124 let mut lead: Option<AnyElement> = None;
1125 let mut subline = String::new();
1126 let mut stack: Option<Div> = None;
1127 match &current.selection {
1128 Selection::Chat(chat_id) => {
1129 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
1130 let faces = others(chat, me);
1131 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
1132 let first = faces.first().cloned().map(face);
1133 if is_one_on_one(chat) || faces.len() < 2 {
1134 let name = first
1135 .as_ref()
1136 .map_or(current.title.as_str(), |face| face.name.as_str());
1137 let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
1138 let avatar = person_avatar(directory, user_id, name, 36.);
1139 let presence = user_id.map(|id| directory.presence_of(id));
1140 lead = Some(match presence {
1141 Some(kind) => with_presence(avatar, kind, 36., theme::background())
1142 .into_any_element(),
1143 None => avatar,
1144 });
1145 subline = presence
1146 .map(|kind| kind.label().to_owned())
1147 .unwrap_or_default();
1148 } else {
1149 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
1150 lead = Some(spec_avatar(directory, &pair, 36., theme::background()));
1151 subline = format!("{} participants", chat.members.len());
1152 let shown: Vec<Face> = faces.iter().cloned().map(face).collect();
1153 stack = Some(member_stack(directory, &shown, shown.len()));
1154 }
1155 }
1156 }
1157 Selection::Channel(channel_id) => {
1158 let team = app.sidebar.teams.iter().find(|entry| {
1159 entry
1160 .channels
1161 .iter()
1162 .any(|channel| &channel.id == channel_id)
1163 });
1164 let (name, key) = team
1165 .map_or((current.title.as_str(), current.title.as_str()), |entry| {
1166 (entry.team.name.as_str(), entry.team.id.as_str())
1167 });
1168 lead = Some(square_avatar(name, key, 36., 9.).into_any_element());
1169 }
1170 }
1171 let mut header = h_flex()
1172 .w_full()
1173 .h(px(60.))
1174 .flex_none()
1175 .px(px(20.))
1176 .gap(px(12.))
1177 .items_center()
1178 .border_b_1()
1179 .border_color(theme::border());
1180 if matches!(current.mode, ViewMode::Thread(_)) {
1181 header = header.child(
1182 Button::new("back-to-threads")
1183 .ghost()
1184 .compact()
1185 .label("Threads")
1186 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx))),
1187 );
1188 }
1189 let channel_note = match current.mode {
1190 ViewMode::Flat => None,
1191 ViewMode::ThreadList => Some("Threads"),
1192 ViewMode::Thread(_) => Some("Thread"),
1193 };
1194 if let Some(note) = channel_note {
1195 subline = note.to_owned();
1196 }
1197 let sync = &current.sync;
1198 if sync.failed {
1199 subline = "Not up to date".to_owned();
1200 } else if sync.shown_at.is_some() {
1201 subline = if sync.slow {
1202 "Taking longer than usual ..."
1203 } else if sync.empty_cache {
1204 "Loading messages ..."
1205 } else {
1206 "Updating ..."
1207 }
1208 .to_owned();
1209 }
1210 header
1211 .relative()
1212 .when(sync.shown_at.is_some(), |header| {
1213 header.child(progress_bar())
1214 })
1215 .children(lead)
1216 .child(
1217 v_flex()
1218 .flex_1()
1219 .min_w_0()
1220 .overflow_hidden()
1221 .gap(px(1.))
1222 .child(
1223 div()
1224 .truncate()
1225 .text_size(px(15.))
1226 .font_weight(FontWeight::SEMIBOLD)
1227 .text_color(theme::text())
1228 .child(current.title.clone()),
1229 )
1230 .when(!subline.is_empty(), |column| {
1231 column.child(
1232 div()
1233 .text_size(px(12.))
1234 .text_color(theme::text_muted())
1235 .child(subline),
1236 )
1237 }),
1238 )
1239 .children(stack)
1240 }
1241}
1242
1243impl Render for ConversationView {
1244 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1245 let background = theme::background();
1246 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
1247 let Some(current) = self.current.as_ref() else {
1248 return root
1249 .items_center()
1250 .justify_center()
1251 .text_color(theme::text_muted())
1252 .child("Select a chat or channel")
1253 .into_any_element();
1254 };
1255 let rows = self.rows.clone();
1256 let view = cx.weak_entity();
1257 let app = self.app.clone();
1258 let highlighted = self.highlighted_message.clone();
1259 let scroller = MessageScroller::new(
1260 "messages",
1261 self.scroller.clone(),
1262 move |index, window, cx| {
1263 let rows = rows.borrow();
1264 match rows.get(index) {
1265 Some(Row::Message(message)) => {
1266 let open_thread = message.open_thread.clone().map(|root_id| {
1267 let view = view.clone();
1268 Box::new(move |cx: &mut App| {
1269 let root_id = root_id.clone();
1270 view.update(cx, |this, cx| this.open_thread(root_id, cx))
1271 .ok();
1272 }) as Box<dyn Fn(&mut App)>
1273 });
1274 let retry = matches!(message.delivery, Delivery::Failed(_)).then(|| {
1275 let (view, key, handle) =
1276 (view.clone(), message.key.clone(), window.window_handle());
1277 Box::new(move |cx: &mut App| {
1278 let (view, key) = (view.clone(), key.clone());
1279 handle
1280 .update(cx, move |_, window, cx| {
1281 view.update(cx, |this, cx| this.retry(&key, window, cx))
1282 .ok();
1283 })
1284 .ok();
1285 }) as Box<dyn Fn(&mut App)>
1286 });
1287 let sender = (!message.own && !message.series.has_prev)
1288 .then(|| message.sender_id.clone())
1289 .flatten()
1290 .filter(|sender| app.read(cx).directory.avatar(sender).is_none());
1291 if let Some(sender) = sender {
1292 let app = app.clone();
1293 cx.defer(move |cx| {
1294 app.update(cx, |state, cx| state.request_avatars(vec![sender], cx));
1295 });
1296 }
1297 let missing_images: Vec<ImageRef> = message
1298 .images
1299 .iter()
1300 .filter(|image| app.read(cx).directory.image(&image.url).is_none())
1301 .cloned()
1302 .collect();
1303 if !missing_images.is_empty() {
1304 let app = app.clone();
1305 cx.defer(move |cx| {
1306 app.update(cx, |state, cx| {
1307 state.request_images(missing_images, cx)
1308 });
1309 });
1310 }
1311 let is_real = !message.key.starts_with(PENDING_KEY_PREFIX);
1312 let hovered = is_real.then(|| {
1313 let (view, key) = (view.clone(), message.key.clone());
1314 Box::new(move |cx: &mut App| {
1315 view.update(cx, |this, _| {
1316 this.hovered_message = Some(key.clone());
1317 })
1318 .ok();
1319 }) as Box<dyn Fn(&mut App)>
1320 });
1321 let reply = (is_real && !message.deleted).then(|| {
1322 let (view, key, handle) =
1323 (view.clone(), message.key.clone(), window.window_handle());
1324 Box::new(move |cx: &mut App| {
1325 let (view, key) = (view.clone(), key.clone());
1326 handle
1327 .update(cx, move |_, window, cx| {
1328 view.update(cx, |this, cx| {
1329 this.begin_reply(&key, window, cx)
1330 })
1331 .ok();
1332 })
1333 .ok();
1334 }) as Box<dyn Fn(&mut App)>
1335 });
1336 let state = app.read(cx);
1337 render_message_row(
1338 message,
1339 index,
1340 RowActions {
1341 open_thread,
1342 retry,
1343 reply,
1344 hovered,
1345 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
1346 },
1347 &state.directory,
1348 cx,
1349 )
1350 }
1351 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
1352 Some(Row::LoadOlder) => {
1353 let view = view.clone();
1354 cx.defer(move |cx| {
1355 view.update(cx, |this, cx| this.request_older(cx)).ok();
1356 });
1357 h_flex()
1358 .w_full()
1359 .py_2()
1360 .gap(px(6.))
1361 .justify_center()
1362 .text_size(px(12.))
1363 .text_color(theme::text_muted())
1364 .child(icon(IconName::Loader, 12., theme::text_muted()))
1365 .child("Loading older messages")
1366 .into_any_element()
1367 }
1368 Some(Row::Start(start)) => {
1369 let state = app.read(cx);
1370 v_flex()
1371 .w_full()
1372 .items_center()
1373 .gap(px(8.))
1374 .pt(px(32.))
1375 .pb(px(16.))
1376 .child(person_avatar(
1377 &state.directory,
1378 start.user_id.as_deref(),
1379 &start.title,
1380 56.,
1381 ))
1382 .child(
1383 div()
1384 .text_size(px(16.))
1385 .font_weight(FontWeight::SEMIBOLD)
1386 .text_color(theme::text())
1387 .child(start.title.clone()),
1388 )
1389 .child(
1390 div()
1391 .text_size(px(12.))
1392 .text_color(theme::text_muted())
1393 .child("This is the beginning of the conversation"),
1394 )
1395 .into_any_element()
1396 }
1397 None => div().into_any_element(),
1398 }
1399 },
1400 )
1401 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
1402 .with_bottom_fade(background);
1403
1404 root = root.child(self.render_header(current, cx));
1405 if let Some(notice) = &self.notice {
1406 root = root.child(
1407 h_flex()
1408 .px_4()
1409 .py_1()
1410 .gap(px(8.))
1411 .items_center()
1412 .text_xs()
1413 .bg(theme::amber().opacity(0.15))
1414 .text_color(theme::amber())
1415 .child(div().flex_1().min_w_0().child(notice.clone()))
1416 .when(current.sync.failed, |bar| {
1417 bar.child(
1418 Button::new("retry-fetch")
1419 .ghost()
1420 .compact()
1421 .label("Retry")
1422 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
1423 )
1424 }),
1425 );
1426 }
1427 let empty_channel = current.mode == ViewMode::ThreadList && self.rows.borrow().is_empty();
1428 let body = if empty_channel {
1429 div()
1430 .size_full()
1431 .flex()
1432 .items_center()
1433 .justify_center()
1434 .text_size(px(13.))
1435 .text_color(theme::text_muted())
1436 .child("No posts in this channel yet")
1437 .into_any_element()
1438 } else {
1439 scroller.into_any_element()
1440 };
1441 root.child(div().flex_1().min_h_0().child(body))
1442 .child(self.composer.clone())
1443 .into_any_element()
1444 }
1445}
1446
1447fn progress_bar() -> impl IntoElement {
1448 div()
1449 .absolute()
1450 .left_0()
1451 .right_0()
1452 .bottom(px(-1.))
1453 .h(px(2.))
1454 .overflow_hidden()
1455 .bg(theme::border())
1456 .child(
1457 div()
1458 .absolute()
1459 .top_0()
1460 .h_full()
1461 .w(relative(PROGRESS_BAR_WIDTH))
1462 .bg(theme::own_read())
1463 .with_animation(
1464 "sync-progress",
1465 Animation::new(PROGRESS_BAR_PERIOD).repeat(),
1466 |bar, delta| {
1467 let travel = 1. + PROGRESS_BAR_WIDTH;
1468 // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).
1469 bar.left(relative(
1470 (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,
1471 ))
1472 },
1473 ),
1474 )
1475}