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