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