1use crate::{collab_panel, ChatPanelSettings};
2use anyhow::Result;
3use call::{room, ActiveCall};
4use channel::{ChannelChat, ChannelChatEvent, ChannelMessage, ChannelMessageId, ChannelStore};
5use client::{ChannelId, Client};
6use collections::HashMap;
7use db::kvp::KEY_VALUE_STORE;
8use editor::{actions, Editor};
9use gpui::{
10 actions, div, list, prelude::*, px, Action, AppContext, AsyncWindowContext, ClipboardItem,
11 CursorStyle, DismissEvent, ElementId, EventEmitter, FocusHandle, FocusableView, FontWeight,
12 HighlightStyle, ListOffset, ListScrollEvent, ListState, Model, Render, Stateful, Subscription,
13 Task, View, ViewContext, VisualContext, WeakView,
14};
15use language::LanguageRegistry;
16use menu::Confirm;
17use message_editor::MessageEditor;
18use project::Fs;
19use rich_text::{Highlight, 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: &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 last_acknowledged_message_id: Option<u64>,
67}
68
69#[derive(Serialize, Deserialize)]
70struct SerializedChatPanel {
71 width: Option<Pixels>,
72}
73
74actions!(chat_panel, [ToggleFocus]);
75
76impl ChatPanel {
77 pub fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> View<Self> {
78 let fs = workspace.app_state().fs.clone();
79 let client = workspace.app_state().client.clone();
80 let channel_store = ChannelStore::global(cx);
81 let languages = workspace.app_state().languages.clone();
82
83 let input_editor = cx.new_view(|cx| {
84 MessageEditor::new(
85 languages.clone(),
86 channel_store.clone(),
87 cx.new_view(|cx| Editor::auto_height(4, cx)),
88 cx,
89 )
90 });
91
92 cx.new_view(|cx: &mut ViewContext<Self>| {
93 let view = cx.view().downgrade();
94 let message_list =
95 ListState::new(0, gpui::ListAlignment::Bottom, px(1000.), move |ix, cx| {
96 if let Some(view) = view.upgrade() {
97 view.update(cx, |view, cx| {
98 view.render_message(ix, cx).into_any_element()
99 })
100 } else {
101 div().into_any()
102 }
103 });
104
105 message_list.set_scroll_handler(cx.listener(|this, event: &ListScrollEvent, cx| {
106 if event.visible_range.start < MESSAGE_LOADING_THRESHOLD {
107 this.load_more_messages(cx);
108 }
109 this.is_scrolled_to_bottom = !event.is_scrolled;
110 }));
111
112 let mut this = Self {
113 fs,
114 client,
115 channel_store,
116 languages,
117 message_list,
118 active_chat: Default::default(),
119 pending_serialization: Task::ready(None),
120 message_editor: input_editor,
121 local_timezone: cx.local_timezone(),
122 subscriptions: Vec::new(),
123 is_scrolled_to_bottom: true,
124 active: false,
125 width: None,
126 markdown_data: Default::default(),
127 focus_handle: cx.focus_handle(),
128 open_context_menu: None,
129 highlighted_message: None,
130 last_acknowledged_message_id: None,
131 };
132
133 if let Some(channel_id) = ActiveCall::global(cx)
134 .read(cx)
135 .room()
136 .and_then(|room| room.read(cx).channel_id())
137 {
138 this.select_channel(channel_id, None, cx)
139 .detach_and_log_err(cx);
140 }
141
142 this.subscriptions.push(cx.subscribe(
143 &ActiveCall::global(cx),
144 move |this: &mut Self, call, event: &room::Event, cx| match event {
145 room::Event::RoomJoined { channel_id } => {
146 if let Some(channel_id) = channel_id {
147 this.select_channel(*channel_id, None, cx)
148 .detach_and_log_err(cx);
149
150 if call
151 .read(cx)
152 .room()
153 .is_some_and(|room| room.read(cx).contains_guests())
154 {
155 cx.emit(PanelEvent::Activate)
156 }
157 }
158 }
159 room::Event::RoomLeft { channel_id } => {
160 if channel_id == &this.channel_id(cx) {
161 cx.emit(PanelEvent::Close)
162 }
163 }
164 _ => {}
165 },
166 ));
167
168 this
169 })
170 }
171
172 pub fn channel_id(&self, cx: &AppContext) -> Option<ChannelId> {
173 self.active_chat
174 .as_ref()
175 .map(|(chat, _)| chat.read(cx).channel_id)
176 }
177
178 pub fn is_scrolled_to_bottom(&self) -> bool {
179 self.is_scrolled_to_bottom
180 }
181
182 pub fn active_chat(&self) -> Option<Model<ChannelChat>> {
183 self.active_chat.as_ref().map(|(chat, _)| chat.clone())
184 }
185
186 pub fn load(
187 workspace: WeakView<Workspace>,
188 cx: AsyncWindowContext,
189 ) -> Task<Result<View<Self>>> {
190 cx.spawn(|mut cx| async move {
191 let serialized_panel = if let Some(panel) = cx
192 .background_executor()
193 .spawn(async move { KEY_VALUE_STORE.read_kvp(CHAT_PANEL_KEY) })
194 .await
195 .log_err()
196 .flatten()
197 {
198 Some(serde_json::from_str::<SerializedChatPanel>(&panel)?)
199 } else {
200 None
201 };
202
203 workspace.update(&mut cx, |workspace, cx| {
204 let panel = Self::new(workspace, cx);
205 if let Some(serialized_panel) = serialized_panel {
206 panel.update(cx, |panel, cx| {
207 panel.width = serialized_panel.width.map(|r| r.round());
208 cx.notify();
209 });
210 }
211 panel
212 })
213 })
214 }
215
216 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
217 let width = self.width;
218 self.pending_serialization = cx.background_executor().spawn(
219 async move {
220 KEY_VALUE_STORE
221 .write_kvp(
222 CHAT_PANEL_KEY.into(),
223 serde_json::to_string(&SerializedChatPanel { width })?,
224 )
225 .await?;
226 anyhow::Ok(())
227 }
228 .log_err(),
229 );
230 }
231
232 fn set_active_chat(&mut self, chat: Model<ChannelChat>, cx: &mut ViewContext<Self>) {
233 if self.active_chat.as_ref().map(|e| &e.0) != Some(&chat) {
234 let channel_id = chat.read(cx).channel_id;
235 {
236 self.markdown_data.clear();
237 let chat = chat.read(cx);
238 self.message_list.reset(chat.message_count());
239
240 let channel_name = chat.channel(cx).map(|channel| channel.name.clone());
241 self.message_editor.update(cx, |editor, cx| {
242 editor.set_channel(channel_id, channel_name, cx);
243 editor.clear_reply_to_message_id();
244 });
245 };
246 let subscription = cx.subscribe(&chat, Self::channel_did_change);
247 self.active_chat = Some((chat, subscription));
248 self.acknowledge_last_message(cx);
249 cx.notify();
250 }
251 }
252
253 fn channel_did_change(
254 &mut self,
255 _: Model<ChannelChat>,
256 event: &ChannelChatEvent,
257 cx: &mut ViewContext<Self>,
258 ) {
259 match event {
260 ChannelChatEvent::MessagesUpdated {
261 old_range,
262 new_count,
263 } => {
264 self.message_list.splice(old_range.clone(), *new_count);
265 if self.active {
266 self.acknowledge_last_message(cx);
267 }
268 }
269 ChannelChatEvent::UpdateMessage {
270 message_id,
271 message_ix,
272 } => {
273 self.message_list.splice(*message_ix..*message_ix + 1, 1);
274 self.markdown_data.remove(message_id);
275 }
276 ChannelChatEvent::NewMessage {
277 channel_id,
278 message_id,
279 } => {
280 if !self.active {
281 self.channel_store.update(cx, |store, cx| {
282 store.update_latest_message_id(*channel_id, *message_id, cx)
283 })
284 }
285 }
286 }
287 cx.notify();
288 }
289
290 fn acknowledge_last_message(&mut self, cx: &mut ViewContext<Self>) {
291 if self.active && self.is_scrolled_to_bottom {
292 if let Some((chat, _)) = &self.active_chat {
293 if let Some(channel_id) = self.channel_id(cx) {
294 self.last_acknowledged_message_id = self
295 .channel_store
296 .read(cx)
297 .last_acknowledge_message_id(channel_id);
298 }
299
300 chat.update(cx, |chat, cx| {
301 chat.acknowledge_last_message(cx);
302 });
303 }
304 }
305 }
306
307 fn render_replied_to_message(
308 &mut self,
309 message_id: Option<ChannelMessageId>,
310 reply_to_message: &Option<ChannelMessage>,
311 cx: &mut ViewContext<Self>,
312 ) -> impl IntoElement {
313 let reply_to_message = match reply_to_message {
314 None => {
315 return div().child(
316 h_flex()
317 .text_ui_xs()
318 .my_0p5()
319 .px_0p5()
320 .gap_x_1()
321 .rounded_md()
322 .child(Icon::new(IconName::ReplyArrowRight).color(Color::Muted))
323 .when(reply_to_message.is_none(), |el| {
324 el.child(
325 Label::new("Message has been deleted...")
326 .size(LabelSize::XSmall)
327 .color(Color::Muted),
328 )
329 }),
330 )
331 }
332 Some(val) => val,
333 };
334
335 let user_being_replied_to = reply_to_message.sender.clone();
336 let message_being_replied_to = reply_to_message.clone();
337
338 let message_element_id: ElementId = match message_id {
339 Some(ChannelMessageId::Saved(id)) => ("reply-to-saved-message-container", id).into(),
340 Some(ChannelMessageId::Pending(id)) => {
341 ("reply-to-pending-message-container", id).into()
342 } // This should never happen
343 None => ("composing-reply-container").into(),
344 };
345
346 let current_channel_id = self.channel_id(cx);
347 let reply_to_message_id = reply_to_message.id;
348
349 div().child(
350 h_flex()
351 .id(message_element_id)
352 .text_ui_xs()
353 .my_0p5()
354 .px_0p5()
355 .gap_x_1()
356 .rounded_md()
357 .overflow_hidden()
358 .hover(|style| style.bg(cx.theme().colors().element_background))
359 .child(Icon::new(IconName::ReplyArrowRight).color(Color::Muted))
360 .child(Avatar::new(user_being_replied_to.avatar_uri.clone()).size(rems(0.7)))
361 .child(
362 div().font_weight(FontWeight::SEMIBOLD).child(
363 Label::new(format!("@{}", user_being_replied_to.github_login))
364 .size(LabelSize::XSmall)
365 .color(Color::Muted),
366 ),
367 )
368 .child(
369 div().overflow_y_hidden().child(
370 Label::new(message_being_replied_to.body.replace('\n', " "))
371 .size(LabelSize::XSmall)
372 .color(Color::Default),
373 ),
374 )
375 .cursor(CursorStyle::PointingHand)
376 .tooltip(|cx| Tooltip::text("Go to message", cx))
377 .on_click(cx.listener(move |chat_panel, _, cx| {
378 if let Some(channel_id) = current_channel_id {
379 chat_panel
380 .select_channel(channel_id, reply_to_message_id.into(), cx)
381 .detach_and_log_err(cx)
382 }
383 })),
384 )
385 }
386
387 fn render_message(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> impl IntoElement {
388 let active_chat = &self.active_chat.as_ref().unwrap().0;
389 let (message, is_continuation_from_previous, is_admin) =
390 active_chat.update(cx, |active_chat, cx| {
391 let is_admin = self
392 .channel_store
393 .read(cx)
394 .is_channel_admin(active_chat.channel_id);
395
396 let last_message = active_chat.message(ix.saturating_sub(1));
397 let this_message = active_chat.message(ix).clone();
398
399 let duration_since_last_message = this_message.timestamp - last_message.timestamp;
400 let is_continuation_from_previous = last_message.sender.id
401 == this_message.sender.id
402 && last_message.id != this_message.id
403 && duration_since_last_message < Duration::from_secs(5 * 60);
404
405 if let ChannelMessageId::Saved(id) = this_message.id {
406 if this_message
407 .mentions
408 .iter()
409 .any(|(_, user_id)| Some(*user_id) == self.client.user_id())
410 {
411 active_chat.acknowledge_message(id);
412 }
413 }
414
415 (this_message, is_continuation_from_previous, is_admin)
416 });
417
418 let _is_pending = message.is_pending();
419
420 let belongs_to_user = Some(message.sender.id) == self.client.user_id();
421 let can_delete_message = belongs_to_user || is_admin;
422 let can_edit_message = belongs_to_user;
423
424 let element_id: ElementId = match message.id {
425 ChannelMessageId::Saved(id) => ("saved-message", id).into(),
426 ChannelMessageId::Pending(id) => ("pending-message", id).into(),
427 };
428
429 let mentioning_you = message
430 .mentions
431 .iter()
432 .any(|m| Some(m.1) == self.client.user_id());
433
434 let message_id = match message.id {
435 ChannelMessageId::Saved(id) => Some(id),
436 ChannelMessageId::Pending(_) => None,
437 };
438
439 let reply_to_message = message
440 .reply_to_message_id
441 .and_then(|id| active_chat.read(cx).find_loaded_message(id))
442 .cloned();
443
444 let replied_to_you =
445 reply_to_message.as_ref().map(|m| m.sender.id) == self.client.user_id();
446
447 let is_highlighted_message = self
448 .highlighted_message
449 .as_ref()
450 .is_some_and(|(id, _)| Some(id) == message_id.as_ref());
451 let background = if is_highlighted_message {
452 cx.theme().status().info_background
453 } else if mentioning_you || replied_to_you {
454 cx.theme().colors().background
455 } else {
456 cx.theme().colors().panel_background
457 };
458
459 let reply_to_message_id = self.message_editor.read(cx).reply_to_message_id();
460
461 v_flex()
462 .w_full()
463 .relative()
464 .group("")
465 .when(!is_continuation_from_previous, |this| this.pt_2())
466 .child(
467 div()
468 .group("")
469 .bg(background)
470 .rounded_md()
471 .overflow_hidden()
472 .px_1p5()
473 .py_0p5()
474 .when_some(reply_to_message_id, |el, reply_id| {
475 el.when_some(message_id, |el, message_id| {
476 el.when(reply_id == message_id, |el| {
477 el.bg(cx.theme().colors().element_selected)
478 })
479 })
480 })
481 .when(!self.has_open_menu(message_id), |this| {
482 this.hover(|style| style.bg(cx.theme().colors().element_hover))
483 })
484 .when(message.reply_to_message_id.is_some(), |el| {
485 el.child(self.render_replied_to_message(
486 Some(message.id),
487 &reply_to_message,
488 cx,
489 ))
490 .when(is_continuation_from_previous, |this| this.mt_2())
491 })
492 .when(
493 !is_continuation_from_previous || message.reply_to_message_id.is_some(),
494 |this| {
495 this.child(
496 h_flex()
497 .text_ui_sm()
498 .child(
499 div().absolute().child(
500 Avatar::new(message.sender.avatar_uri.clone())
501 .size(rems(1.)),
502 ),
503 )
504 .child(
505 div()
506 .pl(cx.rem_size() + px(6.0))
507 .pr(px(8.0))
508 .font_weight(FontWeight::BOLD)
509 .child(
510 Label::new(message.sender.github_login.clone())
511 .size(LabelSize::Small),
512 ),
513 )
514 .child(
515 Label::new(time_format::format_localized_timestamp(
516 message.timestamp,
517 OffsetDateTime::now_utc(),
518 self.local_timezone,
519 time_format::TimestampFormat::EnhancedAbsolute,
520 ))
521 .size(LabelSize::Small)
522 .color(Color::Muted),
523 ),
524 )
525 },
526 )
527 .when(mentioning_you || replied_to_you, |this| this.my_0p5())
528 .map(|el| {
529 let text = self.markdown_data.entry(message.id).or_insert_with(|| {
530 Self::render_markdown_with_mentions(
531 &self.languages,
532 self.client.id(),
533 &message,
534 self.local_timezone,
535 cx,
536 )
537 });
538 el.child(
539 v_flex()
540 .w_full()
541 .text_ui_sm()
542 .id(element_id)
543 .child(text.element("body".into(), cx)),
544 )
545 .when(self.has_open_menu(message_id), |el| {
546 el.bg(cx.theme().colors().element_selected)
547 })
548 }),
549 )
550 .when(
551 self.last_acknowledged_message_id
552 .is_some_and(|l| Some(l) == message_id),
553 |this| {
554 this.child(
555 h_flex()
556 .py_2()
557 .gap_1()
558 .items_center()
559 .child(div().w_full().h_0p5().bg(cx.theme().colors().border))
560 .child(
561 div()
562 .px_1()
563 .rounded_md()
564 .text_ui_xs()
565 .bg(cx.theme().colors().background)
566 .child("New messages"),
567 )
568 .child(div().w_full().h_0p5().bg(cx.theme().colors().border)),
569 )
570 },
571 )
572 .child(
573 self.render_popover_buttons(&cx, message_id, can_delete_message, can_edit_message)
574 .neg_mt_2p5(),
575 )
576 }
577
578 fn has_open_menu(&self, message_id: Option<u64>) -> bool {
579 match self.open_context_menu.as_ref() {
580 Some((id, _)) => Some(*id) == message_id,
581 None => false,
582 }
583 }
584
585 fn render_popover_button(&self, cx: &ViewContext<Self>, child: Stateful<Div>) -> Div {
586 div()
587 .w_6()
588 .bg(cx.theme().colors().element_background)
589 .hover(|style| style.bg(cx.theme().colors().element_hover).rounded_md())
590 .child(child)
591 }
592
593 fn render_popover_buttons(
594 &self,
595 cx: &ViewContext<Self>,
596 message_id: Option<u64>,
597 can_delete_message: bool,
598 can_edit_message: bool,
599 ) -> Div {
600 h_flex()
601 .absolute()
602 .right_2()
603 .overflow_hidden()
604 .rounded_md()
605 .border_color(cx.theme().colors().element_selected)
606 .border_1()
607 .when(!self.has_open_menu(message_id), |el| {
608 el.visible_on_hover("")
609 })
610 .bg(cx.theme().colors().element_background)
611 .when_some(message_id, |el, message_id| {
612 el.child(
613 self.render_popover_button(
614 cx,
615 div()
616 .id("reply")
617 .child(
618 IconButton::new(("reply", message_id), IconName::ReplyArrowRight)
619 .on_click(cx.listener(move |this, _, cx| {
620 this.cancel_edit_message(cx);
621
622 this.message_editor.update(cx, |editor, cx| {
623 editor.set_reply_to_message_id(message_id);
624 editor.focus_handle(cx).focus(cx);
625 })
626 })),
627 )
628 .tooltip(|cx| Tooltip::text("Reply", cx)),
629 ),
630 )
631 })
632 .when_some(message_id, |el, message_id| {
633 el.when(can_edit_message, |el| {
634 el.child(
635 self.render_popover_button(
636 cx,
637 div()
638 .id("edit")
639 .child(
640 IconButton::new(("edit", message_id), IconName::Pencil)
641 .on_click(cx.listener(move |this, _, cx| {
642 this.message_editor.update(cx, |editor, cx| {
643 editor.clear_reply_to_message_id();
644
645 let message = this
646 .active_chat()
647 .and_then(|active_chat| {
648 active_chat
649 .read(cx)
650 .find_loaded_message(message_id)
651 })
652 .cloned();
653
654 if let Some(message) = message {
655 let buffer = editor
656 .editor
657 .read(cx)
658 .buffer()
659 .read(cx)
660 .as_singleton()
661 .expect("message editor must be singleton");
662
663 buffer.update(cx, |buffer, cx| {
664 buffer.set_text(message.body.clone(), cx)
665 });
666
667 editor.set_edit_message_id(message_id);
668 editor.focus_handle(cx).focus(cx);
669 }
670 })
671 })),
672 )
673 .tooltip(|cx| Tooltip::text("Edit", cx)),
674 ),
675 )
676 })
677 })
678 .when_some(message_id, |el, message_id| {
679 let this = cx.view().clone();
680
681 el.child(
682 self.render_popover_button(
683 cx,
684 div()
685 .child(
686 popover_menu(("menu", message_id))
687 .trigger(IconButton::new(
688 ("trigger", message_id),
689 IconName::Ellipsis,
690 ))
691 .menu(move |cx| {
692 Some(Self::render_message_menu(
693 &this,
694 message_id,
695 can_delete_message,
696 cx,
697 ))
698 }),
699 )
700 .id("more")
701 .tooltip(|cx| Tooltip::text("More", cx)),
702 ),
703 )
704 })
705 }
706
707 fn render_message_menu(
708 this: &View<Self>,
709 message_id: u64,
710 can_delete_message: bool,
711 cx: &mut WindowContext,
712 ) -> View<ContextMenu> {
713 let menu = {
714 ContextMenu::build(cx, move |menu, cx| {
715 menu.entry(
716 "Copy message text",
717 None,
718 cx.handler_for(&this, move |this, cx| {
719 if let Some(message) = this.active_chat().and_then(|active_chat| {
720 active_chat.read(cx).find_loaded_message(message_id)
721 }) {
722 let text = message.body.clone();
723 cx.write_to_clipboard(ClipboardItem::new(text))
724 }
725 }),
726 )
727 .when(can_delete_message, |menu| {
728 menu.entry(
729 "Delete message",
730 None,
731 cx.handler_for(&this, move |this, cx| this.remove_message(message_id, cx)),
732 )
733 })
734 })
735 };
736 this.update(cx, |this, cx| {
737 let subscription = cx.subscribe(&menu, |this: &mut Self, _, _: &DismissEvent, _| {
738 this.open_context_menu = None;
739 });
740 this.open_context_menu = Some((message_id, subscription));
741 });
742 menu
743 }
744
745 fn render_markdown_with_mentions(
746 language_registry: &Arc<LanguageRegistry>,
747 current_user_id: u64,
748 message: &channel::ChannelMessage,
749 local_timezone: UtcOffset,
750 cx: &AppContext,
751 ) -> RichText {
752 let mentions = message
753 .mentions
754 .iter()
755 .map(|(range, user_id)| rich_text::Mention {
756 range: range.clone(),
757 is_self_mention: *user_id == current_user_id,
758 })
759 .collect::<Vec<_>>();
760
761 const MESSAGE_EDITED: &str = " (edited)";
762
763 let mut body = message.body.clone();
764
765 if message.edited_at.is_some() {
766 body.push_str(MESSAGE_EDITED);
767 }
768
769 let mut rich_text = rich_text::render_rich_text(body, &mentions, language_registry, None);
770
771 if message.edited_at.is_some() {
772 let range = (rich_text.text.len() - MESSAGE_EDITED.len())..rich_text.text.len();
773 rich_text.highlights.push((
774 range.clone(),
775 Highlight::Highlight(HighlightStyle {
776 color: Some(cx.theme().colors().text_muted),
777 ..Default::default()
778 }),
779 ));
780
781 if let Some(edit_timestamp) = message.edited_at {
782 let edit_timestamp_text = time_format::format_localized_timestamp(
783 edit_timestamp,
784 OffsetDateTime::now_utc(),
785 local_timezone,
786 time_format::TimestampFormat::Absolute,
787 );
788
789 rich_text.custom_ranges.push(range);
790 rich_text.set_tooltip_builder_for_custom_ranges(move |_, _, cx| {
791 Some(Tooltip::text(edit_timestamp_text.clone(), cx))
792 })
793 }
794 }
795 rich_text
796 }
797
798 fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
799 if let Some((chat, _)) = self.active_chat.as_ref() {
800 let message = self
801 .message_editor
802 .update(cx, |editor, cx| editor.take_message(cx));
803
804 if let Some(id) = self.message_editor.read(cx).edit_message_id() {
805 self.message_editor.update(cx, |editor, _| {
806 editor.clear_edit_message_id();
807 });
808
809 if let Some(task) = chat
810 .update(cx, |chat, cx| chat.update_message(id, message, cx))
811 .log_err()
812 {
813 task.detach();
814 }
815 } else {
816 if let Some(task) = chat
817 .update(cx, |chat, cx| chat.send_message(message, cx))
818 .log_err()
819 {
820 task.detach();
821 }
822 }
823 }
824 }
825
826 fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
827 if let Some((chat, _)) = self.active_chat.as_ref() {
828 chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
829 }
830 }
831
832 fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
833 if let Some((chat, _)) = self.active_chat.as_ref() {
834 chat.update(cx, |channel, cx| {
835 if let Some(task) = channel.load_more_messages(cx) {
836 task.detach();
837 }
838 })
839 }
840 }
841
842 pub fn select_channel(
843 &mut self,
844 selected_channel_id: ChannelId,
845 scroll_to_message_id: Option<u64>,
846 cx: &mut ViewContext<ChatPanel>,
847 ) -> Task<Result<()>> {
848 let open_chat = self
849 .active_chat
850 .as_ref()
851 .and_then(|(chat, _)| {
852 (chat.read(cx).channel_id == selected_channel_id)
853 .then(|| Task::ready(anyhow::Ok(chat.clone())))
854 })
855 .unwrap_or_else(|| {
856 self.channel_store.update(cx, |store, cx| {
857 store.open_channel_chat(selected_channel_id, cx)
858 })
859 });
860
861 cx.spawn(|this, mut cx| async move {
862 let chat = open_chat.await?;
863 let highlight_message_id = scroll_to_message_id;
864 let scroll_to_message_id = this.update(&mut cx, |this, cx| {
865 this.set_active_chat(chat.clone(), cx);
866
867 scroll_to_message_id.or_else(|| this.last_acknowledged_message_id)
868 })?;
869
870 if let Some(message_id) = scroll_to_message_id {
871 if let Some(item_ix) =
872 ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
873 .await
874 {
875 this.update(&mut cx, |this, cx| {
876 if let Some(highlight_message_id) = highlight_message_id {
877 let task = cx.spawn({
878 |this, mut cx| async move {
879 cx.background_executor().timer(Duration::from_secs(2)).await;
880 this.update(&mut cx, |this, cx| {
881 this.highlighted_message.take();
882 cx.notify();
883 })
884 .ok();
885 }
886 });
887
888 this.highlighted_message = Some((highlight_message_id, task));
889 }
890
891 if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
892 this.message_list.scroll_to(ListOffset {
893 item_ix,
894 offset_in_item: px(0.0),
895 });
896 cx.notify();
897 }
898 })?;
899 }
900 }
901
902 Ok(())
903 })
904 }
905
906 fn close_reply_preview(&mut self, cx: &mut ViewContext<Self>) {
907 self.message_editor
908 .update(cx, |editor, _| editor.clear_reply_to_message_id());
909 }
910
911 fn cancel_edit_message(&mut self, cx: &mut ViewContext<Self>) {
912 self.message_editor.update(cx, |editor, cx| {
913 // only clear the editor input if we were editing a message
914 if editor.edit_message_id().is_none() {
915 return;
916 }
917
918 editor.clear_edit_message_id();
919
920 let buffer = editor
921 .editor
922 .read(cx)
923 .buffer()
924 .read(cx)
925 .as_singleton()
926 .expect("message editor must be singleton");
927
928 buffer.update(cx, |buffer, cx| buffer.set_text("", cx));
929 });
930 }
931}
932
933impl Render for ChatPanel {
934 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
935 let channel_id = self
936 .active_chat
937 .as_ref()
938 .map(|(c, _)| c.read(cx).channel_id);
939 let message_editor = self.message_editor.read(cx);
940
941 let reply_to_message_id = message_editor.reply_to_message_id();
942 let edit_message_id = message_editor.edit_message_id();
943
944 v_flex()
945 .key_context("ChatPanel")
946 .track_focus(&self.focus_handle)
947 .size_full()
948 .on_action(cx.listener(Self::send))
949 .child(
950 h_flex().child(
951 TabBar::new("chat_header").child(
952 h_flex()
953 .w_full()
954 .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
955 .px_2()
956 .child(Label::new(
957 self.active_chat
958 .as_ref()
959 .and_then(|c| {
960 Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
961 })
962 .unwrap_or("Chat".to_string()),
963 )),
964 ),
965 ),
966 )
967 .child(div().flex_grow().px_2().map(|this| {
968 if self.active_chat.is_some() {
969 this.child(list(self.message_list.clone()).size_full())
970 } else {
971 this.child(
972 div()
973 .size_full()
974 .p_4()
975 .child(
976 Label::new("Select a channel to chat in.")
977 .size(LabelSize::Small)
978 .color(Color::Muted),
979 )
980 .child(
981 div().pt_1().w_full().items_center().child(
982 Button::new("toggle-collab", "Open")
983 .full_width()
984 .key_binding(KeyBinding::for_action(
985 &collab_panel::ToggleFocus,
986 cx,
987 ))
988 .on_click(|_, cx| {
989 cx.dispatch_action(
990 collab_panel::ToggleFocus.boxed_clone(),
991 )
992 }),
993 ),
994 ),
995 )
996 }
997 }))
998 .when(!self.is_scrolled_to_bottom, |el| {
999 el.child(div().border_t_1().border_color(cx.theme().colors().border))
1000 })
1001 .when_some(edit_message_id, |el, _| {
1002 el.child(
1003 h_flex()
1004 .px_2()
1005 .text_ui_xs()
1006 .justify_between()
1007 .border_t_1()
1008 .border_color(cx.theme().colors().border)
1009 .bg(cx.theme().colors().background)
1010 .child("Editing message")
1011 .child(
1012 IconButton::new("cancel-edit-message", IconName::Close)
1013 .shape(ui::IconButtonShape::Square)
1014 .tooltip(|cx| Tooltip::text("Cancel edit message", cx))
1015 .on_click(cx.listener(move |this, _, cx| {
1016 this.cancel_edit_message(cx);
1017 })),
1018 ),
1019 )
1020 })
1021 .when_some(reply_to_message_id, |el, reply_to_message_id| {
1022 let reply_message = self
1023 .active_chat()
1024 .and_then(|active_chat| {
1025 active_chat
1026 .read(cx)
1027 .find_loaded_message(reply_to_message_id)
1028 })
1029 .cloned();
1030
1031 el.when_some(reply_message, |el, reply_message| {
1032 let user_being_replied_to = reply_message.sender.clone();
1033
1034 el.child(
1035 h_flex()
1036 .when(!self.is_scrolled_to_bottom, |el| {
1037 el.border_t_1().border_color(cx.theme().colors().border)
1038 })
1039 .justify_between()
1040 .overflow_hidden()
1041 .items_start()
1042 .py_1()
1043 .px_2()
1044 .bg(cx.theme().colors().background)
1045 .child(
1046 div().flex_shrink().overflow_hidden().child(
1047 h_flex()
1048 .id(("reply-preview", reply_to_message_id))
1049 .child(Label::new("Replying to ").size(LabelSize::Small))
1050 .child(
1051 div().font_weight(FontWeight::BOLD).child(
1052 Label::new(format!(
1053 "@{}",
1054 user_being_replied_to.github_login.clone()
1055 ))
1056 .size(LabelSize::Small),
1057 ),
1058 )
1059 .when_some(channel_id, |this, channel_id| {
1060 this.cursor_pointer().on_click(cx.listener(
1061 move |chat_panel, _, cx| {
1062 chat_panel
1063 .select_channel(
1064 channel_id,
1065 reply_to_message_id.into(),
1066 cx,
1067 )
1068 .detach_and_log_err(cx)
1069 },
1070 ))
1071 }),
1072 ),
1073 )
1074 .child(
1075 IconButton::new("close-reply-preview", IconName::Close)
1076 .shape(ui::IconButtonShape::Square)
1077 .tooltip(|cx| Tooltip::text("Close reply", cx))
1078 .on_click(cx.listener(move |this, _, cx| {
1079 this.close_reply_preview(cx);
1080 })),
1081 ),
1082 )
1083 })
1084 })
1085 .children(
1086 Some(
1087 h_flex()
1088 .p_2()
1089 .on_action(cx.listener(|this, _: &actions::Cancel, cx| {
1090 this.cancel_edit_message(cx);
1091 this.close_reply_preview(cx);
1092 }))
1093 .map(|el| el.child(self.message_editor.clone())),
1094 )
1095 .filter(|_| self.active_chat.is_some()),
1096 )
1097 .into_any()
1098 }
1099}
1100
1101impl FocusableView for ChatPanel {
1102 fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
1103 if self.active_chat.is_some() {
1104 self.message_editor.read(cx).focus_handle(cx)
1105 } else {
1106 self.focus_handle.clone()
1107 }
1108 }
1109}
1110
1111impl Panel for ChatPanel {
1112 fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
1113 ChatPanelSettings::get_global(cx).dock
1114 }
1115
1116 fn position_is_valid(&self, position: DockPosition) -> bool {
1117 matches!(position, DockPosition::Left | DockPosition::Right)
1118 }
1119
1120 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1121 settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
1122 settings.dock = Some(position)
1123 });
1124 }
1125
1126 fn size(&self, cx: &gpui::WindowContext) -> Pixels {
1127 self.width
1128 .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
1129 }
1130
1131 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1132 self.width = size;
1133 self.serialize(cx);
1134 cx.notify();
1135 }
1136
1137 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1138 self.active = active;
1139 if active {
1140 self.acknowledge_last_message(cx);
1141 }
1142 }
1143
1144 fn persistent_name() -> &'static str {
1145 "ChatPanel"
1146 }
1147
1148 fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
1149 Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
1150 }
1151
1152 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1153 Some("Chat Panel")
1154 }
1155
1156 fn toggle_action(&self) -> Box<dyn gpui::Action> {
1157 Box::new(ToggleFocus)
1158 }
1159
1160 fn starts_open(&self, cx: &WindowContext) -> bool {
1161 ActiveCall::global(cx)
1162 .read(cx)
1163 .room()
1164 .is_some_and(|room| room.read(cx).contains_guests())
1165 }
1166}
1167
1168impl EventEmitter<PanelEvent> for ChatPanel {}
1169
1170#[cfg(test)]
1171mod tests {
1172 use super::*;
1173 use gpui::HighlightStyle;
1174 use pretty_assertions::assert_eq;
1175 use rich_text::Highlight;
1176 use time::OffsetDateTime;
1177 use util::test::marked_text_ranges;
1178
1179 #[gpui::test]
1180 fn test_render_markdown_with_mentions(cx: &mut AppContext) {
1181 let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1182 let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
1183 let message = channel::ChannelMessage {
1184 id: ChannelMessageId::Saved(0),
1185 body,
1186 timestamp: OffsetDateTime::now_utc(),
1187 sender: Arc::new(client::User {
1188 github_login: "fgh".into(),
1189 avatar_uri: "avatar_fgh".into(),
1190 id: 103,
1191 }),
1192 nonce: 5,
1193 mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
1194 reply_to_message_id: None,
1195 edited_at: None,
1196 };
1197
1198 let message = ChatPanel::render_markdown_with_mentions(
1199 &language_registry,
1200 102,
1201 &message,
1202 UtcOffset::UTC,
1203 cx,
1204 );
1205
1206 // Note that the "'" was replaced with ’ due to smart punctuation.
1207 let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
1208 assert_eq!(message.text, body);
1209 assert_eq!(
1210 message.highlights,
1211 vec![
1212 (
1213 ranges[0].clone(),
1214 HighlightStyle {
1215 font_style: Some(gpui::FontStyle::Italic),
1216 ..Default::default()
1217 }
1218 .into()
1219 ),
1220 (ranges[1].clone(), Highlight::Mention),
1221 (
1222 ranges[2].clone(),
1223 HighlightStyle {
1224 font_weight: Some(gpui::FontWeight::BOLD),
1225 ..Default::default()
1226 }
1227 .into()
1228 ),
1229 (ranges[3].clone(), Highlight::SelfMention)
1230 ]
1231 );
1232 }
1233
1234 #[gpui::test]
1235 fn test_render_markdown_with_auto_detect_links(cx: &mut AppContext) {
1236 let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1237 let message = channel::ChannelMessage {
1238 id: ChannelMessageId::Saved(0),
1239 body: "Here is a link https://zed.dev to zeds website".to_string(),
1240 timestamp: OffsetDateTime::now_utc(),
1241 sender: Arc::new(client::User {
1242 github_login: "fgh".into(),
1243 avatar_uri: "avatar_fgh".into(),
1244 id: 103,
1245 }),
1246 nonce: 5,
1247 mentions: Vec::new(),
1248 reply_to_message_id: None,
1249 edited_at: None,
1250 };
1251
1252 let message = ChatPanel::render_markdown_with_mentions(
1253 &language_registry,
1254 102,
1255 &message,
1256 UtcOffset::UTC,
1257 cx,
1258 );
1259
1260 // Note that the "'" was replaced with ’ due to smart punctuation.
1261 let (body, ranges) =
1262 marked_text_ranges("Here is a link «https://zed.dev» to zeds website", false);
1263 assert_eq!(message.text, body);
1264 assert_eq!(1, ranges.len());
1265 assert_eq!(
1266 message.highlights,
1267 vec![(
1268 ranges[0].clone(),
1269 HighlightStyle {
1270 underline: Some(gpui::UnderlineStyle {
1271 thickness: 1.0.into(),
1272 ..Default::default()
1273 }),
1274 ..Default::default()
1275 }
1276 .into()
1277 ),]
1278 );
1279 }
1280
1281 #[gpui::test]
1282 fn test_render_markdown_with_auto_detect_links_and_additional_formatting(cx: &mut AppContext) {
1283 let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1284 let message = channel::ChannelMessage {
1285 id: ChannelMessageId::Saved(0),
1286 body: "**Here is a link https://zed.dev to zeds website**".to_string(),
1287 timestamp: OffsetDateTime::now_utc(),
1288 sender: Arc::new(client::User {
1289 github_login: "fgh".into(),
1290 avatar_uri: "avatar_fgh".into(),
1291 id: 103,
1292 }),
1293 nonce: 5,
1294 mentions: Vec::new(),
1295 reply_to_message_id: None,
1296 edited_at: None,
1297 };
1298
1299 let message = ChatPanel::render_markdown_with_mentions(
1300 &language_registry,
1301 102,
1302 &message,
1303 UtcOffset::UTC,
1304 cx,
1305 );
1306
1307 // Note that the "'" was replaced with ’ due to smart punctuation.
1308 let (body, ranges) = marked_text_ranges(
1309 "«Here is a link »«https://zed.dev»« to zeds website»",
1310 false,
1311 );
1312 assert_eq!(message.text, body);
1313 assert_eq!(3, ranges.len());
1314 assert_eq!(
1315 message.highlights,
1316 vec![
1317 (
1318 ranges[0].clone(),
1319 HighlightStyle {
1320 font_weight: Some(gpui::FontWeight::BOLD),
1321 ..Default::default()
1322 }
1323 .into()
1324 ),
1325 (
1326 ranges[1].clone(),
1327 HighlightStyle {
1328 font_weight: Some(gpui::FontWeight::BOLD),
1329 underline: Some(gpui::UnderlineStyle {
1330 thickness: 1.0.into(),
1331 ..Default::default()
1332 }),
1333 ..Default::default()
1334 }
1335 .into()
1336 ),
1337 (
1338 ranges[2].clone(),
1339 HighlightStyle {
1340 font_weight: Some(gpui::FontWeight::BOLD),
1341 ..Default::default()
1342 }
1343 .into()
1344 ),
1345 ]
1346 );
1347 }
1348}