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