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