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