BlueGit

ict rusty-teams

Files

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

conversation.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
conversation.rs 42.4 KiB Download Raw
1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::rc::Rc;
4use std::time::Duration;
5
6use chrono::{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};
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, Row, RowContext, Series, StartInfo, assign_series, changed_indices,
29 diff_keys, flat_rows, reply_excerpt, thread_list_rows, thread_rows,
30};
31use crate::runtime;
32use crate::sidebar_model::{AvatarSpec, Face};
33use crate::theme;
34
35const CHAT_OPEN_LIMIT: usize = 60;
36const CHANNEL_OPEN_LIMIT: usize = 300;
37const GROWTH_HEADROOM: usize = 20;
38const META_USER_ID: &str = "me_user_id";
39const PENDING_KEY_PREFIX: &str = "pending-";
40const MAX_NOTICE_CHARS: usize = 140;
41const JUMP_SCAN_LIMIT: usize = 5000;
42const JUMP_CONTEXT_MESSAGES: usize = 12;
43const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
44
45actions!(teams, [ReplyToHovered]);
46
47#[derive(Debug, Clone, PartialEq, Eq)]
48enum ViewMode {
49 Flat,
50 ThreadList,
51 Thread(String),
52}
53
54struct Current {
55 selection: Selection,
56 title: String,
57 mode: ViewMode,
58 loaded_limit: usize,
59 loaded_count: usize,
60 has_older: bool,
61 loading_older: bool,
62 older_blocked: bool,
63 fetched: bool,
64 first_unread: Option<String>,
65}
66
67pub struct ConversationView {
68 app: Entity<AppState>,
69 scroller: Entity<MessageScrollerState>,
70 composer: Entity<Composer>,
71 rows: Rc<RefCell<Vec<Row>>>,
72 current: Option<Current>,
73 pending: Vec<MessageRow>,
74 pending_counter: usize,
75 pending_outgoing: HashMap<String, Outgoing>,
76 hovered_message: Option<String>,
77 highlighted_message: Option<String>,
78 notice: Option<String>,
79 _subscriptions: Vec<Subscription>,
80}
81
82fn open_limit(selection: &Selection) -> usize {
83 match selection {
84 Selection::Chat(_) => CHAT_OPEN_LIMIT,
85 Selection::Channel(_) => CHANNEL_OPEN_LIMIT,
86 }
87}
88
89fn short_error(error: &dyn std::fmt::Display) -> String {
90 error.to_string().chars().take(MAX_NOTICE_CHARS).collect()
91}
92
93impl ConversationView {
94 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
95 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
96 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
97 let subscriptions = vec![
98 cx.subscribe_in(&app, window, Self::on_app_event),
99 cx.subscribe_in(&composer, window, Self::on_composer_event),
100 ];
101 let mut view = ConversationView {
102 app,
103 scroller,
104 composer,
105 rows: Rc::new(RefCell::new(Vec::new())),
106 current: None,
107 pending: Vec::new(),
108 pending_counter: 0,
109 pending_outgoing: HashMap::new(),
110 hovered_message: None,
111 highlighted_message: None,
112 notice: None,
113 _subscriptions: subscriptions,
114 };
115 if let Some(selection) = view.app.read(cx).selection.clone() {
116 view.open(selection, window, cx);
117 }
118 view
119 }
120
121 #[cfg_attr(not(windows), allow(dead_code))]
122 pub fn composer_is_empty(&self, cx: &App) -> bool {
123 self.composer.read(cx).is_empty(cx)
124 }
125
126 #[cfg_attr(not(windows), allow(dead_code))]
127 pub fn send_in_flight(&self) -> bool {
128 self.pending
129 .iter()
130 .any(|row| matches!(row.delivery, Delivery::Sending))
131 }
132
133 fn on_app_event(
134 &mut self,
135 _: &Entity<AppState>,
136 event: &AppEvent,
137 window: &mut Window,
138 cx: &mut Context<Self>,
139 ) {
140 match event {
141 AppEvent::Selection => {
142 if let Some(selection) = self.app.read(cx).selection.clone() {
143 self.open(selection, window, cx);
144 }
145 }
146 AppEvent::Messages(conversation_id) => {
147 let is_current = self
148 .current
149 .as_ref()
150 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
151 if is_current {
152 self.rebuild(false, cx);
153 self.mark_read(cx);
154 }
155 }
156 AppEvent::Images(keys) => self.remeasure_images(keys, cx),
157 AppEvent::Jump => self.apply_pending_jump(cx),
158 AppEvent::Status => self.start_fetch(cx),
159 AppEvent::Directory => cx.notify(),
160 AppEvent::Sidebar => {
161 if let Some(current) = self.current.as_mut() {
162 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
163 if current.title != title {
164 current.title = title.clone();
165 let conversation_id = current.selection.conversation_id().to_owned();
166 self.composer.update(cx, |composer, cx| {
167 composer.set_conversation(&conversation_id, &title, window, cx)
168 });
169 cx.notify();
170 }
171 }
172 }
173 }
174 }
175
176 fn on_composer_event(
177 &mut self,
178 _: &Entity<Composer>,
179 event: &ComposerEvent,
180 window: &mut Window,
181 cx: &mut Context<Self>,
182 ) {
183 let ComposerEvent::Submit(outgoing) = event;
184 self.send(outgoing.clone(), window, cx);
185 }
186
187 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
188 let title = selection_title(&self.app.read(cx).sidebar, &selection);
189 let mode = match selection {
190 Selection::Chat(_) => ViewMode::Flat,
191 Selection::Channel(_) => ViewMode::ThreadList,
192 };
193 let first_unread = self.first_unread_id(&selection, cx);
194 self.current = Some(Current {
195 loaded_limit: open_limit(&selection),
196 selection,
197 title,
198 mode,
199 loaded_count: 0,
200 has_older: false,
201 loading_older: false,
202 older_blocked: false,
203 fetched: false,
204 first_unread,
205 });
206 self.pending.clear();
207 self.notice = None;
208 self.rebuild(true, cx);
209 self.start_fetch(cx);
210 self.mark_read(cx);
211 let target = self
212 .current
213 .as_ref()
214 .map(|current| {
215 (
216 current.selection.conversation_id().to_owned(),
217 current.title.clone(),
218 )
219 })
220 .unwrap_or_default();
221 self.composer.update(cx, |composer, cx| {
222 composer.set_conversation(&target.0, &target.1, window, cx);
223 composer.focus(window, cx);
224 });
225 self.hovered_message = None;
226 self.apply_pending_jump(cx);
227 }
228
229 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
230 let indices: Vec<usize> = self
231 .rows
232 .borrow()
233 .iter()
234 .enumerate()
235 .filter_map(|(index, row)| match row {
236 Row::Message(message)
237 if message.images.iter().any(|image| keys.contains(&image.url)) =>
238 {
239 Some(index)
240 }
241 _ => None,
242 })
243 .collect();
244 self.scroller.update(cx, |scroller, cx| {
245 for index in indices {
246 scroller.remeasure_items(index..index + 1, cx);
247 }
248 });
249 cx.notify();
250 }
251
252 fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {
253 let Some(conversation_id) = self
254 .current
255 .as_ref()
256 .map(|current| current.selection.conversation_id().to_owned())
257 else {
258 return;
259 };
260 let jump = self
261 .app
262 .update(cx, |state, _| match state.pending_jump.take() {
263 Some((target, message_id)) if target == conversation_id => Some(message_id),
264 other => {
265 state.pending_jump = other;
266 None
267 }
268 });
269 if let Some(message_id) = jump {
270 self.jump_to_message(&conversation_id, &message_id, cx);
271 }
272 }
273
274 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
275 let store = self.app.read(cx).store.clone();
276 let Some(record) = store
277 .messages_by_id(conversation_id, &[message_id.to_owned()])
278 .ok()
279 .and_then(|mut found| found.remove(message_id))
280 else {
281 return;
282 };
283 let messages_from_target = store
284 .messages(conversation_id, None, JUMP_SCAN_LIMIT)
285 .ok()
286 .and_then(|all| {
287 all.iter()
288 .position(|candidate| candidate.message_id == message_id)
289 .map(|position| all.len() - position)
290 })
291 .unwrap_or_default();
292 let row_key = record
293 .reply_to_id
294 .clone()
295 .unwrap_or_else(|| message_id.to_owned());
296 let Some(current) = self.current.as_mut() else {
297 return;
298 };
299 current.loaded_limit = current
300 .loaded_limit
301 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
302 current.first_unread = None;
303 if matches!(current.selection, Selection::Channel(_)) {
304 current.mode = match record.reply_to_id {
305 Some(root_id) => ViewMode::Thread(root_id),
306 None => ViewMode::ThreadList,
307 };
308 }
309 let target_key = if matches!(current.mode, ViewMode::Thread(_)) {
310 message_id.to_owned()
311 } else {
312 row_key
313 };
314 self.pending.clear();
315 self.rebuild(true, cx);
316 let index = self
317 .rows
318 .borrow()
319 .iter()
320 .position(|row| row.key() == target_key);
321 if let Some(index) = index {
322 self.scroller
323 .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx));
324 self.highlight(target_key, cx);
325 }
326 }
327
328 fn highlight(&mut self, key: String, cx: &mut Context<Self>) {
329 self.highlighted_message = Some(key.clone());
330 cx.notify();
331 cx.spawn(async move |this, cx| {
332 cx.background_executor().timer(HIGHLIGHT_DURATION).await;
333 this.update(cx, |this, cx| {
334 if this.highlighted_message.as_deref() == Some(key.as_str()) {
335 this.highlighted_message = None;
336 cx.notify();
337 }
338 })
339 .ok();
340 })
341 .detach();
342 }
343
344 pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
345 self.composer
346 .update(cx, |composer, cx| composer.set_text(text, window, cx));
347 self.composer
348 .update(cx, |composer, cx| composer.focus(window, cx));
349 }
350
351 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
352 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
353 Row::Message(message) if !message.own => Some(message.key.clone()),
354 _ => None,
355 });
356 if let Some(key) = key {
357 self.begin_reply(&key, window, cx);
358 }
359 }
360
361 pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) {
362 if let Some(message_id) = self.hovered_message.clone() {
363 self.begin_reply(&message_id, window, cx);
364 }
365 }
366
367 fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
368 let Some(conversation_id) = self
369 .current
370 .as_ref()
371 .map(|current| current.selection.conversation_id().to_owned())
372 else {
373 return;
374 };
375 let store = self.app.read(cx).store.clone();
376 let record = store
377 .messages_by_id(&conversation_id, &[message_id.to_owned()])
378 .ok()
379 .and_then(|mut found| found.remove(message_id))
380 .filter(|record| !record.deleted);
381 let Some(record) = record else {
382 return;
383 };
384 let preview = ReplyPreview {
385 message_id: record.message_id.clone(),
386 author: record
387 .sender_name
388 .clone()
389 .unwrap_or_else(|| "Unbekannt".to_owned()),
390 excerpt: reply_excerpt(&record),
391 };
392 self.composer.update(cx, |composer, cx| {
393 composer.set_reply(Some(preview), cx);
394 composer.focus(window, cx);
395 });
396 }
397
398 fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> {
399 let Selection::Chat(chat_id) = selection else {
400 return None;
401 };
402 let state = self.app.read(cx);
403 if state.mode.demo {
404 return crate::demo::first_unread(chat_id);
405 }
406 state.engine.as_ref()?.first_unread_message_id(chat_id)
407 }
408
409 fn row_context(&self, cx: &App) -> RowContext {
410 let now = Local::now();
411 RowContext {
412 offset: now.offset().fix(),
413 today: now.date_naive(),
414 my_user_id: self.app.read(cx).store.meta(META_USER_ID).ok().flatten(),
415 }
416 }
417
418 fn start_info(&self, cx: &App) -> Option<StartInfo> {
419 let current = self.current.as_ref()?;
420 let app = self.app.read(cx);
421 let user_id = match &current.selection {
422 Selection::Chat(chat_id) => app
423 .sidebar
424 .chats
425 .iter()
426 .find(|chat| &chat.id == chat_id)
427 .filter(|chat| is_one_on_one(chat))
428 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next())
429 .and_then(|(user_id, _)| user_id),
430 Selection::Channel(_) => None,
431 };
432 Some(StartInfo {
433 title: current.title.clone(),
434 user_id,
435 })
436 }
437
438 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
439 let Some(current) = self.current.as_ref() else {
440 self.apply_rows(Vec::new(), true, cx);
441 return;
442 };
443 let conversation_id = current.selection.conversation_id().to_owned();
444 let limit = if reset {
445 current.loaded_limit
446 } else {
447 current
448 .loaded_limit
449 .max(current.loaded_count + GROWTH_HEADROOM)
450 };
451 let store = self.app.read(cx).store.clone();
452 let records: Vec<MessageRecord> = store
453 .messages(&conversation_id, None, limit)
454 .unwrap_or_default();
455 let sync_has_more = store
456 .sync_state(&conversation_id)
457 .ok()
458 .flatten()
459 .is_none_or(|state| state.has_more);
460 let context = self.row_context(cx);
461 let can_load_older = self.app.read(cx).engine.is_some();
462 let start = self.start_info(cx);
463 let current = self.current.as_mut().expect("checked above");
464 let first_unread = current.first_unread.clone();
465 current.loaded_limit = limit;
466 current.loaded_count = records.len();
467 let has_older = sync_has_more && !current.older_blocked && can_load_older;
468 let mut rows = match &current.mode {
469 ViewMode::Flat => {
470 current.has_older = has_older;
471 let mut rows = flat_rows(&records, &context, has_older);
472 if !has_older && let Some(start) = start {
473 rows.insert(0, Row::Start(start));
474 }
475 rows
476 }
477 ViewMode::ThreadList => {
478 current.has_older = has_older;
479 thread_list_rows(&records, &context, has_older)
480 }
481 ViewMode::Thread(root_id) => {
482 current.has_older = false;
483 thread_rows(&records, root_id, &context)
484 }
485 };
486 rows.extend(
487 self.pending
488 .iter()
489 .cloned()
490 .map(|row| Row::Message(Box::new(row))),
491 );
492 let read_ids = self.read_message_ids(&records, cx);
493 for row in rows.iter_mut() {
494 if let Row::Message(message) = row {
495 message.read = read_ids.contains(&message.key);
496 }
497 }
498 if let Some(unread_id) = &first_unread {
499 for row in rows.iter_mut() {
500 if let Row::Message(message) = row
501 && &message.key == unread_id
502 {
503 message.new_marker = true;
504 }
505 }
506 }
507 assign_series(&mut rows);
508 self.apply_rows(rows, reset, cx);
509 }
510
511 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
512 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
513 let new_len = self.rows.borrow().len();
514 if reset {
515 let marker_index = self
516 .rows
517 .borrow()
518 .iter()
519 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
520 self.scroller.update(cx, |scroller, cx| {
521 scroller.reset(new_len, cx);
522 match marker_index {
523 Some(index) if !scroller.scroll_to_item(index, cx) => {
524 scroller.scroll_to_end(cx)
525 }
526 Some(_) => {}
527 None => scroller.scroll_to_end(cx),
528 }
529 });
530 cx.notify();
531 return;
532 }
533 let (splice, changed) = {
534 let new_rows = self.rows.borrow();
535 let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect();
536 let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect();
537 (
538 diff_keys(&old_keys, &new_keys),
539 changed_indices(&old_rows, &new_rows),
540 )
541 };
542 self.scroller.update(cx, |scroller, cx| {
543 if let Some(splice) = splice
544 && !scroller.splice(splice.range, splice.count, cx)
545 {
546 scroller.reset(new_len, cx);
547 }
548 for index in changed {
549 scroller.remeasure_items(index..index + 1, cx);
550 }
551 });
552 cx.notify();
553 }
554
555 fn start_fetch(&mut self, cx: &mut Context<Self>) {
556 let Some(engine) = self.app.read(cx).engine.clone() else {
557 return;
558 };
559 let Some(current) = self.current.as_mut() else {
560 return;
561 };
562 if current.fetched {
563 return;
564 }
565 current.fetched = true;
566 let conversation_id = current.selection.conversation_id().to_owned();
567 let receiver = runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
568 cx.spawn(async move |this, cx| {
569 if let Ok(Err(error)) = receiver.await {
570 this.update(cx, |this, cx| {
571 this.notice = Some(format!("Could not refresh: {}", short_error(&error)));
572 cx.notify();
573 })
574 .ok();
575 }
576 })
577 .detach();
578 self.mark_read(cx);
579 self.refresh_receipts(cx);
580 }
581
582 fn read_message_ids(
583 &self,
584 records: &[MessageRecord],
585 cx: &App,
586 ) -> std::collections::HashSet<String> {
587 let state = self.app.read(cx);
588 if state.mode.demo {
589 return crate::demo::read_message_ids(records);
590 }
591 let Some(engine) = state.engine.as_ref() else {
592 return Default::default();
593 };
594 records
595 .iter()
596 .filter(|record| {
597 matches!(
598 engine.receipt_state_for(record),
599 teams_core::ReceiptState::Read { .. }
600 )
601 })
602 .map(|record| record.message_id.clone())
603 .collect()
604 }
605
606 fn refresh_receipts(&mut self, cx: &mut Context<Self>) {
607 let state = self.app.read(cx);
608 let (Some(engine), Some(Selection::Chat(chat_id))) = (
609 state.engine.clone(),
610 self.current.as_ref().map(|c| c.selection.clone()),
611 ) else {
612 return;
613 };
614 drop(runtime::spawn(async move {
615 engine.refresh_receipts(&chat_id).await
616 }));
617 }
618
619 fn mark_read(&mut self, cx: &mut Context<Self>) {
620 let state = self.app.read(cx);
621 let (Some(engine), Some(Selection::Chat(chat_id))) = (
622 state.engine.clone(),
623 self.current.as_ref().map(|c| c.selection.clone()),
624 ) else {
625 return;
626 };
627 if state.mode.read_only || state.mode.demo {
628 return;
629 }
630 let unread = state
631 .sidebar
632 .chats
633 .iter()
634 .any(|chat| chat.id == chat_id && chat.unread);
635 if !unread {
636 return;
637 }
638 drop(runtime::spawn(
639 async move { engine.mark_read(&chat_id).await },
640 ));
641 }
642
643 fn request_older(&mut self, cx: &mut Context<Self>) {
644 let Some(engine) = self.app.read(cx).engine.clone() else {
645 return;
646 };
647 let Some(current) = self.current.as_mut() else {
648 return;
649 };
650 if current.loading_older || current.older_blocked || !current.has_older {
651 return;
652 }
653 current.loading_older = true;
654 let conversation_id = current.selection.conversation_id().to_owned();
655 let task_id = conversation_id.clone();
656 let receiver = runtime::spawn(async move { engine.load_older(&task_id).await });
657 cx.spawn(async move |this, cx| {
658 let result = receiver.await;
659 this.update(cx, |this, cx| {
660 this.finish_older(&conversation_id, result, cx)
661 })
662 .ok();
663 })
664 .detach();
665 }
666
667 fn finish_older(
668 &mut self,
669 conversation_id: &str,
670 result: Result<
671 teams_core::Result<Vec<MessageRecord>>,
672 tokio::sync::oneshot::error::RecvError,
673 >,
674 cx: &mut Context<Self>,
675 ) {
676 let Some(current) = self.current.as_mut() else {
677 return;
678 };
679 if current.selection.conversation_id() != conversation_id {
680 return;
681 }
682 current.loading_older = false;
683 match result {
684 Ok(Ok(records)) if !records.is_empty() => {
685 current.loaded_limit = current.loaded_count + records.len();
686 }
687 Ok(Ok(_)) => current.older_blocked = true,
688 Ok(Err(error)) => {
689 current.older_blocked = true;
690 self.notice = Some(format!(
691 "Could not load older messages: {}",
692 short_error(&error)
693 ));
694 }
695 Err(_) => current.older_blocked = true,
696 }
697 self.rebuild(false, cx);
698 }
699
700 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
701 if let Some(current) = self.current.as_mut() {
702 current.mode = ViewMode::Thread(root_id);
703 }
704 self.pending.clear();
705 self.rebuild(true, cx);
706 }
707
708 fn back_to_threads(&mut self, cx: &mut Context<Self>) {
709 if let Some(current) = self.current.as_mut() {
710 current.mode = ViewMode::ThreadList;
711 }
712 self.pending.clear();
713 self.rebuild(true, cx);
714 }
715
716 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
717 let state = self.app.read(cx);
718 let (mode, engine) = (state.mode, state.engine.clone());
719 let Some(current) = self.current.as_ref() else {
720 return;
721 };
722 let restore =
723 |this: &mut Self, message: &str, window: &mut Window, cx: &mut Context<Self>| {
724 this.notice = Some(message.to_owned());
725 this.composer
726 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
727 cx.notify();
728 };
729 if mode.read_only || mode.demo {
730 restore(self, "Read-only mode: nothing was sent", window, cx);
731 return;
732 }
733 let Some(engine) = engine else {
734 restore(self, "Not connected yet: nothing was sent", window, cx);
735 return;
736 };
737 let conversation_id = current.selection.conversation_id().to_owned();
738 let view_mode = current.mode.clone();
739 self.pending_counter += 1;
740 let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
741 let my_user_id = self.row_context(cx).my_user_id;
742 self.pending_outgoing.insert(key.clone(), outgoing.clone());
743 self.pending.push(MessageRow {
744 key: key.clone(),
745 author: "Du".to_owned(),
746 sender_id: my_user_id,
747 created_at: Utc::now(),
748 series: Series::default(),
749 card: false,
750 time: chrono::Local::now().format("%H:%M").to_string(),
751 day_header: None,
752 blocks: vec![Block::Paragraph(Inline::plain(&outgoing.text))],
753 edited: false,
754 deleted: false,
755 reactions: Vec::new(),
756 images: Vec::new(),
757 files: Vec::new(),
758 reply_count: None,
759 new_marker: false,
760 reply_faces: Vec::new(),
761 last_reply_time: None,
762 open_thread: None,
763 is_reply: false,
764 delivery: Delivery::Sending,
765 read: false,
766 own: true,
767 });
768 self.notice = None;
769 self.rebuild(false, cx);
770 self.scroller
771 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
772
773 let sent = outgoing.clone();
774 let receiver = runtime::spawn(async move {
775 let Outgoing {
776 text,
777 mentions,
778 reply,
779 } = &sent;
780 match (&view_mode, reply) {
781 (_, Some(reply)) => {
782 engine
783 .reply_to_with_mentions(&conversation_id, &reply.message_id, text, mentions)
784 .await
785 }
786 (ViewMode::Flat, None) => {
787 engine
788 .send_message_with_mentions(&conversation_id, text, None, mentions)
789 .await
790 }
791 (ViewMode::ThreadList, None) => {
792 engine
793 .post_to_channel_with_mentions(&conversation_id, text, None, mentions)
794 .await
795 }
796 (ViewMode::Thread(root_id), None) => {
797 engine
798 .send_message_with_mentions(&conversation_id, text, Some(root_id), mentions)
799 .await
800 }
801 }
802 .map(|_| ())
803 });
804 cx.spawn_in(window, async move |this, cx| {
805 let result = receiver.await;
806 this.update_in(cx, |this, window, cx| {
807 this.finish_send(&key, result, window, cx)
808 })
809 .ok();
810 })
811 .detach();
812 }
813
814 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
815 let Some(outgoing) = self.pending_outgoing.remove(key) else {
816 return;
817 };
818 self.pending.retain(|row| row.key != key);
819 self.send(outgoing, window, cx);
820 }
821
822 fn finish_send(
823 &mut self,
824 key: &str,
825 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
826 window: &mut Window,
827 cx: &mut Context<Self>,
828 ) {
829 let failure = match result {
830 Ok(Ok(())) => None,
831 Ok(Err(error)) => Some(short_error(&error)),
832 Err(error) => Some(short_error(&error)),
833 };
834 match failure {
835 None => {
836 self.pending.retain(|row| row.key != key);
837 self.pending_outgoing.remove(key);
838 }
839 Some(error) => {
840 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
841 row.delivery = Delivery::Failed(error.clone());
842 }
843 self.notice = Some(format!("Not sent: {error}"));
844 if self.composer.read(cx).is_empty(cx)
845 && let Some(outgoing) = self.pending_outgoing.get(key).cloned()
846 {
847 self.composer
848 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
849 }
850 }
851 }
852 self.rebuild(false, cx);
853 }
854
855 fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement {
856 let app = self.app.read(cx);
857 let directory = &app.directory;
858 let me = directory.me.as_ref();
859 let mut lead: Option<AnyElement> = None;
860 let mut subline = String::new();
861 let mut stack: Option<Div> = None;
862 match &current.selection {
863 Selection::Chat(chat_id) => {
864 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
865 let faces = others(chat, me);
866 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
867 let first = faces.first().cloned().map(face);
868 if is_one_on_one(chat) || faces.len() < 2 {
869 let name = first
870 .as_ref()
871 .map_or(current.title.as_str(), |face| face.name.as_str());
872 let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
873 let avatar = person_avatar(directory, user_id, name, 36.);
874 let presence = user_id.map(|id| directory.presence_of(id));
875 lead = Some(match presence {
876 Some(kind) => with_presence(avatar, kind, 36., theme::background())
877 .into_any_element(),
878 None => avatar,
879 });
880 subline = presence
881 .map(|kind| kind.label().to_owned())
882 .unwrap_or_default();
883 } else {
884 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
885 lead = Some(spec_avatar(directory, &pair, 36., theme::background()));
886 subline = format!("{} Teilnehmer", chat.members.len());
887 let shown: Vec<Face> = faces.iter().cloned().map(face).collect();
888 stack = Some(member_stack(directory, &shown, shown.len()));
889 }
890 }
891 }
892 Selection::Channel(channel_id) => {
893 let team = app.sidebar.teams.iter().find(|entry| {
894 entry
895 .channels
896 .iter()
897 .any(|channel| &channel.id == channel_id)
898 });
899 let (name, key) = team
900 .map_or((current.title.as_str(), current.title.as_str()), |entry| {
901 (entry.team.name.as_str(), entry.team.id.as_str())
902 });
903 lead = Some(square_avatar(name, key, 36., 9.).into_any_element());
904 }
905 }
906 let mut header = h_flex()
907 .w_full()
908 .h(px(60.))
909 .flex_none()
910 .px(px(20.))
911 .gap(px(12.))
912 .items_center()
913 .border_b_1()
914 .border_color(theme::border());
915 if matches!(current.mode, ViewMode::Thread(_)) {
916 header = header.child(
917 Button::new("back-to-threads")
918 .ghost()
919 .compact()
920 .label("Threads")
921 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx))),
922 );
923 }
924 let channel_note = match current.mode {
925 ViewMode::Flat => None,
926 ViewMode::ThreadList => Some("Threads"),
927 ViewMode::Thread(_) => Some("Thread"),
928 };
929 if let Some(note) = channel_note {
930 subline = note.to_owned();
931 }
932 header
933 .children(lead)
934 .child(
935 v_flex()
936 .flex_1()
937 .min_w_0()
938 .overflow_hidden()
939 .gap(px(1.))
940 .child(
941 div()
942 .truncate()
943 .text_size(px(15.))
944 .font_weight(FontWeight::SEMIBOLD)
945 .text_color(theme::text())
946 .child(current.title.clone()),
947 )
948 .when(!subline.is_empty(), |column| {
949 column.child(
950 div()
951 .text_size(px(12.))
952 .text_color(theme::text_muted())
953 .child(subline),
954 )
955 }),
956 )
957 .children(stack)
958 }
959}
960
961impl Render for ConversationView {
962 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
963 let background = theme::background();
964 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
965 let Some(current) = self.current.as_ref() else {
966 return root
967 .items_center()
968 .justify_center()
969 .text_color(theme::text_muted())
970 .child("Chat oder Channel auswählen")
971 .into_any_element();
972 };
973 let rows = self.rows.clone();
974 let view = cx.weak_entity();
975 let app = self.app.clone();
976 let highlighted = self.highlighted_message.clone();
977 let scroller = MessageScroller::new(
978 "messages",
979 self.scroller.clone(),
980 move |index, window, cx| {
981 let rows = rows.borrow();
982 match rows.get(index) {
983 Some(Row::Message(message)) => {
984 let open_thread = message.open_thread.clone().map(|root_id| {
985 let view = view.clone();
986 Box::new(move |cx: &mut App| {
987 let root_id = root_id.clone();
988 view.update(cx, |this, cx| this.open_thread(root_id, cx))
989 .ok();
990 }) as Box<dyn Fn(&mut App)>
991 });
992 let retry = matches!(message.delivery, Delivery::Failed(_)).then(|| {
993 let (view, key, handle) =
994 (view.clone(), message.key.clone(), window.window_handle());
995 Box::new(move |cx: &mut App| {
996 let (view, key) = (view.clone(), key.clone());
997 handle
998 .update(cx, move |_, window, cx| {
999 view.update(cx, |this, cx| this.retry(&key, window, cx))
1000 .ok();
1001 })
1002 .ok();
1003 }) as Box<dyn Fn(&mut App)>
1004 });
1005 let sender = (!message.own && !message.series.has_prev)
1006 .then(|| message.sender_id.clone())
1007 .flatten()
1008 .filter(|sender| app.read(cx).directory.avatar(sender).is_none());
1009 if let Some(sender) = sender {
1010 let app = app.clone();
1011 cx.defer(move |cx| {
1012 app.update(cx, |state, cx| state.request_avatars(vec![sender], cx));
1013 });
1014 }
1015 let missing_images: Vec<ImageRef> = message
1016 .images
1017 .iter()
1018 .filter(|image| app.read(cx).directory.image(&image.url).is_none())
1019 .cloned()
1020 .collect();
1021 if !missing_images.is_empty() {
1022 let app = app.clone();
1023 cx.defer(move |cx| {
1024 app.update(cx, |state, cx| {
1025 state.request_images(missing_images, cx)
1026 });
1027 });
1028 }
1029 let is_real = !message.key.starts_with(PENDING_KEY_PREFIX);
1030 let hovered = is_real.then(|| {
1031 let (view, key) = (view.clone(), message.key.clone());
1032 Box::new(move |cx: &mut App| {
1033 view.update(cx, |this, _| {
1034 this.hovered_message = Some(key.clone());
1035 })
1036 .ok();
1037 }) as Box<dyn Fn(&mut App)>
1038 });
1039 let reply = (is_real && !message.deleted).then(|| {
1040 let (view, key, handle) =
1041 (view.clone(), message.key.clone(), window.window_handle());
1042 Box::new(move |cx: &mut App| {
1043 let (view, key) = (view.clone(), key.clone());
1044 handle
1045 .update(cx, move |_, window, cx| {
1046 view.update(cx, |this, cx| {
1047 this.begin_reply(&key, window, cx)
1048 })
1049 .ok();
1050 })
1051 .ok();
1052 }) as Box<dyn Fn(&mut App)>
1053 });
1054 let state = app.read(cx);
1055 render_message_row(
1056 message,
1057 index,
1058 RowActions {
1059 open_thread,
1060 retry,
1061 reply,
1062 hovered,
1063 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
1064 },
1065 &state.directory,
1066 cx,
1067 )
1068 }
1069 Some(Row::LoadOlder) => {
1070 let view = view.clone();
1071 cx.defer(move |cx| {
1072 view.update(cx, |this, cx| this.request_older(cx)).ok();
1073 });
1074 h_flex()
1075 .w_full()
1076 .py_2()
1077 .gap(px(6.))
1078 .justify_center()
1079 .text_size(px(12.))
1080 .text_color(theme::text_muted())
1081 .child(icon(IconName::Loader, 12., theme::text_muted()))
1082 .child("Ältere Nachrichten werden geladen")
1083 .into_any_element()
1084 }
1085 Some(Row::Start(start)) => {
1086 let state = app.read(cx);
1087 v_flex()
1088 .w_full()
1089 .items_center()
1090 .gap(px(8.))
1091 .pt(px(32.))
1092 .pb(px(16.))
1093 .child(person_avatar(
1094 &state.directory,
1095 start.user_id.as_deref(),
1096 &start.title,
1097 56.,
1098 ))
1099 .child(
1100 div()
1101 .text_size(px(16.))
1102 .font_weight(FontWeight::SEMIBOLD)
1103 .text_color(theme::text())
1104 .child(start.title.clone()),
1105 )
1106 .child(
1107 div()
1108 .text_size(px(12.))
1109 .text_color(theme::text_muted())
1110 .child("Das ist der Anfang der Unterhaltung"),
1111 )
1112 .into_any_element()
1113 }
1114 None => div().into_any_element(),
1115 }
1116 },
1117 )
1118 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
1119 .with_bottom_fade(background);
1120
1121 root = root.child(self.render_header(current, cx));
1122 if let Some(notice) = &self.notice {
1123 root = root.child(
1124 div()
1125 .px_4()
1126 .py_1()
1127 .text_xs()
1128 .bg(theme::amber().opacity(0.15))
1129 .text_color(theme::amber())
1130 .child(notice.clone()),
1131 );
1132 }
1133 let empty_channel = current.mode == ViewMode::ThreadList && self.rows.borrow().is_empty();
1134 let body = if empty_channel {
1135 div()
1136 .size_full()
1137 .flex()
1138 .items_center()
1139 .justify_center()
1140 .text_size(px(13.))
1141 .text_color(theme::text_muted())
1142 .child("Noch keine Beiträge in diesem Channel")
1143 .into_any_element()
1144 } else {
1145 scroller.into_any_element()
1146 };
1147 root.child(div().flex_1().min_h_0().child(body))
1148 .child(self.composer.clone())
1149 .into_any_element()
1150 }
1151}