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_string(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 if let Some(task) = chat
806 .update(cx, |chat, cx| chat.send_message(message, cx))
807 .log_err()
808 {
809 task.detach();
810 }
811 }
812 }
813
814 fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
815 if let Some((chat, _)) = self.active_chat.as_ref() {
816 chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
817 }
818 }
819
820 fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
821 if let Some((chat, _)) = self.active_chat.as_ref() {
822 chat.update(cx, |channel, cx| {
823 if let Some(task) = channel.load_more_messages(cx) {
824 task.detach();
825 }
826 })
827 }
828 }
829
830 pub fn select_channel(
831 &mut self,
832 selected_channel_id: ChannelId,
833 scroll_to_message_id: Option<u64>,
834 cx: &mut ViewContext<ChatPanel>,
835 ) -> Task<Result<()>> {
836 let open_chat = self
837 .active_chat
838 .as_ref()
839 .and_then(|(chat, _)| {
840 (chat.read(cx).channel_id == selected_channel_id)
841 .then(|| Task::ready(anyhow::Ok(chat.clone())))
842 })
843 .unwrap_or_else(|| {
844 self.channel_store.update(cx, |store, cx| {
845 store.open_channel_chat(selected_channel_id, cx)
846 })
847 });
848
849 cx.spawn(|this, mut cx| async move {
850 let chat = open_chat.await?;
851 let highlight_message_id = scroll_to_message_id;
852 let scroll_to_message_id = this.update(&mut cx, |this, cx| {
853 this.set_active_chat(chat.clone(), cx);
854
855 scroll_to_message_id.or(this.last_acknowledged_message_id)
856 })?;
857
858 if let Some(message_id) = scroll_to_message_id {
859 if let Some(item_ix) =
860 ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
861 .await
862 {
863 this.update(&mut cx, |this, cx| {
864 if let Some(highlight_message_id) = highlight_message_id {
865 let task = cx.spawn({
866 |this, mut cx| async move {
867 cx.background_executor().timer(Duration::from_secs(2)).await;
868 this.update(&mut cx, |this, cx| {
869 this.highlighted_message.take();
870 cx.notify();
871 })
872 .ok();
873 }
874 });
875
876 this.highlighted_message = Some((highlight_message_id, task));
877 }
878
879 if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
880 this.message_list.scroll_to(ListOffset {
881 item_ix,
882 offset_in_item: px(0.0),
883 });
884 cx.notify();
885 }
886 })?;
887 }
888 }
889
890 Ok(())
891 })
892 }
893
894 fn close_reply_preview(&mut self, cx: &mut ViewContext<Self>) {
895 self.message_editor
896 .update(cx, |editor, _| editor.clear_reply_to_message_id());
897 }
898
899 fn cancel_edit_message(&mut self, cx: &mut ViewContext<Self>) {
900 self.message_editor.update(cx, |editor, cx| {
901 // only clear the editor input if we were editing a message
902 if editor.edit_message_id().is_none() {
903 return;
904 }
905
906 editor.clear_edit_message_id();
907
908 let buffer = editor
909 .editor
910 .read(cx)
911 .buffer()
912 .read(cx)
913 .as_singleton()
914 .expect("message editor must be singleton");
915
916 buffer.update(cx, |buffer, cx| buffer.set_text("", cx));
917 });
918 }
919}
920
921impl Render for ChatPanel {
922 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
923 let channel_id = self
924 .active_chat
925 .as_ref()
926 .map(|(c, _)| c.read(cx).channel_id);
927 let message_editor = self.message_editor.read(cx);
928
929 let reply_to_message_id = message_editor.reply_to_message_id();
930 let edit_message_id = message_editor.edit_message_id();
931
932 v_flex()
933 .key_context("ChatPanel")
934 .track_focus(&self.focus_handle)
935 .size_full()
936 .on_action(cx.listener(Self::send))
937 .child(
938 h_flex().child(
939 TabBar::new("chat_header").child(
940 h_flex()
941 .w_full()
942 .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
943 .px_2()
944 .child(Label::new(
945 self.active_chat
946 .as_ref()
947 .and_then(|c| {
948 Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
949 })
950 .unwrap_or("Chat".to_string()),
951 )),
952 ),
953 ),
954 )
955 .child(div().flex_grow().px_2().map(|this| {
956 if self.active_chat.is_some() {
957 this.child(list(self.message_list.clone()).size_full())
958 } else {
959 this.child(
960 div()
961 .size_full()
962 .p_4()
963 .child(
964 Label::new("Select a channel to chat in.")
965 .size(LabelSize::Small)
966 .color(Color::Muted),
967 )
968 .child(
969 div().pt_1().w_full().items_center().child(
970 Button::new("toggle-collab", "Open")
971 .full_width()
972 .key_binding(KeyBinding::for_action(
973 &collab_panel::ToggleFocus,
974 cx,
975 ))
976 .on_click(|_, cx| {
977 cx.dispatch_action(
978 collab_panel::ToggleFocus.boxed_clone(),
979 )
980 }),
981 ),
982 ),
983 )
984 }
985 }))
986 .when(!self.is_scrolled_to_bottom, |el| {
987 el.child(div().border_t_1().border_color(cx.theme().colors().border))
988 })
989 .when_some(edit_message_id, |el, _| {
990 el.child(
991 h_flex()
992 .px_2()
993 .text_ui_xs(cx)
994 .justify_between()
995 .border_t_1()
996 .border_color(cx.theme().colors().border)
997 .bg(cx.theme().colors().background)
998 .child("Editing message")
999 .child(
1000 IconButton::new("cancel-edit-message", IconName::Close)
1001 .shape(ui::IconButtonShape::Square)
1002 .tooltip(|cx| Tooltip::text("Cancel edit message", cx))
1003 .on_click(cx.listener(move |this, _, cx| {
1004 this.cancel_edit_message(cx);
1005 })),
1006 ),
1007 )
1008 })
1009 .when_some(reply_to_message_id, |el, reply_to_message_id| {
1010 let reply_message = self
1011 .active_chat()
1012 .and_then(|active_chat| {
1013 active_chat
1014 .read(cx)
1015 .find_loaded_message(reply_to_message_id)
1016 })
1017 .cloned();
1018
1019 el.when_some(reply_message, |el, reply_message| {
1020 let user_being_replied_to = reply_message.sender.clone();
1021
1022 el.child(
1023 h_flex()
1024 .when(!self.is_scrolled_to_bottom, |el| {
1025 el.border_t_1().border_color(cx.theme().colors().border)
1026 })
1027 .justify_between()
1028 .overflow_hidden()
1029 .items_start()
1030 .py_1()
1031 .px_2()
1032 .bg(cx.theme().colors().background)
1033 .child(
1034 div().flex_shrink().overflow_hidden().child(
1035 h_flex()
1036 .id(("reply-preview", reply_to_message_id))
1037 .child(Label::new("Replying to ").size(LabelSize::Small))
1038 .child(
1039 Label::new(format!(
1040 "@{}",
1041 user_being_replied_to.github_login.clone()
1042 ))
1043 .size(LabelSize::Small)
1044 .weight(FontWeight::BOLD),
1045 )
1046 .when_some(channel_id, |this, channel_id| {
1047 this.cursor_pointer().on_click(cx.listener(
1048 move |chat_panel, _, cx| {
1049 chat_panel
1050 .select_channel(
1051 channel_id,
1052 reply_to_message_id.into(),
1053 cx,
1054 )
1055 .detach_and_log_err(cx)
1056 },
1057 ))
1058 }),
1059 ),
1060 )
1061 .child(
1062 IconButton::new("close-reply-preview", IconName::Close)
1063 .shape(ui::IconButtonShape::Square)
1064 .tooltip(|cx| Tooltip::text("Close reply", cx))
1065 .on_click(cx.listener(move |this, _, cx| {
1066 this.close_reply_preview(cx);
1067 })),
1068 ),
1069 )
1070 })
1071 })
1072 .children(
1073 Some(
1074 h_flex()
1075 .p_2()
1076 .on_action(cx.listener(|this, _: &actions::Cancel, cx| {
1077 this.cancel_edit_message(cx);
1078 this.close_reply_preview(cx);
1079 }))
1080 .map(|el| el.child(self.message_editor.clone())),
1081 )
1082 .filter(|_| self.active_chat.is_some()),
1083 )
1084 .into_any()
1085 }
1086}
1087
1088impl FocusableView for ChatPanel {
1089 fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
1090 if self.active_chat.is_some() {
1091 self.message_editor.read(cx).focus_handle(cx)
1092 } else {
1093 self.focus_handle.clone()
1094 }
1095 }
1096}
1097
1098impl Panel for ChatPanel {
1099 fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
1100 ChatPanelSettings::get_global(cx).dock
1101 }
1102
1103 fn position_is_valid(&self, position: DockPosition) -> bool {
1104 matches!(position, DockPosition::Left | DockPosition::Right)
1105 }
1106
1107 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1108 settings::update_settings_file::<ChatPanelSettings>(
1109 self.fs.clone(),
1110 cx,
1111 move |settings, _| settings.dock = Some(position),
1112 );
1113 }
1114
1115 fn size(&self, cx: &gpui::WindowContext) -> Pixels {
1116 self.width
1117 .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
1118 }
1119
1120 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1121 self.width = size;
1122 self.serialize(cx);
1123 cx.notify();
1124 }
1125
1126 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1127 self.active = active;
1128 if active {
1129 self.acknowledge_last_message(cx);
1130 }
1131 }
1132
1133 fn persistent_name() -> &'static str {
1134 "ChatPanel"
1135 }
1136
1137 fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
1138 Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
1139 }
1140
1141 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1142 Some("Chat Panel")
1143 }
1144
1145 fn toggle_action(&self) -> Box<dyn gpui::Action> {
1146 Box::new(ToggleFocus)
1147 }
1148
1149 fn starts_open(&self, cx: &WindowContext) -> bool {
1150 ActiveCall::global(cx)
1151 .read(cx)
1152 .room()
1153 .is_some_and(|room| room.read(cx).contains_guests())
1154 }
1155}
1156
1157impl EventEmitter<PanelEvent> for ChatPanel {}
1158
1159#[cfg(test)]
1160mod tests {
1161 use super::*;
1162 use gpui::HighlightStyle;
1163 use pretty_assertions::assert_eq;
1164 use rich_text::Highlight;
1165 use time::OffsetDateTime;
1166 use util::test::marked_text_ranges;
1167
1168 #[gpui::test]
1169 fn test_render_markdown_with_mentions(cx: &mut AppContext) {
1170 let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1171 let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
1172 let message = channel::ChannelMessage {
1173 id: ChannelMessageId::Saved(0),
1174 body,
1175 timestamp: OffsetDateTime::now_utc(),
1176 sender: Arc::new(client::User {
1177 github_login: "fgh".into(),
1178 avatar_uri: "avatar_fgh".into(),
1179 id: 103,
1180 }),
1181 nonce: 5,
1182 mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
1183 reply_to_message_id: None,
1184 edited_at: None,
1185 };
1186
1187 let message = ChatPanel::render_markdown_with_mentions(
1188 &language_registry,
1189 102,
1190 &message,
1191 UtcOffset::UTC,
1192 cx,
1193 );
1194
1195 // Note that the "'" was replaced with ’ due to smart punctuation.
1196 let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
1197 assert_eq!(message.text, body);
1198 assert_eq!(
1199 message.highlights,
1200 vec![
1201 (
1202 ranges[0].clone(),
1203 HighlightStyle {
1204 font_style: Some(gpui::FontStyle::Italic),
1205 ..Default::default()
1206 }
1207 .into()
1208 ),
1209 (ranges[1].clone(), Highlight::Mention),
1210 (
1211 ranges[2].clone(),
1212 HighlightStyle {
1213 font_weight: Some(gpui::FontWeight::BOLD),
1214 ..Default::default()
1215 }
1216 .into()
1217 ),
1218 (ranges[3].clone(), Highlight::SelfMention)
1219 ]
1220 );
1221 }
1222
1223 #[gpui::test]
1224 fn test_render_markdown_with_auto_detect_links(cx: &mut AppContext) {
1225 let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1226 let message = channel::ChannelMessage {
1227 id: ChannelMessageId::Saved(0),
1228 body: "Here is a link https://zed.dev to zeds website".to_string(),
1229 timestamp: OffsetDateTime::now_utc(),
1230 sender: Arc::new(client::User {
1231 github_login: "fgh".into(),
1232 avatar_uri: "avatar_fgh".into(),
1233 id: 103,
1234 }),
1235 nonce: 5,
1236 mentions: Vec::new(),
1237 reply_to_message_id: None,
1238 edited_at: None,
1239 };
1240
1241 let message = ChatPanel::render_markdown_with_mentions(
1242 &language_registry,
1243 102,
1244 &message,
1245 UtcOffset::UTC,
1246 cx,
1247 );
1248
1249 // Note that the "'" was replaced with ’ due to smart punctuation.
1250 let (body, ranges) =
1251 marked_text_ranges("Here is a link «https://zed.dev» to zeds website", false);
1252 assert_eq!(message.text, body);
1253 assert_eq!(1, ranges.len());
1254 assert_eq!(
1255 message.highlights,
1256 vec![(
1257 ranges[0].clone(),
1258 HighlightStyle {
1259 underline: Some(gpui::UnderlineStyle {
1260 thickness: 1.0.into(),
1261 ..Default::default()
1262 }),
1263 ..Default::default()
1264 }
1265 .into()
1266 ),]
1267 );
1268 }
1269
1270 #[gpui::test]
1271 fn test_render_markdown_with_auto_detect_links_and_additional_formatting(cx: &mut AppContext) {
1272 let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1273 let message = channel::ChannelMessage {
1274 id: ChannelMessageId::Saved(0),
1275 body: "**Here is a link https://zed.dev to zeds website**".to_string(),
1276 timestamp: OffsetDateTime::now_utc(),
1277 sender: Arc::new(client::User {
1278 github_login: "fgh".into(),
1279 avatar_uri: "avatar_fgh".into(),
1280 id: 103,
1281 }),
1282 nonce: 5,
1283 mentions: Vec::new(),
1284 reply_to_message_id: None,
1285 edited_at: None,
1286 };
1287
1288 let message = ChatPanel::render_markdown_with_mentions(
1289 &language_registry,
1290 102,
1291 &message,
1292 UtcOffset::UTC,
1293 cx,
1294 );
1295
1296 // Note that the "'" was replaced with ’ due to smart punctuation.
1297 let (body, ranges) = marked_text_ranges(
1298 "«Here is a link »«https://zed.dev»« to zeds website»",
1299 false,
1300 );
1301 assert_eq!(message.text, body);
1302 assert_eq!(3, ranges.len());
1303 assert_eq!(
1304 message.highlights,
1305 vec![
1306 (
1307 ranges[0].clone(),
1308 HighlightStyle {
1309 font_weight: Some(gpui::FontWeight::BOLD),
1310 ..Default::default()
1311 }
1312 .into()
1313 ),
1314 (
1315 ranges[1].clone(),
1316 HighlightStyle {
1317 font_weight: Some(gpui::FontWeight::BOLD),
1318 underline: Some(gpui::UnderlineStyle {
1319 thickness: 1.0.into(),
1320 ..Default::default()
1321 }),
1322 ..Default::default()
1323 }
1324 .into()
1325 ),
1326 (
1327 ranges[2].clone(),
1328 HighlightStyle {
1329 font_weight: Some(gpui::FontWeight::BOLD),
1330 ..Default::default()
1331 }
1332 .into()
1333 ),
1334 ]
1335 );
1336 }
1337}