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
291 && self.is_scrolled_to_bottom
292 && let Some((chat, _)) = &self.active_chat
293 {
294 if let Some(channel_id) = self.channel_id(cx) {
295 self.last_acknowledged_message_id = self
296 .channel_store
297 .read(cx)
298 .last_acknowledge_message_id(channel_id);
299 }
300
301 chat.update(cx, |chat, cx| {
302 chat.acknowledge_last_message(cx);
303 });
304 }
305 }
306
307 fn render_replied_to_message(
308 &mut self,
309 message_id: Option<ChannelMessageId>,
310 reply_to_message: &Option<ChannelMessage>,
311 cx: &mut Context<Self>,
312 ) -> impl IntoElement {
313 let reply_to_message = match reply_to_message {
314 None => {
315 return div().child(
316 h_flex()
317 .text_ui_xs(cx)
318 .my_0p5()
319 .px_0p5()
320 .gap_x_1()
321 .rounded_sm()
322 .child(Icon::new(IconName::ReplyArrowRight).color(Color::Muted))
323 .when(reply_to_message.is_none(), |el| {
324 el.child(
325 Label::new("Message has been deleted...")
326 .size(LabelSize::XSmall)
327 .color(Color::Muted),
328 )
329 }),
330 );
331 }
332 Some(val) => val,
333 };
334
335 let user_being_replied_to = reply_to_message.sender.clone();
336 let message_being_replied_to = reply_to_message.clone();
337
338 let message_element_id: ElementId = match message_id {
339 Some(ChannelMessageId::Saved(id)) => ("reply-to-saved-message-container", id).into(),
340 Some(ChannelMessageId::Pending(id)) => {
341 ("reply-to-pending-message-container", id).into()
342 } // This should never happen
343 None => ("composing-reply-container").into(),
344 };
345
346 let current_channel_id = self.channel_id(cx);
347 let reply_to_message_id = reply_to_message.id;
348
349 div().child(
350 h_flex()
351 .id(message_element_id)
352 .text_ui_xs(cx)
353 .my_0p5()
354 .px_0p5()
355 .gap_x_1()
356 .rounded_sm()
357 .overflow_hidden()
358 .hover(|style| style.bg(cx.theme().colors().element_background))
359 .child(Icon::new(IconName::ReplyArrowRight).color(Color::Muted))
360 .child(Avatar::new(user_being_replied_to.avatar_uri.clone()).size(rems(0.7)))
361 .child(
362 Label::new(format!("@{}", user_being_replied_to.github_login))
363 .size(LabelSize::XSmall)
364 .weight(FontWeight::SEMIBOLD)
365 .color(Color::Muted),
366 )
367 .child(
368 div().overflow_y_hidden().child(
369 Label::new(message_being_replied_to.body.replace('\n', " "))
370 .size(LabelSize::XSmall)
371 .color(Color::Default),
372 ),
373 )
374 .cursor(CursorStyle::PointingHand)
375 .tooltip(Tooltip::text("Go to message"))
376 .on_click(cx.listener(move |chat_panel, _, _, cx| {
377 if let Some(channel_id) = current_channel_id {
378 chat_panel
379 .select_channel(channel_id, reply_to_message_id.into(), cx)
380 .detach_and_log_err(cx)
381 }
382 })),
383 )
384 }
385
386 fn render_message(
387 &mut self,
388 ix: usize,
389 window: &mut Window,
390 cx: &mut Context<Self>,
391 ) -> AnyElement {
392 let active_chat = &self.active_chat.as_ref().unwrap().0;
393 let (message, is_continuation_from_previous, is_admin) =
394 active_chat.update(cx, |active_chat, cx| {
395 let is_admin = self
396 .channel_store
397 .read(cx)
398 .is_channel_admin(active_chat.channel_id);
399
400 let last_message = active_chat.message(ix.saturating_sub(1));
401 let this_message = active_chat.message(ix).clone();
402
403 let duration_since_last_message = this_message.timestamp - last_message.timestamp;
404 let is_continuation_from_previous = last_message.sender.id
405 == this_message.sender.id
406 && last_message.id != this_message.id
407 && duration_since_last_message < Duration::from_secs(5 * 60);
408
409 if let ChannelMessageId::Saved(id) = this_message.id
410 && this_message
411 .mentions
412 .iter()
413 .any(|(_, user_id)| Some(*user_id) == self.client.user_id())
414 {
415 active_chat.acknowledge_message(id);
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 && 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().is_some_and(|(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 Ok(())
904 })
905 }
906
907 fn close_reply_preview(&mut self, cx: &mut Context<Self>) {
908 self.message_editor
909 .update(cx, |editor, _| editor.clear_reply_to_message_id());
910 }
911
912 fn cancel_edit_message(&mut self, cx: &mut Context<Self>) {
913 self.message_editor.update(cx, |editor, cx| {
914 // only clear the editor input if we were editing a message
915 if editor.edit_message_id().is_none() {
916 return;
917 }
918
919 editor.clear_edit_message_id();
920
921 let buffer = editor
922 .editor
923 .read(cx)
924 .buffer()
925 .read(cx)
926 .as_singleton()
927 .expect("message editor must be singleton");
928
929 buffer.update(cx, |buffer, cx| buffer.set_text("", cx));
930 });
931 }
932}
933
934impl Render for ChatPanel {
935 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
936 let channel_id = self
937 .active_chat
938 .as_ref()
939 .map(|(c, _)| c.read(cx).channel_id);
940 let message_editor = self.message_editor.read(cx);
941
942 let reply_to_message_id = message_editor.reply_to_message_id();
943 let edit_message_id = message_editor.edit_message_id();
944
945 v_flex()
946 .key_context("ChatPanel")
947 .track_focus(&self.focus_handle)
948 .size_full()
949 .on_action(cx.listener(Self::send))
950 .child(
951 h_flex().child(
952 TabBar::new("chat_header").child(
953 h_flex()
954 .w_full()
955 .h(Tab::container_height(cx))
956 .px_2()
957 .child(Label::new(
958 self.active_chat
959 .as_ref()
960 .and_then(|c| {
961 Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
962 })
963 .unwrap_or("Chat".to_string()),
964 )),
965 ),
966 ),
967 )
968 .child(div().flex_grow().px_2().map(|this| {
969 if self.active_chat.is_some() {
970 this.child(
971 list(
972 self.message_list.clone(),
973 cx.processor(Self::render_message),
974 )
975 .size_full(),
976 )
977 } else {
978 this.child(
979 div()
980 .size_full()
981 .p_4()
982 .child(
983 Label::new("Select a channel to chat in.")
984 .size(LabelSize::Small)
985 .color(Color::Muted),
986 )
987 .child(
988 div().pt_1().w_full().items_center().child(
989 Button::new("toggle-collab", "Open")
990 .full_width()
991 .key_binding(KeyBinding::for_action(
992 &collab_panel::ToggleFocus,
993 window,
994 cx,
995 ))
996 .on_click(|_, window, cx| {
997 window.dispatch_action(
998 collab_panel::ToggleFocus.boxed_clone(),
999 cx,
1000 )
1001 }),
1002 ),
1003 ),
1004 )
1005 }
1006 }))
1007 .when(!self.is_scrolled_to_bottom, |el| {
1008 el.child(div().border_t_1().border_color(cx.theme().colors().border))
1009 })
1010 .when_some(edit_message_id, |el, _| {
1011 el.child(
1012 h_flex()
1013 .px_2()
1014 .text_ui_xs(cx)
1015 .justify_between()
1016 .border_t_1()
1017 .border_color(cx.theme().colors().border)
1018 .bg(cx.theme().colors().background)
1019 .child("Editing message")
1020 .child(
1021 IconButton::new("cancel-edit-message", IconName::Close)
1022 .shape(ui::IconButtonShape::Square)
1023 .tooltip(Tooltip::text("Cancel edit message"))
1024 .on_click(cx.listener(move |this, _, _, cx| {
1025 this.cancel_edit_message(cx);
1026 })),
1027 ),
1028 )
1029 })
1030 .when_some(reply_to_message_id, |el, reply_to_message_id| {
1031 let reply_message = self
1032 .active_chat()
1033 .and_then(|active_chat| {
1034 active_chat
1035 .read(cx)
1036 .find_loaded_message(reply_to_message_id)
1037 })
1038 .cloned();
1039
1040 el.when_some(reply_message, |el, reply_message| {
1041 let user_being_replied_to = reply_message.sender;
1042
1043 el.child(
1044 h_flex()
1045 .when(!self.is_scrolled_to_bottom, |el| {
1046 el.border_t_1().border_color(cx.theme().colors().border)
1047 })
1048 .justify_between()
1049 .overflow_hidden()
1050 .items_start()
1051 .py_1()
1052 .px_2()
1053 .bg(cx.theme().colors().background)
1054 .child(
1055 div().flex_shrink().overflow_hidden().child(
1056 h_flex()
1057 .id(("reply-preview", reply_to_message_id))
1058 .child(Label::new("Replying to ").size(LabelSize::Small))
1059 .child(
1060 Label::new(format!(
1061 "@{}",
1062 user_being_replied_to.github_login
1063 ))
1064 .size(LabelSize::Small)
1065 .weight(FontWeight::BOLD),
1066 )
1067 .when_some(channel_id, |this, channel_id| {
1068 this.cursor_pointer().on_click(cx.listener(
1069 move |chat_panel, _, _, cx| {
1070 chat_panel
1071 .select_channel(
1072 channel_id,
1073 reply_to_message_id.into(),
1074 cx,
1075 )
1076 .detach_and_log_err(cx)
1077 },
1078 ))
1079 }),
1080 ),
1081 )
1082 .child(
1083 IconButton::new("close-reply-preview", IconName::Close)
1084 .shape(ui::IconButtonShape::Square)
1085 .tooltip(Tooltip::text("Close reply"))
1086 .on_click(cx.listener(move |this, _, _, cx| {
1087 this.close_reply_preview(cx);
1088 })),
1089 ),
1090 )
1091 })
1092 })
1093 .children(
1094 Some(
1095 h_flex()
1096 .p_2()
1097 .on_action(cx.listener(|this, _: &actions::Cancel, _, cx| {
1098 this.cancel_edit_message(cx);
1099 this.close_reply_preview(cx);
1100 }))
1101 .map(|el| el.child(self.message_editor.clone())),
1102 )
1103 .filter(|_| self.active_chat.is_some()),
1104 )
1105 .into_any()
1106 }
1107}
1108
1109impl Focusable for ChatPanel {
1110 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1111 if self.active_chat.is_some() {
1112 self.message_editor.read(cx).focus_handle(cx)
1113 } else {
1114 self.focus_handle.clone()
1115 }
1116 }
1117}
1118
1119impl Panel for ChatPanel {
1120 fn position(&self, _: &Window, cx: &App) -> DockPosition {
1121 ChatPanelSettings::get_global(cx).dock
1122 }
1123
1124 fn position_is_valid(&self, position: DockPosition) -> bool {
1125 matches!(position, DockPosition::Left | DockPosition::Right)
1126 }
1127
1128 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
1129 settings::update_settings_file::<ChatPanelSettings>(
1130 self.fs.clone(),
1131 cx,
1132 move |settings, _| settings.dock = Some(position),
1133 );
1134 }
1135
1136 fn size(&self, _: &Window, cx: &App) -> Pixels {
1137 self.width
1138 .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
1139 }
1140
1141 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
1142 self.width = size;
1143 self.serialize(cx);
1144 cx.notify();
1145 }
1146
1147 fn set_active(&mut self, active: bool, _: &mut Window, cx: &mut Context<Self>) {
1148 self.active = active;
1149 if active {
1150 self.acknowledge_last_message(cx);
1151 }
1152 }
1153
1154 fn persistent_name() -> &'static str {
1155 "ChatPanel"
1156 }
1157
1158 fn icon(&self, _window: &Window, cx: &App) -> Option<ui::IconName> {
1159 self.enabled(cx).then(|| ui::IconName::Chat)
1160 }
1161
1162 fn icon_tooltip(&self, _: &Window, _: &App) -> Option<&'static str> {
1163 Some("Chat Panel")
1164 }
1165
1166 fn toggle_action(&self) -> Box<dyn gpui::Action> {
1167 Box::new(ToggleFocus)
1168 }
1169
1170 fn starts_open(&self, _: &Window, cx: &App) -> bool {
1171 ActiveCall::global(cx)
1172 .read(cx)
1173 .room()
1174 .is_some_and(|room| room.read(cx).contains_guests())
1175 }
1176
1177 fn activation_priority(&self) -> u32 {
1178 7
1179 }
1180
1181 fn enabled(&self, cx: &App) -> bool {
1182 match ChatPanelSettings::get_global(cx).button {
1183 ChatPanelButton::Never => false,
1184 ChatPanelButton::Always => true,
1185 ChatPanelButton::WhenInCall => {
1186 let is_in_call = ActiveCall::global(cx)
1187 .read(cx)
1188 .room()
1189 .is_some_and(|room| room.read(cx).contains_guests());
1190
1191 self.active || is_in_call
1192 }
1193 }
1194 }
1195}
1196
1197impl EventEmitter<PanelEvent> for ChatPanel {}
1198
1199#[cfg(test)]
1200mod tests {
1201 use super::*;
1202 use gpui::HighlightStyle;
1203 use pretty_assertions::assert_eq;
1204 use rich_text::Highlight;
1205 use time::OffsetDateTime;
1206 use util::test::marked_text_ranges;
1207
1208 #[gpui::test]
1209 fn test_render_markdown_with_mentions(cx: &mut App) {
1210 let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1211 let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
1212 let message = channel::ChannelMessage {
1213 id: ChannelMessageId::Saved(0),
1214 body,
1215 timestamp: OffsetDateTime::now_utc(),
1216 sender: Arc::new(client::User {
1217 github_login: "fgh".into(),
1218 avatar_uri: "avatar_fgh".into(),
1219 id: 103,
1220 name: None,
1221 }),
1222 nonce: 5,
1223 mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
1224 reply_to_message_id: None,
1225 edited_at: None,
1226 };
1227
1228 let message = ChatPanel::render_markdown_with_mentions(
1229 &language_registry,
1230 102,
1231 &message,
1232 UtcOffset::UTC,
1233 cx,
1234 );
1235
1236 // Note that the "'" was replaced with ’ due to smart punctuation.
1237 let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
1238 assert_eq!(message.text, body);
1239 assert_eq!(
1240 message.highlights,
1241 vec![
1242 (
1243 ranges[0].clone(),
1244 HighlightStyle {
1245 font_style: Some(gpui::FontStyle::Italic),
1246 ..Default::default()
1247 }
1248 .into()
1249 ),
1250 (ranges[1].clone(), Highlight::Mention),
1251 (
1252 ranges[2].clone(),
1253 HighlightStyle {
1254 font_weight: Some(gpui::FontWeight::BOLD),
1255 ..Default::default()
1256 }
1257 .into()
1258 ),
1259 (ranges[3].clone(), Highlight::SelfMention)
1260 ]
1261 );
1262 }
1263
1264 #[gpui::test]
1265 fn test_render_markdown_with_auto_detect_links(cx: &mut App) {
1266 let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1267 let message = channel::ChannelMessage {
1268 id: ChannelMessageId::Saved(0),
1269 body: "Here is a link https://zed.dev to zeds website".to_string(),
1270 timestamp: OffsetDateTime::now_utc(),
1271 sender: Arc::new(client::User {
1272 github_login: "fgh".into(),
1273 avatar_uri: "avatar_fgh".into(),
1274 id: 103,
1275 name: None,
1276 }),
1277 nonce: 5,
1278 mentions: Vec::new(),
1279 reply_to_message_id: None,
1280 edited_at: None,
1281 };
1282
1283 let message = ChatPanel::render_markdown_with_mentions(
1284 &language_registry,
1285 102,
1286 &message,
1287 UtcOffset::UTC,
1288 cx,
1289 );
1290
1291 // Note that the "'" was replaced with ’ due to smart punctuation.
1292 let (body, ranges) =
1293 marked_text_ranges("Here is a link «https://zed.dev» to zeds website", false);
1294 assert_eq!(message.text, body);
1295 assert_eq!(1, ranges.len());
1296 assert_eq!(
1297 message.highlights,
1298 vec![(
1299 ranges[0].clone(),
1300 HighlightStyle {
1301 underline: Some(gpui::UnderlineStyle {
1302 thickness: 1.0.into(),
1303 ..Default::default()
1304 }),
1305 ..Default::default()
1306 }
1307 .into()
1308 ),]
1309 );
1310 }
1311
1312 #[gpui::test]
1313 fn test_render_markdown_with_auto_detect_links_and_additional_formatting(cx: &mut App) {
1314 let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1315 let message = channel::ChannelMessage {
1316 id: ChannelMessageId::Saved(0),
1317 body: "**Here is a link https://zed.dev to zeds website**".to_string(),
1318 timestamp: OffsetDateTime::now_utc(),
1319 sender: Arc::new(client::User {
1320 github_login: "fgh".into(),
1321 avatar_uri: "avatar_fgh".into(),
1322 id: 103,
1323 name: None,
1324 }),
1325 nonce: 5,
1326 mentions: Vec::new(),
1327 reply_to_message_id: None,
1328 edited_at: None,
1329 };
1330
1331 let message = ChatPanel::render_markdown_with_mentions(
1332 &language_registry,
1333 102,
1334 &message,
1335 UtcOffset::UTC,
1336 cx,
1337 );
1338
1339 // Note that the "'" was replaced with ’ due to smart punctuation.
1340 let (body, ranges) = marked_text_ranges(
1341 "«Here is a link »«https://zed.dev»« to zeds website»",
1342 false,
1343 );
1344 assert_eq!(message.text, body);
1345 assert_eq!(3, ranges.len());
1346 assert_eq!(
1347 message.highlights,
1348 vec![
1349 (
1350 ranges[0].clone(),
1351 HighlightStyle {
1352 font_weight: Some(gpui::FontWeight::BOLD),
1353 ..Default::default()
1354 }
1355 .into()
1356 ),
1357 (
1358 ranges[1].clone(),
1359 HighlightStyle {
1360 font_weight: Some(gpui::FontWeight::BOLD),
1361 underline: Some(gpui::UnderlineStyle {
1362 thickness: 1.0.into(),
1363 ..Default::default()
1364 }),
1365 ..Default::default()
1366 }
1367 .into()
1368 ),
1369 (
1370 ranges[2].clone(),
1371 HighlightStyle {
1372 font_weight: Some(gpui::FontWeight::BOLD),
1373 ..Default::default()
1374 }
1375 .into()
1376 ),
1377 ]
1378 );
1379 }
1380}