1use crate::{collab_panel, ChatPanelSettings};
2use anyhow::Result;
3use call::{room, ActiveCall};
4use channel::{ChannelChat, ChannelChatEvent, ChannelMessage, ChannelMessageId, ChannelStore};
5use client::Client;
6use collections::HashMap;
7use db::kvp::KEY_VALUE_STORE;
8use editor::Editor;
9use gpui::{
10 actions, div, list, prelude::*, px, Action, AppContext, AsyncWindowContext, CursorStyle,
11 DismissEvent, ElementId, EventEmitter, FocusHandle, FocusableView, FontStyle, FontWeight,
12 HighlightStyle, ListOffset, ListScrollEvent, ListState, Model, Render, StyledText,
13 Subscription, Task, View, ViewContext, VisualContext, WeakView,
14};
15use language::LanguageRegistry;
16use menu::Confirm;
17use message_editor::MessageEditor;
18use project::Fs;
19use rich_text::RichText;
20use serde::{Deserialize, Serialize};
21use settings::Settings;
22use std::{sync::Arc, time::Duration};
23use time::{OffsetDateTime, UtcOffset};
24use ui::{
25 popover_menu, prelude::*, Avatar, Button, ContextMenu, IconButton, IconName, KeyBinding, Label,
26 TabBar, Tooltip,
27};
28use util::{ResultExt, TryFutureExt};
29use workspace::{
30 dock::{DockPosition, Panel, PanelEvent},
31 Workspace,
32};
33
34mod message_editor;
35
36const MESSAGE_LOADING_THRESHOLD: usize = 50;
37const CHAT_PANEL_KEY: &'static str = "ChatPanel";
38
39pub fn init(cx: &mut AppContext) {
40 cx.observe_new_views(|workspace: &mut Workspace, _| {
41 workspace.register_action(|workspace, _: &ToggleFocus, cx| {
42 workspace.toggle_panel_focus::<ChatPanel>(cx);
43 });
44 })
45 .detach();
46}
47
48pub struct ChatPanel {
49 client: Arc<Client>,
50 channel_store: Model<ChannelStore>,
51 languages: Arc<LanguageRegistry>,
52 message_list: ListState,
53 active_chat: Option<(Model<ChannelChat>, Subscription)>,
54 message_editor: View<MessageEditor>,
55 local_timezone: UtcOffset,
56 fs: Arc<dyn Fs>,
57 width: Option<Pixels>,
58 active: bool,
59 pending_serialization: Task<Option<()>>,
60 subscriptions: Vec<gpui::Subscription>,
61 is_scrolled_to_bottom: bool,
62 markdown_data: HashMap<ChannelMessageId, RichText>,
63 focus_handle: FocusHandle,
64 open_context_menu: Option<(u64, Subscription)>,
65 highlighted_message: Option<(u64, Task<()>)>,
66}
67
68#[derive(Serialize, Deserialize)]
69struct SerializedChatPanel {
70 width: Option<Pixels>,
71}
72
73actions!(chat_panel, [ToggleFocus, CloseReplyPreview]);
74
75impl ChatPanel {
76 pub fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> View<Self> {
77 let fs = workspace.app_state().fs.clone();
78 let client = workspace.app_state().client.clone();
79 let channel_store = ChannelStore::global(cx);
80 let languages = workspace.app_state().languages.clone();
81
82 let input_editor = cx.new_view(|cx| {
83 MessageEditor::new(
84 languages.clone(),
85 channel_store.clone(),
86 cx.new_view(|cx| Editor::auto_height(4, cx)),
87 cx,
88 )
89 });
90
91 cx.new_view(|cx: &mut ViewContext<Self>| {
92 let view = cx.view().downgrade();
93 let message_list =
94 ListState::new(0, gpui::ListAlignment::Bottom, px(1000.), move |ix, cx| {
95 if let Some(view) = view.upgrade() {
96 view.update(cx, |view, cx| {
97 view.render_message(ix, cx).into_any_element()
98 })
99 } else {
100 div().into_any()
101 }
102 });
103
104 message_list.set_scroll_handler(cx.listener(|this, event: &ListScrollEvent, cx| {
105 if event.visible_range.start < MESSAGE_LOADING_THRESHOLD {
106 this.load_more_messages(cx);
107 }
108 this.is_scrolled_to_bottom = !event.is_scrolled;
109 }));
110
111 let mut this = Self {
112 fs,
113 client,
114 channel_store,
115 languages,
116 message_list,
117 active_chat: Default::default(),
118 pending_serialization: Task::ready(None),
119 message_editor: input_editor,
120 local_timezone: cx.local_timezone(),
121 subscriptions: Vec::new(),
122 is_scrolled_to_bottom: true,
123 active: false,
124 width: None,
125 markdown_data: Default::default(),
126 focus_handle: cx.focus_handle(),
127 open_context_menu: None,
128 highlighted_message: None,
129 };
130
131 if let Some(channel_id) = ActiveCall::global(cx)
132 .read(cx)
133 .room()
134 .and_then(|room| room.read(cx).channel_id())
135 {
136 this.select_channel(channel_id, None, cx)
137 .detach_and_log_err(cx);
138 }
139
140 this.subscriptions.push(cx.subscribe(
141 &ActiveCall::global(cx),
142 move |this: &mut Self, call, event: &room::Event, cx| match event {
143 room::Event::RoomJoined { channel_id } => {
144 if let Some(channel_id) = channel_id {
145 this.select_channel(*channel_id, None, cx)
146 .detach_and_log_err(cx);
147
148 if call
149 .read(cx)
150 .room()
151 .is_some_and(|room| room.read(cx).contains_guests())
152 {
153 cx.emit(PanelEvent::Activate)
154 }
155 }
156 }
157 room::Event::Left { channel_id } => {
158 if channel_id == &this.channel_id(cx) {
159 cx.emit(PanelEvent::Close)
160 }
161 }
162 _ => {}
163 },
164 ));
165
166 this
167 })
168 }
169
170 pub fn channel_id(&self, cx: &AppContext) -> Option<u64> {
171 self.active_chat
172 .as_ref()
173 .map(|(chat, _)| chat.read(cx).channel_id)
174 }
175
176 pub fn is_scrolled_to_bottom(&self) -> bool {
177 self.is_scrolled_to_bottom
178 }
179
180 pub fn active_chat(&self) -> Option<Model<ChannelChat>> {
181 self.active_chat.as_ref().map(|(chat, _)| chat.clone())
182 }
183
184 pub fn load(
185 workspace: WeakView<Workspace>,
186 cx: AsyncWindowContext,
187 ) -> Task<Result<View<Self>>> {
188 cx.spawn(|mut cx| async move {
189 let serialized_panel = if let Some(panel) = cx
190 .background_executor()
191 .spawn(async move { KEY_VALUE_STORE.read_kvp(CHAT_PANEL_KEY) })
192 .await
193 .log_err()
194 .flatten()
195 {
196 Some(serde_json::from_str::<SerializedChatPanel>(&panel)?)
197 } else {
198 None
199 };
200
201 workspace.update(&mut cx, |workspace, cx| {
202 let panel = Self::new(workspace, cx);
203 if let Some(serialized_panel) = serialized_panel {
204 panel.update(cx, |panel, cx| {
205 panel.width = serialized_panel.width;
206 cx.notify();
207 });
208 }
209 panel
210 })
211 })
212 }
213
214 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
215 let width = self.width;
216 self.pending_serialization = cx.background_executor().spawn(
217 async move {
218 KEY_VALUE_STORE
219 .write_kvp(
220 CHAT_PANEL_KEY.into(),
221 serde_json::to_string(&SerializedChatPanel { width })?,
222 )
223 .await?;
224 anyhow::Ok(())
225 }
226 .log_err(),
227 );
228 }
229
230 fn set_active_chat(&mut self, chat: Model<ChannelChat>, cx: &mut ViewContext<Self>) {
231 if self.active_chat.as_ref().map(|e| &e.0) != Some(&chat) {
232 let channel_id = chat.read(cx).channel_id;
233 {
234 self.markdown_data.clear();
235 let chat = chat.read(cx);
236 self.message_list.reset(chat.message_count());
237
238 let channel_name = chat.channel(cx).map(|channel| channel.name.clone());
239 self.message_editor.update(cx, |editor, cx| {
240 editor.set_channel(channel_id, channel_name, cx);
241 editor.clear_reply_to_message_id();
242 });
243 };
244 let subscription = cx.subscribe(&chat, Self::channel_did_change);
245 self.active_chat = Some((chat, subscription));
246 self.acknowledge_last_message(cx);
247 cx.notify();
248 }
249 }
250
251 fn channel_did_change(
252 &mut self,
253 _: Model<ChannelChat>,
254 event: &ChannelChatEvent,
255 cx: &mut ViewContext<Self>,
256 ) {
257 match event {
258 ChannelChatEvent::MessagesUpdated {
259 old_range,
260 new_count,
261 } => {
262 self.message_list.splice(old_range.clone(), *new_count);
263 if self.active {
264 self.acknowledge_last_message(cx);
265 }
266 }
267 ChannelChatEvent::NewMessage {
268 channel_id,
269 message_id,
270 } => {
271 if !self.active {
272 self.channel_store.update(cx, |store, cx| {
273 store.update_latest_message_id(*channel_id, *message_id, cx)
274 })
275 }
276 }
277 }
278 cx.notify();
279 }
280
281 fn acknowledge_last_message(&mut self, cx: &mut ViewContext<Self>) {
282 if self.active && self.is_scrolled_to_bottom {
283 if let Some((chat, _)) = &self.active_chat {
284 chat.update(cx, |chat, cx| {
285 chat.acknowledge_last_message(cx);
286 });
287 }
288 }
289 }
290
291 fn render_replied_to_message(
292 &mut self,
293 message_id: Option<ChannelMessageId>,
294 reply_to_message: &ChannelMessage,
295 cx: &mut ViewContext<Self>,
296 ) -> impl IntoElement {
297 let body_element_id: ElementId = match message_id {
298 Some(ChannelMessageId::Saved(id)) => ("reply-to-saved-message", id).into(),
299 Some(ChannelMessageId::Pending(id)) => ("reply-to-pending-message", id).into(), // This should never happen
300 None => ("composing-reply").into(),
301 };
302
303 let message_element_id: ElementId = match message_id {
304 Some(ChannelMessageId::Saved(id)) => ("reply-to-saved-message-container", id).into(),
305 Some(ChannelMessageId::Pending(id)) => {
306 ("reply-to-pending-message-container", id).into()
307 } // This should never happen
308 None => ("composing-reply-container").into(),
309 };
310
311 let current_channel_id = self.channel_id(cx);
312 let reply_to_message_id = reply_to_message.id;
313
314 let reply_to_message_body = self
315 .markdown_data
316 .entry(reply_to_message.id)
317 .or_insert_with(|| {
318 Self::render_markdown_with_mentions(
319 &self.languages,
320 self.client.id(),
321 reply_to_message,
322 )
323 });
324
325 const REPLY_TO_PREFIX: &str = "Reply to @";
326
327 div().flex_grow().child(
328 v_flex()
329 .id(message_element_id)
330 .text_ui_xs()
331 .child(
332 h_flex()
333 .gap_x_1()
334 .items_center()
335 .justify_start()
336 .overflow_x_hidden()
337 .whitespace_nowrap()
338 .child(
339 StyledText::new(format!(
340 "{}{}",
341 REPLY_TO_PREFIX,
342 reply_to_message.sender.github_login.clone()
343 ))
344 .with_highlights(
345 &cx.text_style(),
346 vec![(
347 (REPLY_TO_PREFIX.len() - 1)
348 ..(reply_to_message.sender.github_login.len()
349 + REPLY_TO_PREFIX.len()),
350 HighlightStyle {
351 font_weight: Some(FontWeight::BOLD),
352 ..Default::default()
353 },
354 )],
355 ),
356 ),
357 )
358 .child(
359 div()
360 .border_l_2()
361 .border_color(cx.theme().colors().border)
362 .px_1()
363 .py_0p5()
364 .mb_1()
365 .overflow_hidden()
366 .child(
367 div()
368 .max_h_12()
369 .child(reply_to_message_body.element(body_element_id, cx)),
370 ),
371 )
372 .cursor(CursorStyle::PointingHand)
373 .tooltip(|cx| Tooltip::text("Go to message", cx))
374 .on_click(cx.listener(move |chat_panel, _, cx| {
375 if let Some(channel_id) = current_channel_id {
376 chat_panel
377 .select_channel(channel_id, reply_to_message_id.into(), cx)
378 .detach_and_log_err(cx)
379 }
380 })),
381 )
382 }
383
384 fn render_message(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> impl IntoElement {
385 let active_chat = &self.active_chat.as_ref().unwrap().0;
386 let (message, is_continuation_from_previous, is_admin) =
387 active_chat.update(cx, |active_chat, cx| {
388 let is_admin = self
389 .channel_store
390 .read(cx)
391 .is_channel_admin(active_chat.channel_id);
392
393 let last_message = active_chat.message(ix.saturating_sub(1));
394 let this_message = active_chat.message(ix).clone();
395
396 let duration_since_last_message = this_message.timestamp - last_message.timestamp;
397 let is_continuation_from_previous = last_message.sender.id
398 == this_message.sender.id
399 && last_message.id != this_message.id
400 && duration_since_last_message < Duration::from_secs(5 * 60);
401
402 if let ChannelMessageId::Saved(id) = this_message.id {
403 if this_message
404 .mentions
405 .iter()
406 .any(|(_, user_id)| Some(*user_id) == self.client.user_id())
407 {
408 active_chat.acknowledge_message(id);
409 }
410 }
411
412 (this_message, is_continuation_from_previous, is_admin)
413 });
414
415 let _is_pending = message.is_pending();
416
417 let belongs_to_user = Some(message.sender.id) == self.client.user_id();
418 let can_delete_message = belongs_to_user || is_admin;
419
420 let element_id: ElementId = match message.id {
421 ChannelMessageId::Saved(id) => ("saved-message", id).into(),
422 ChannelMessageId::Pending(id) => ("pending-message", id).into(),
423 };
424 let this = cx.view().clone();
425
426 let mentioning_you = message
427 .mentions
428 .iter()
429 .any(|m| Some(m.1) == self.client.user_id());
430
431 let message_id = match message.id {
432 ChannelMessageId::Saved(id) => Some(id),
433 ChannelMessageId::Pending(_) => None,
434 };
435
436 let reply_to_message = message
437 .reply_to_message_id
438 .map(|id| active_chat.read(cx).find_loaded_message(id))
439 .flatten()
440 .cloned();
441
442 let replied_to_you =
443 reply_to_message.as_ref().map(|m| m.sender.id) == self.client.user_id();
444
445 let is_highlighted_message = self
446 .highlighted_message
447 .as_ref()
448 .is_some_and(|(id, _)| Some(id) == message_id.as_ref());
449 let background = if is_highlighted_message {
450 cx.theme().status().info_background
451 } else if mentioning_you || replied_to_you {
452 cx.theme().colors().background
453 } else {
454 cx.theme().colors().panel_background
455 };
456
457 v_flex().w_full().relative().child(
458 div()
459 .bg(background)
460 .rounded_md()
461 .overflow_hidden()
462 .px_1()
463 .py_0p5()
464 .when(!is_continuation_from_previous, |this| {
465 this.mt_2().child(
466 h_flex()
467 .text_ui_sm()
468 .child(div().absolute().child(
469 Avatar::new(message.sender.avatar_uri.clone()).size(rems(1.)),
470 ))
471 .child(
472 div()
473 .pl(cx.rem_size() + px(6.0))
474 .pr(px(8.0))
475 .font_weight(FontWeight::BOLD)
476 .child(Label::new(message.sender.github_login.clone())),
477 )
478 .child(
479 Label::new(format_timestamp(
480 OffsetDateTime::now_utc(),
481 message.timestamp,
482 self.local_timezone,
483 ))
484 .size(LabelSize::Small)
485 .color(Color::Muted),
486 ),
487 )
488 })
489 .when(
490 message.reply_to_message_id.is_some() && reply_to_message.is_none(),
491 |this| {
492 const MESSAGE_DELETED: &str = "Message has been deleted";
493
494 let body_text = StyledText::new(MESSAGE_DELETED).with_highlights(
495 &cx.text_style(),
496 vec![(
497 0..MESSAGE_DELETED.len(),
498 HighlightStyle {
499 font_style: Some(FontStyle::Italic),
500 ..Default::default()
501 },
502 )],
503 );
504
505 this.child(
506 div()
507 .border_l_2()
508 .text_ui_xs()
509 .border_color(cx.theme().colors().border)
510 .px_1()
511 .py_0p5()
512 .child(body_text),
513 )
514 },
515 )
516 .when_some(reply_to_message, |el, reply_to_message| {
517 el.child(self.render_replied_to_message(
518 Some(message.id),
519 &reply_to_message,
520 cx,
521 ))
522 })
523 .when(mentioning_you || replied_to_you, |this| this.my_0p5())
524 .map(|el| {
525 let text = self.markdown_data.entry(message.id).or_insert_with(|| {
526 Self::render_markdown_with_mentions(
527 &self.languages,
528 self.client.id(),
529 &message,
530 )
531 });
532 el.child(
533 v_flex()
534 .w_full()
535 .text_ui_sm()
536 .id(element_id)
537 .group("")
538 .child(text.element("body".into(), cx))
539 .child(
540 div()
541 .absolute()
542 .z_index(1)
543 .right_0()
544 .w_6()
545 .bg(background)
546 .when(!self.has_open_menu(message_id), |el| {
547 el.visible_on_hover("")
548 })
549 .when_some(message_id, |el, message_id| {
550 el.child(
551 popover_menu(("menu", message_id))
552 .trigger(IconButton::new(
553 ("trigger", message_id),
554 IconName::Ellipsis,
555 ))
556 .menu(move |cx| {
557 Some(Self::render_message_menu(
558 &this,
559 message_id,
560 can_delete_message,
561 cx,
562 ))
563 }),
564 )
565 }),
566 ),
567 )
568 }),
569 )
570 }
571
572 fn has_open_menu(&self, message_id: Option<u64>) -> bool {
573 match self.open_context_menu.as_ref() {
574 Some((id, _)) => Some(*id) == message_id,
575 None => false,
576 }
577 }
578
579 fn render_message_menu(
580 this: &View<Self>,
581 message_id: u64,
582 can_delete_message: bool,
583 cx: &mut WindowContext,
584 ) -> View<ContextMenu> {
585 let menu = {
586 ContextMenu::build(cx, move |menu, cx| {
587 menu.entry(
588 "Reply to message",
589 None,
590 cx.handler_for(&this, move |this, cx| {
591 this.message_editor.update(cx, |editor, cx| {
592 editor.set_reply_to_message_id(message_id);
593 editor.focus_handle(cx).focus(cx);
594 })
595 }),
596 )
597 .when(can_delete_message, move |menu| {
598 menu.entry(
599 "Delete message",
600 None,
601 cx.handler_for(&this, move |this, cx| this.remove_message(message_id, cx)),
602 )
603 })
604 })
605 };
606 this.update(cx, |this, cx| {
607 let subscription = cx.subscribe(&menu, |this: &mut Self, _, _: &DismissEvent, _| {
608 this.open_context_menu = None;
609 });
610 this.open_context_menu = Some((message_id, subscription));
611 });
612 menu
613 }
614
615 fn render_markdown_with_mentions(
616 language_registry: &Arc<LanguageRegistry>,
617 current_user_id: u64,
618 message: &channel::ChannelMessage,
619 ) -> RichText {
620 let mentions = message
621 .mentions
622 .iter()
623 .map(|(range, user_id)| rich_text::Mention {
624 range: range.clone(),
625 is_self_mention: *user_id == current_user_id,
626 })
627 .collect::<Vec<_>>();
628
629 rich_text::render_rich_text(message.body.clone(), &mentions, language_registry, None)
630 }
631
632 fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
633 if let Some((chat, _)) = self.active_chat.as_ref() {
634 let message = self
635 .message_editor
636 .update(cx, |editor, cx| editor.take_message(cx));
637
638 if let Some(task) = chat
639 .update(cx, |chat, cx| chat.send_message(message, cx))
640 .log_err()
641 {
642 task.detach();
643 }
644 }
645 }
646
647 fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
648 if let Some((chat, _)) = self.active_chat.as_ref() {
649 chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
650 }
651 }
652
653 fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
654 if let Some((chat, _)) = self.active_chat.as_ref() {
655 chat.update(cx, |channel, cx| {
656 if let Some(task) = channel.load_more_messages(cx) {
657 task.detach();
658 }
659 })
660 }
661 }
662
663 pub fn select_channel(
664 &mut self,
665 selected_channel_id: u64,
666 scroll_to_message_id: Option<u64>,
667 cx: &mut ViewContext<ChatPanel>,
668 ) -> Task<Result<()>> {
669 let open_chat = self
670 .active_chat
671 .as_ref()
672 .and_then(|(chat, _)| {
673 (chat.read(cx).channel_id == selected_channel_id)
674 .then(|| Task::ready(anyhow::Ok(chat.clone())))
675 })
676 .unwrap_or_else(|| {
677 self.channel_store.update(cx, |store, cx| {
678 store.open_channel_chat(selected_channel_id, cx)
679 })
680 });
681
682 cx.spawn(|this, mut cx| async move {
683 let chat = open_chat.await?;
684 this.update(&mut cx, |this, cx| {
685 this.set_active_chat(chat.clone(), cx);
686 })?;
687
688 if let Some(message_id) = scroll_to_message_id {
689 if let Some(item_ix) =
690 ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
691 .await
692 {
693 let task = cx.spawn({
694 let this = this.clone();
695
696 |mut cx| async move {
697 cx.background_executor().timer(Duration::from_secs(2)).await;
698 this.update(&mut cx, |this, cx| {
699 this.highlighted_message.take();
700 cx.notify();
701 })
702 .ok();
703 }
704 });
705
706 this.update(&mut cx, |this, cx| {
707 this.highlighted_message = Some((message_id, task));
708 if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
709 this.message_list.scroll_to(ListOffset {
710 item_ix,
711 offset_in_item: px(0.0),
712 });
713 cx.notify();
714 }
715 })?;
716 }
717 }
718
719 Ok(())
720 })
721 }
722
723 fn close_reply_preview(&mut self, _: &CloseReplyPreview, cx: &mut ViewContext<Self>) {
724 self.message_editor
725 .update(cx, |editor, _| editor.clear_reply_to_message_id());
726 }
727}
728
729impl Render for ChatPanel {
730 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
731 let reply_to_message_id = self.message_editor.read(cx).reply_to_message_id();
732
733 v_flex()
734 .key_context("ChatPanel")
735 .track_focus(&self.focus_handle)
736 .full()
737 .on_action(cx.listener(Self::send))
738 .child(
739 h_flex().z_index(1).child(
740 TabBar::new("chat_header").child(
741 h_flex()
742 .w_full()
743 .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
744 .px_2()
745 .child(Label::new(
746 self.active_chat
747 .as_ref()
748 .and_then(|c| {
749 Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
750 })
751 .unwrap_or("Chat".to_string()),
752 )),
753 ),
754 ),
755 )
756 .child(div().flex_grow().px_2().map(|this| {
757 if self.active_chat.is_some() {
758 this.child(list(self.message_list.clone()).full())
759 } else {
760 this.child(
761 div()
762 .full()
763 .p_4()
764 .child(
765 Label::new("Select a channel to chat in.")
766 .size(LabelSize::Small)
767 .color(Color::Muted),
768 )
769 .child(
770 div().pt_1().w_full().items_center().child(
771 Button::new("toggle-collab", "Open")
772 .full_width()
773 .key_binding(KeyBinding::for_action(
774 &collab_panel::ToggleFocus,
775 cx,
776 ))
777 .on_click(|_, cx| {
778 cx.dispatch_action(
779 collab_panel::ToggleFocus.boxed_clone(),
780 )
781 }),
782 ),
783 ),
784 )
785 }
786 }))
787 .when_some(reply_to_message_id, |el, reply_to_message_id| {
788 let reply_message = self
789 .active_chat()
790 .map(|active_chat| {
791 active_chat.read(cx).messages().iter().find_map(|m| {
792 if m.id == ChannelMessageId::Saved(reply_to_message_id) {
793 Some(m)
794 } else {
795 None
796 }
797 })
798 })
799 .flatten()
800 .cloned();
801
802 el.when_some(reply_message, |el, reply_message| {
803 el.child(
804 div()
805 .when(!self.is_scrolled_to_bottom, |el| {
806 el.border_t_1().border_color(cx.theme().colors().border)
807 })
808 .flex()
809 .w_full()
810 .items_start()
811 .overflow_hidden()
812 .py_1()
813 .px_2()
814 .bg(cx.theme().colors().background)
815 .child(self.render_replied_to_message(None, &reply_message, cx))
816 .child(
817 IconButton::new("close-reply-preview", IconName::Close)
818 .shape(ui::IconButtonShape::Square)
819 .tooltip(|cx| {
820 Tooltip::for_action(
821 "Close reply preview",
822 &CloseReplyPreview,
823 cx,
824 )
825 })
826 .on_click(cx.listener(move |_, _, cx| {
827 cx.dispatch_action(CloseReplyPreview.boxed_clone())
828 })),
829 ),
830 )
831 })
832 })
833 .children(
834 Some(
835 h_flex()
836 .key_context("MessageEditor")
837 .on_action(cx.listener(ChatPanel::close_reply_preview))
838 .when(
839 !self.is_scrolled_to_bottom && reply_to_message_id.is_none(),
840 |el| el.border_t_1().border_color(cx.theme().colors().border),
841 )
842 .p_2()
843 .map(|el| el.child(self.message_editor.clone())),
844 )
845 .filter(|_| self.active_chat.is_some()),
846 )
847 .into_any()
848 }
849}
850
851impl FocusableView for ChatPanel {
852 fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
853 if self.active_chat.is_some() {
854 self.message_editor.read(cx).focus_handle(cx)
855 } else {
856 self.focus_handle.clone()
857 }
858 }
859}
860
861impl Panel for ChatPanel {
862 fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
863 ChatPanelSettings::get_global(cx).dock
864 }
865
866 fn position_is_valid(&self, position: DockPosition) -> bool {
867 matches!(position, DockPosition::Left | DockPosition::Right)
868 }
869
870 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
871 settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
872 settings.dock = Some(position)
873 });
874 }
875
876 fn size(&self, cx: &gpui::WindowContext) -> Pixels {
877 self.width
878 .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
879 }
880
881 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
882 self.width = size;
883 self.serialize(cx);
884 cx.notify();
885 }
886
887 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
888 self.active = active;
889 if active {
890 self.acknowledge_last_message(cx);
891 }
892 }
893
894 fn persistent_name() -> &'static str {
895 "ChatPanel"
896 }
897
898 fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
899 Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
900 }
901
902 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
903 Some("Chat Panel")
904 }
905
906 fn toggle_action(&self) -> Box<dyn gpui::Action> {
907 Box::new(ToggleFocus)
908 }
909
910 fn starts_open(&self, cx: &WindowContext) -> bool {
911 ActiveCall::global(cx)
912 .read(cx)
913 .room()
914 .is_some_and(|room| room.read(cx).contains_guests())
915 }
916}
917
918impl EventEmitter<PanelEvent> for ChatPanel {}
919
920fn format_timestamp(
921 reference: OffsetDateTime,
922 timestamp: OffsetDateTime,
923 timezone: UtcOffset,
924) -> String {
925 let timestamp_local = timestamp.to_offset(timezone);
926 let timestamp_local_hour = timestamp_local.hour();
927
928 let hour_12 = match timestamp_local_hour {
929 0 => 12, // Midnight
930 13..=23 => timestamp_local_hour - 12, // PM hours
931 _ => timestamp_local_hour, // AM hours
932 };
933 let meridiem = if timestamp_local_hour >= 12 {
934 "pm"
935 } else {
936 "am"
937 };
938 let timestamp_local_minute = timestamp_local.minute();
939 let formatted_time = format!("{:02}:{:02} {}", hour_12, timestamp_local_minute, meridiem);
940
941 let reference_local = reference.to_offset(timezone);
942 let reference_local_date = reference_local.date();
943 let timestamp_local_date = timestamp_local.date();
944
945 if timestamp_local_date == reference_local_date {
946 return formatted_time;
947 }
948
949 if reference_local_date.previous_day() == Some(timestamp_local_date) {
950 return format!("yesterday at {}", formatted_time);
951 }
952
953 format!(
954 "{:02}/{:02}/{}",
955 timestamp_local_date.month() as u32,
956 timestamp_local_date.day(),
957 timestamp_local_date.year()
958 )
959}
960
961#[cfg(test)]
962mod tests {
963 use super::*;
964 use gpui::HighlightStyle;
965 use pretty_assertions::assert_eq;
966 use rich_text::Highlight;
967 use time::{Date, OffsetDateTime, Time, UtcOffset};
968 use util::test::marked_text_ranges;
969
970 #[gpui::test]
971 fn test_render_markdown_with_mentions() {
972 let language_registry = Arc::new(LanguageRegistry::test());
973 let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
974 let message = channel::ChannelMessage {
975 id: ChannelMessageId::Saved(0),
976 body,
977 timestamp: OffsetDateTime::now_utc(),
978 sender: Arc::new(client::User {
979 github_login: "fgh".into(),
980 avatar_uri: "avatar_fgh".into(),
981 id: 103,
982 }),
983 nonce: 5,
984 mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
985 reply_to_message_id: None,
986 };
987
988 let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
989
990 // Note that the "'" was replaced with ’ due to smart punctuation.
991 let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
992 assert_eq!(message.text, body);
993 assert_eq!(
994 message.highlights,
995 vec![
996 (
997 ranges[0].clone(),
998 HighlightStyle {
999 font_style: Some(gpui::FontStyle::Italic),
1000 ..Default::default()
1001 }
1002 .into()
1003 ),
1004 (ranges[1].clone(), Highlight::Mention),
1005 (
1006 ranges[2].clone(),
1007 HighlightStyle {
1008 font_weight: Some(gpui::FontWeight::BOLD),
1009 ..Default::default()
1010 }
1011 .into()
1012 ),
1013 (ranges[3].clone(), Highlight::SelfMention)
1014 ]
1015 );
1016 }
1017
1018 #[test]
1019 fn test_format_today() {
1020 let reference = create_offset_datetime(1990, 4, 12, 16, 45, 0);
1021 let timestamp = create_offset_datetime(1990, 4, 12, 15, 30, 0);
1022
1023 assert_eq!(
1024 format_timestamp(reference, timestamp, test_timezone()),
1025 "03:30 pm"
1026 );
1027 }
1028
1029 #[test]
1030 fn test_format_yesterday() {
1031 let reference = create_offset_datetime(1990, 4, 12, 10, 30, 0);
1032 let timestamp = create_offset_datetime(1990, 4, 11, 9, 0, 0);
1033
1034 assert_eq!(
1035 format_timestamp(reference, timestamp, test_timezone()),
1036 "yesterday at 09:00 am"
1037 );
1038 }
1039
1040 #[test]
1041 fn test_format_yesterday_less_than_24_hours_ago() {
1042 let reference = create_offset_datetime(1990, 4, 12, 19, 59, 0);
1043 let timestamp = create_offset_datetime(1990, 4, 11, 20, 0, 0);
1044
1045 assert_eq!(
1046 format_timestamp(reference, timestamp, test_timezone()),
1047 "yesterday at 08:00 pm"
1048 );
1049 }
1050
1051 #[test]
1052 fn test_format_yesterday_more_than_24_hours_ago() {
1053 let reference = create_offset_datetime(1990, 4, 12, 19, 59, 0);
1054 let timestamp = create_offset_datetime(1990, 4, 11, 18, 0, 0);
1055
1056 assert_eq!(
1057 format_timestamp(reference, timestamp, test_timezone()),
1058 "yesterday at 06:00 pm"
1059 );
1060 }
1061
1062 #[test]
1063 fn test_format_yesterday_over_midnight() {
1064 let reference = create_offset_datetime(1990, 4, 12, 0, 5, 0);
1065 let timestamp = create_offset_datetime(1990, 4, 11, 23, 55, 0);
1066
1067 assert_eq!(
1068 format_timestamp(reference, timestamp, test_timezone()),
1069 "yesterday at 11:55 pm"
1070 );
1071 }
1072
1073 #[test]
1074 fn test_format_yesterday_over_month() {
1075 let reference = create_offset_datetime(1990, 4, 2, 9, 0, 0);
1076 let timestamp = create_offset_datetime(1990, 4, 1, 20, 0, 0);
1077
1078 assert_eq!(
1079 format_timestamp(reference, timestamp, test_timezone()),
1080 "yesterday at 08:00 pm"
1081 );
1082 }
1083
1084 #[test]
1085 fn test_format_before_yesterday() {
1086 let reference = create_offset_datetime(1990, 4, 12, 10, 30, 0);
1087 let timestamp = create_offset_datetime(1990, 4, 10, 20, 20, 0);
1088
1089 assert_eq!(
1090 format_timestamp(reference, timestamp, test_timezone()),
1091 "04/10/1990"
1092 );
1093 }
1094
1095 fn test_timezone() -> UtcOffset {
1096 UtcOffset::from_hms(0, 0, 0).expect("Valid timezone offset")
1097 }
1098
1099 fn create_offset_datetime(
1100 year: i32,
1101 month: u8,
1102 day: u8,
1103 hour: u8,
1104 minute: u8,
1105 second: u8,
1106 ) -> OffsetDateTime {
1107 let date =
1108 Date::from_calendar_date(year, time::Month::try_from(month).unwrap(), day).unwrap();
1109 let time = Time::from_hms(hour, minute, second).unwrap();
1110 date.with_time(time).assume_utc() // Assume UTC for simplicity
1111 }
1112}