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, CursorStyle,
11 DismissEvent, ElementId, EventEmitter, FocusHandle, FocusableView, FontStyle, FontWeight,
12 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 .when(can_delete_message, move |menu| {
633 menu.entry(
634 "Delete message",
635 None,
636 cx.handler_for(&this, move |this, cx| this.remove_message(message_id, cx)),
637 )
638 })
639 })
640 };
641 this.update(cx, |this, cx| {
642 let subscription = cx.subscribe(&menu, |this: &mut Self, _, _: &DismissEvent, _| {
643 this.open_context_menu = None;
644 });
645 this.open_context_menu = Some((message_id, subscription));
646 });
647 menu
648 }
649
650 fn render_markdown_with_mentions(
651 language_registry: &Arc<LanguageRegistry>,
652 current_user_id: u64,
653 message: &channel::ChannelMessage,
654 ) -> RichText {
655 let mentions = message
656 .mentions
657 .iter()
658 .map(|(range, user_id)| rich_text::Mention {
659 range: range.clone(),
660 is_self_mention: *user_id == current_user_id,
661 })
662 .collect::<Vec<_>>();
663
664 rich_text::render_rich_text(message.body.clone(), &mentions, language_registry, None)
665 }
666
667 fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
668 if let Some((chat, _)) = self.active_chat.as_ref() {
669 let message = self
670 .message_editor
671 .update(cx, |editor, cx| editor.take_message(cx));
672
673 if let Some(task) = chat
674 .update(cx, |chat, cx| chat.send_message(message, cx))
675 .log_err()
676 {
677 task.detach();
678 }
679 }
680 }
681
682 fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
683 if let Some((chat, _)) = self.active_chat.as_ref() {
684 chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
685 }
686 }
687
688 fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
689 if let Some((chat, _)) = self.active_chat.as_ref() {
690 chat.update(cx, |channel, cx| {
691 if let Some(task) = channel.load_more_messages(cx) {
692 task.detach();
693 }
694 })
695 }
696 }
697
698 pub fn select_channel(
699 &mut self,
700 selected_channel_id: u64,
701 scroll_to_message_id: Option<u64>,
702 cx: &mut ViewContext<ChatPanel>,
703 ) -> Task<Result<()>> {
704 let open_chat = self
705 .active_chat
706 .as_ref()
707 .and_then(|(chat, _)| {
708 (chat.read(cx).channel_id == selected_channel_id)
709 .then(|| Task::ready(anyhow::Ok(chat.clone())))
710 })
711 .unwrap_or_else(|| {
712 self.channel_store.update(cx, |store, cx| {
713 store.open_channel_chat(selected_channel_id, cx)
714 })
715 });
716
717 cx.spawn(|this, mut cx| async move {
718 let chat = open_chat.await?;
719 let highlight_message_id = scroll_to_message_id;
720 let scroll_to_message_id = this.update(&mut cx, |this, cx| {
721 this.set_active_chat(chat.clone(), cx);
722
723 scroll_to_message_id.or_else(|| this.last_acknowledged_message_id)
724 })?;
725
726 if let Some(message_id) = scroll_to_message_id {
727 if let Some(item_ix) =
728 ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
729 .await
730 {
731 this.update(&mut cx, |this, cx| {
732 if let Some(highlight_message_id) = highlight_message_id {
733 let task = cx.spawn({
734 |this, mut cx| async move {
735 cx.background_executor().timer(Duration::from_secs(2)).await;
736 this.update(&mut cx, |this, cx| {
737 this.highlighted_message.take();
738 cx.notify();
739 })
740 .ok();
741 }
742 });
743
744 this.highlighted_message = Some((highlight_message_id, task));
745 }
746
747 if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
748 this.message_list.scroll_to(ListOffset {
749 item_ix,
750 offset_in_item: px(0.0),
751 });
752 cx.notify();
753 }
754 })?;
755 }
756 }
757
758 Ok(())
759 })
760 }
761
762 fn close_reply_preview(&mut self, _: &CloseReplyPreview, cx: &mut ViewContext<Self>) {
763 self.message_editor
764 .update(cx, |editor, _| editor.clear_reply_to_message_id());
765 }
766}
767
768impl Render for ChatPanel {
769 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
770 let reply_to_message_id = self.message_editor.read(cx).reply_to_message_id();
771
772 v_flex()
773 .key_context("ChatPanel")
774 .track_focus(&self.focus_handle)
775 .size_full()
776 .on_action(cx.listener(Self::send))
777 .child(
778 h_flex().z_index(1).child(
779 TabBar::new("chat_header").child(
780 h_flex()
781 .w_full()
782 .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
783 .px_2()
784 .child(Label::new(
785 self.active_chat
786 .as_ref()
787 .and_then(|c| {
788 Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
789 })
790 .unwrap_or("Chat".to_string()),
791 )),
792 ),
793 ),
794 )
795 .child(div().flex_grow().px_2().map(|this| {
796 if self.active_chat.is_some() {
797 this.child(list(self.message_list.clone()).size_full())
798 } else {
799 this.child(
800 div()
801 .size_full()
802 .p_4()
803 .child(
804 Label::new("Select a channel to chat in.")
805 .size(LabelSize::Small)
806 .color(Color::Muted),
807 )
808 .child(
809 div().pt_1().w_full().items_center().child(
810 Button::new("toggle-collab", "Open")
811 .full_width()
812 .key_binding(KeyBinding::for_action(
813 &collab_panel::ToggleFocus,
814 cx,
815 ))
816 .on_click(|_, cx| {
817 cx.dispatch_action(
818 collab_panel::ToggleFocus.boxed_clone(),
819 )
820 }),
821 ),
822 ),
823 )
824 }
825 }))
826 .when_some(reply_to_message_id, |el, reply_to_message_id| {
827 let reply_message = self
828 .active_chat()
829 .map(|active_chat| {
830 active_chat.read(cx).messages().iter().find_map(|m| {
831 if m.id == ChannelMessageId::Saved(reply_to_message_id) {
832 Some(m)
833 } else {
834 None
835 }
836 })
837 })
838 .flatten()
839 .cloned();
840
841 el.when_some(reply_message, |el, reply_message| {
842 el.child(
843 h_flex()
844 .when(!self.is_scrolled_to_bottom, |el| {
845 el.border_t_1().border_color(cx.theme().colors().border)
846 })
847 .justify_between()
848 .overflow_hidden()
849 .items_start()
850 .py_1()
851 .px_2()
852 .bg(cx.theme().colors().background)
853 .child(
854 div().flex_shrink().overflow_hidden().child(
855 self.render_replied_to_message(None, &reply_message, cx),
856 ),
857 )
858 .child(
859 IconButton::new("close-reply-preview", IconName::Close)
860 .shape(ui::IconButtonShape::Square)
861 .tooltip(|cx| {
862 Tooltip::for_action(
863 "Close reply preview",
864 &CloseReplyPreview,
865 cx,
866 )
867 })
868 .on_click(cx.listener(move |_, _, cx| {
869 cx.dispatch_action(CloseReplyPreview.boxed_clone())
870 })),
871 ),
872 )
873 })
874 })
875 .children(
876 Some(
877 h_flex()
878 .key_context("MessageEditor")
879 .on_action(cx.listener(ChatPanel::close_reply_preview))
880 .when(
881 !self.is_scrolled_to_bottom && reply_to_message_id.is_none(),
882 |el| el.border_t_1().border_color(cx.theme().colors().border),
883 )
884 .p_2()
885 .map(|el| el.child(self.message_editor.clone())),
886 )
887 .filter(|_| self.active_chat.is_some()),
888 )
889 .into_any()
890 }
891}
892
893impl FocusableView for ChatPanel {
894 fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
895 if self.active_chat.is_some() {
896 self.message_editor.read(cx).focus_handle(cx)
897 } else {
898 self.focus_handle.clone()
899 }
900 }
901}
902
903impl Panel for ChatPanel {
904 fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
905 ChatPanelSettings::get_global(cx).dock
906 }
907
908 fn position_is_valid(&self, position: DockPosition) -> bool {
909 matches!(position, DockPosition::Left | DockPosition::Right)
910 }
911
912 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
913 settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
914 settings.dock = Some(position)
915 });
916 }
917
918 fn size(&self, cx: &gpui::WindowContext) -> Pixels {
919 self.width
920 .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
921 }
922
923 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
924 self.width = size;
925 self.serialize(cx);
926 cx.notify();
927 }
928
929 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
930 self.active = active;
931 if active {
932 self.acknowledge_last_message(cx);
933 }
934 }
935
936 fn persistent_name() -> &'static str {
937 "ChatPanel"
938 }
939
940 fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
941 Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
942 }
943
944 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
945 Some("Chat Panel")
946 }
947
948 fn toggle_action(&self) -> Box<dyn gpui::Action> {
949 Box::new(ToggleFocus)
950 }
951
952 fn starts_open(&self, cx: &WindowContext) -> bool {
953 ActiveCall::global(cx)
954 .read(cx)
955 .room()
956 .is_some_and(|room| room.read(cx).contains_guests())
957 }
958}
959
960impl EventEmitter<PanelEvent> for ChatPanel {}
961
962fn is_12_hour_clock(locale: String) -> bool {
963 [
964 "es-MX", "es-CO", "es-SV", "es-NI",
965 "es-HN", // Mexico, Colombia, El Salvador, Nicaragua, Honduras
966 "en-US", "en-CA", "en-AU", "en-NZ", // U.S, Canada, Australia, New Zealand
967 "ar-SA", "ar-EG", "ar-JO", // Saudi Arabia, Egypt, Jordan
968 "en-IN", "hi-IN", // India, Hindu
969 "en-PK", "ur-PK", // Pakistan, Urdu
970 "en-PH", "fil-PH", // Philippines, Filipino
971 "bn-BD", "ccp-BD", // Bangladesh, Chakma
972 "en-IE", "ga-IE", // Ireland, Irish
973 "en-MY", "ms-MY", // Malaysia, Malay
974 ]
975 .contains(&locale.as_str())
976}
977
978fn format_timestamp(
979 reference: OffsetDateTime,
980 timestamp: OffsetDateTime,
981 timezone: UtcOffset,
982 locale: Option<String>,
983) -> String {
984 let locale = match locale {
985 Some(locale) => locale,
986 None => sys_locale::get_locale().unwrap_or_else(|| String::from("en-US")),
987 };
988 let timestamp_local = timestamp.to_offset(timezone);
989 let timestamp_local_hour = timestamp_local.hour();
990 let timestamp_local_minute = timestamp_local.minute();
991
992 let (hour, meridiem) = if is_12_hour_clock(locale) {
993 let meridiem = if timestamp_local_hour >= 12 {
994 "pm"
995 } else {
996 "am"
997 };
998
999 let hour_12 = match timestamp_local_hour {
1000 0 => 12, // Midnight
1001 13..=23 => timestamp_local_hour - 12, // PM hours
1002 _ => timestamp_local_hour, // AM hours
1003 };
1004
1005 (hour_12, Some(meridiem))
1006 } else {
1007 (timestamp_local_hour, None)
1008 };
1009
1010 let formatted_time = match meridiem {
1011 Some(meridiem) => format!("{:02}:{:02} {}", hour, timestamp_local_minute, meridiem),
1012 None => format!("{:02}:{:02}", hour, timestamp_local_minute),
1013 };
1014
1015 let reference_local = reference.to_offset(timezone);
1016 let reference_local_date = reference_local.date();
1017 let timestamp_local_date = timestamp_local.date();
1018
1019 if timestamp_local_date == reference_local_date {
1020 return formatted_time;
1021 }
1022
1023 if reference_local_date.previous_day() == Some(timestamp_local_date) {
1024 return format!("yesterday at {}", formatted_time);
1025 }
1026
1027 match meridiem {
1028 Some(_) => format!(
1029 "{:02}/{:02}/{}",
1030 timestamp_local_date.month() as u32,
1031 timestamp_local_date.day(),
1032 timestamp_local_date.year()
1033 ),
1034 None => format!(
1035 "{:02}/{:02}/{}",
1036 timestamp_local_date.day(),
1037 timestamp_local_date.month() as u32,
1038 timestamp_local_date.year()
1039 ),
1040 }
1041}
1042
1043#[cfg(test)]
1044mod tests {
1045 use super::*;
1046 use gpui::HighlightStyle;
1047 use pretty_assertions::assert_eq;
1048 use rich_text::Highlight;
1049 use time::{Date, OffsetDateTime, Time, UtcOffset};
1050 use util::test::marked_text_ranges;
1051
1052 #[gpui::test]
1053 fn test_render_markdown_with_mentions() {
1054 let language_registry = Arc::new(LanguageRegistry::test());
1055 let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
1056 let message = channel::ChannelMessage {
1057 id: ChannelMessageId::Saved(0),
1058 body,
1059 timestamp: OffsetDateTime::now_utc(),
1060 sender: Arc::new(client::User {
1061 github_login: "fgh".into(),
1062 avatar_uri: "avatar_fgh".into(),
1063 id: 103,
1064 }),
1065 nonce: 5,
1066 mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
1067 reply_to_message_id: None,
1068 };
1069
1070 let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
1071
1072 // Note that the "'" was replaced with ’ due to smart punctuation.
1073 let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
1074 assert_eq!(message.text, body);
1075 assert_eq!(
1076 message.highlights,
1077 vec![
1078 (
1079 ranges[0].clone(),
1080 HighlightStyle {
1081 font_style: Some(gpui::FontStyle::Italic),
1082 ..Default::default()
1083 }
1084 .into()
1085 ),
1086 (ranges[1].clone(), Highlight::Mention),
1087 (
1088 ranges[2].clone(),
1089 HighlightStyle {
1090 font_weight: Some(gpui::FontWeight::BOLD),
1091 ..Default::default()
1092 }
1093 .into()
1094 ),
1095 (ranges[3].clone(), Highlight::SelfMention)
1096 ]
1097 );
1098 }
1099
1100 #[gpui::test]
1101 fn test_render_markdown_with_auto_detect_links() {
1102 let language_registry = Arc::new(LanguageRegistry::test());
1103 let message = channel::ChannelMessage {
1104 id: ChannelMessageId::Saved(0),
1105 body: "Here is a link https://zed.dev to zeds website".to_string(),
1106 timestamp: OffsetDateTime::now_utc(),
1107 sender: Arc::new(client::User {
1108 github_login: "fgh".into(),
1109 avatar_uri: "avatar_fgh".into(),
1110 id: 103,
1111 }),
1112 nonce: 5,
1113 mentions: Vec::new(),
1114 reply_to_message_id: None,
1115 };
1116
1117 let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
1118
1119 // Note that the "'" was replaced with ’ due to smart punctuation.
1120 let (body, ranges) =
1121 marked_text_ranges("Here is a link «https://zed.dev» to zeds website", false);
1122 assert_eq!(message.text, body);
1123 assert_eq!(1, ranges.len());
1124 assert_eq!(
1125 message.highlights,
1126 vec![(
1127 ranges[0].clone(),
1128 HighlightStyle {
1129 underline: Some(gpui::UnderlineStyle {
1130 thickness: 1.0.into(),
1131 ..Default::default()
1132 }),
1133 ..Default::default()
1134 }
1135 .into()
1136 ),]
1137 );
1138 }
1139
1140 #[gpui::test]
1141 fn test_render_markdown_with_auto_detect_links_and_additional_formatting() {
1142 let language_registry = Arc::new(LanguageRegistry::test());
1143 let message = channel::ChannelMessage {
1144 id: ChannelMessageId::Saved(0),
1145 body: "**Here is a link https://zed.dev to zeds website**".to_string(),
1146 timestamp: OffsetDateTime::now_utc(),
1147 sender: Arc::new(client::User {
1148 github_login: "fgh".into(),
1149 avatar_uri: "avatar_fgh".into(),
1150 id: 103,
1151 }),
1152 nonce: 5,
1153 mentions: Vec::new(),
1154 reply_to_message_id: None,
1155 };
1156
1157 let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
1158
1159 // Note that the "'" was replaced with ’ due to smart punctuation.
1160 let (body, ranges) = marked_text_ranges(
1161 "«Here is a link »«https://zed.dev»« to zeds website»",
1162 false,
1163 );
1164 assert_eq!(message.text, body);
1165 assert_eq!(3, ranges.len());
1166 assert_eq!(
1167 message.highlights,
1168 vec![
1169 (
1170 ranges[0].clone(),
1171 HighlightStyle {
1172 font_weight: Some(gpui::FontWeight::BOLD),
1173 ..Default::default()
1174 }
1175 .into()
1176 ),
1177 (
1178 ranges[1].clone(),
1179 HighlightStyle {
1180 font_weight: Some(gpui::FontWeight::BOLD),
1181 underline: Some(gpui::UnderlineStyle {
1182 thickness: 1.0.into(),
1183 ..Default::default()
1184 }),
1185 ..Default::default()
1186 }
1187 .into()
1188 ),
1189 (
1190 ranges[2].clone(),
1191 HighlightStyle {
1192 font_weight: Some(gpui::FontWeight::BOLD),
1193 ..Default::default()
1194 }
1195 .into()
1196 ),
1197 ]
1198 );
1199 }
1200
1201 #[test]
1202 fn test_format_locale() {
1203 let reference = create_offset_datetime(1990, 4, 12, 16, 45, 0);
1204 let timestamp = create_offset_datetime(1990, 4, 12, 15, 30, 0);
1205
1206 assert_eq!(
1207 format_timestamp(
1208 reference,
1209 timestamp,
1210 test_timezone(),
1211 Some(String::from("en-GB"))
1212 ),
1213 "15:30"
1214 );
1215 }
1216
1217 #[test]
1218 fn test_format_today() {
1219 let reference = create_offset_datetime(1990, 4, 12, 16, 45, 0);
1220 let timestamp = create_offset_datetime(1990, 4, 12, 15, 30, 0);
1221
1222 assert_eq!(
1223 format_timestamp(
1224 reference,
1225 timestamp,
1226 test_timezone(),
1227 Some(String::from("en-US"))
1228 ),
1229 "03:30 pm"
1230 );
1231 }
1232
1233 #[test]
1234 fn test_format_yesterday() {
1235 let reference = create_offset_datetime(1990, 4, 12, 10, 30, 0);
1236 let timestamp = create_offset_datetime(1990, 4, 11, 9, 0, 0);
1237
1238 assert_eq!(
1239 format_timestamp(
1240 reference,
1241 timestamp,
1242 test_timezone(),
1243 Some(String::from("en-US"))
1244 ),
1245 "yesterday at 09:00 am"
1246 );
1247 }
1248
1249 #[test]
1250 fn test_format_yesterday_less_than_24_hours_ago() {
1251 let reference = create_offset_datetime(1990, 4, 12, 19, 59, 0);
1252 let timestamp = create_offset_datetime(1990, 4, 11, 20, 0, 0);
1253
1254 assert_eq!(
1255 format_timestamp(
1256 reference,
1257 timestamp,
1258 test_timezone(),
1259 Some(String::from("en-US"))
1260 ),
1261 "yesterday at 08:00 pm"
1262 );
1263 }
1264
1265 #[test]
1266 fn test_format_yesterday_more_than_24_hours_ago() {
1267 let reference = create_offset_datetime(1990, 4, 12, 19, 59, 0);
1268 let timestamp = create_offset_datetime(1990, 4, 11, 18, 0, 0);
1269
1270 assert_eq!(
1271 format_timestamp(
1272 reference,
1273 timestamp,
1274 test_timezone(),
1275 Some(String::from("en-US"))
1276 ),
1277 "yesterday at 06:00 pm"
1278 );
1279 }
1280
1281 #[test]
1282 fn test_format_yesterday_over_midnight() {
1283 let reference = create_offset_datetime(1990, 4, 12, 0, 5, 0);
1284 let timestamp = create_offset_datetime(1990, 4, 11, 23, 55, 0);
1285
1286 assert_eq!(
1287 format_timestamp(
1288 reference,
1289 timestamp,
1290 test_timezone(),
1291 Some(String::from("en-US"))
1292 ),
1293 "yesterday at 11:55 pm"
1294 );
1295 }
1296
1297 #[test]
1298 fn test_format_yesterday_over_month() {
1299 let reference = create_offset_datetime(1990, 4, 2, 9, 0, 0);
1300 let timestamp = create_offset_datetime(1990, 4, 1, 20, 0, 0);
1301
1302 assert_eq!(
1303 format_timestamp(
1304 reference,
1305 timestamp,
1306 test_timezone(),
1307 Some(String::from("en-US"))
1308 ),
1309 "yesterday at 08:00 pm"
1310 );
1311 }
1312
1313 #[test]
1314 fn test_format_before_yesterday() {
1315 let reference = create_offset_datetime(1990, 4, 12, 10, 30, 0);
1316 let timestamp = create_offset_datetime(1990, 4, 10, 20, 20, 0);
1317
1318 assert_eq!(
1319 format_timestamp(
1320 reference,
1321 timestamp,
1322 test_timezone(),
1323 Some(String::from("en-US"))
1324 ),
1325 "04/10/1990"
1326 );
1327 }
1328
1329 fn test_timezone() -> UtcOffset {
1330 UtcOffset::from_hms(0, 0, 0).expect("Valid timezone offset")
1331 }
1332
1333 fn create_offset_datetime(
1334 year: i32,
1335 month: u8,
1336 day: u8,
1337 hour: u8,
1338 minute: u8,
1339 second: u8,
1340 ) -> OffsetDateTime {
1341 let date =
1342 Date::from_calendar_date(year, time::Month::try_from(month).unwrap(), day).unwrap();
1343 let time = Time::from_hms(hour, minute, second).unwrap();
1344 date.with_time(time).assume_utc() // Assume UTC for simplicity
1345 }
1346}