1use crate::{channel_view::ChannelView, is_channels_feature_enabled, ChatPanelSettings};
2use anyhow::Result;
3use call::ActiveCall;
4use channel::{ChannelChat, ChannelChatEvent, 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, AnyElement, AppContext, AsyncWindowContext, ClickEvent,
11 ElementId, EventEmitter, FocusableView, ListOffset, ListScrollEvent, ListState, Model, Render,
12 Subscription, Task, View, ViewContext, VisualContext, WeakView,
13};
14use language::LanguageRegistry;
15use menu::Confirm;
16use message_editor::MessageEditor;
17use project::Fs;
18use rich_text::RichText;
19use serde::{Deserialize, Serialize};
20use settings::{Settings, SettingsStore};
21use std::sync::Arc;
22use time::{OffsetDateTime, UtcOffset};
23use ui::{prelude::*, Avatar, Button, Icon, IconButton, Label, TabBar, Tooltip};
24use util::{ResultExt, TryFutureExt};
25use workspace::{
26 dock::{DockPosition, Panel, PanelEvent},
27 Workspace,
28};
29
30mod message_editor;
31
32const MESSAGE_LOADING_THRESHOLD: usize = 50;
33const CHAT_PANEL_KEY: &'static str = "ChatPanel";
34
35pub fn init(cx: &mut AppContext) {
36 cx.observe_new_views(|workspace: &mut Workspace, _| {
37 workspace.register_action(|workspace, _: &ToggleFocus, cx| {
38 workspace.toggle_panel_focus::<ChatPanel>(cx);
39 });
40 })
41 .detach();
42}
43
44pub struct ChatPanel {
45 client: Arc<Client>,
46 channel_store: Model<ChannelStore>,
47 languages: Arc<LanguageRegistry>,
48 message_list: ListState,
49 active_chat: Option<(Model<ChannelChat>, Subscription)>,
50 message_editor: View<MessageEditor>,
51 local_timezone: UtcOffset,
52 fs: Arc<dyn Fs>,
53 width: Option<Pixels>,
54 active: bool,
55 pending_serialization: Task<Option<()>>,
56 subscriptions: Vec<gpui::Subscription>,
57 workspace: WeakView<Workspace>,
58 is_scrolled_to_bottom: bool,
59 markdown_data: HashMap<ChannelMessageId, RichText>,
60}
61
62#[derive(Serialize, Deserialize)]
63struct SerializedChatPanel {
64 width: Option<Pixels>,
65}
66
67#[derive(Debug)]
68pub enum Event {
69 DockPositionChanged,
70 Focus,
71 Dismissed,
72}
73
74actions!(chat_panel, [ToggleFocus]);
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 let workspace_handle = workspace.weak_handle();
93
94 cx.new_view(|cx: &mut ViewContext<Self>| {
95 let view = cx.view().downgrade();
96 let message_list =
97 ListState::new(0, gpui::ListAlignment::Bottom, px(1000.), move |ix, cx| {
98 if let Some(view) = view.upgrade() {
99 view.update(cx, |view, cx| {
100 view.render_message(ix, cx).into_any_element()
101 })
102 } else {
103 div().into_any()
104 }
105 });
106
107 message_list.set_scroll_handler(cx.listener(|this, event: &ListScrollEvent, cx| {
108 if event.visible_range.start < MESSAGE_LOADING_THRESHOLD {
109 this.load_more_messages(cx);
110 }
111 this.is_scrolled_to_bottom = event.visible_range.end == event.count;
112 }));
113
114 let mut this = Self {
115 fs,
116 client,
117 channel_store,
118 languages,
119 message_list,
120 active_chat: Default::default(),
121 pending_serialization: Task::ready(None),
122 message_editor: input_editor,
123 local_timezone: cx.local_timezone(),
124 subscriptions: Vec::new(),
125 workspace: workspace_handle,
126 is_scrolled_to_bottom: true,
127 active: false,
128 width: None,
129 markdown_data: Default::default(),
130 };
131
132 let mut old_dock_position = this.position(cx);
133 this.subscriptions.push(cx.observe_global::<SettingsStore>(
134 move |this: &mut Self, cx| {
135 let new_dock_position = this.position(cx);
136 if new_dock_position != old_dock_position {
137 old_dock_position = new_dock_position;
138 cx.emit(Event::DockPositionChanged);
139 }
140 cx.notify();
141 },
142 ));
143
144 this
145 })
146 }
147
148 pub fn is_scrolled_to_bottom(&self) -> bool {
149 self.is_scrolled_to_bottom
150 }
151
152 pub fn active_chat(&self) -> Option<Model<ChannelChat>> {
153 self.active_chat.as_ref().map(|(chat, _)| chat.clone())
154 }
155
156 pub fn load(
157 workspace: WeakView<Workspace>,
158 cx: AsyncWindowContext,
159 ) -> Task<Result<View<Self>>> {
160 cx.spawn(|mut cx| async move {
161 let serialized_panel = if let Some(panel) = cx
162 .background_executor()
163 .spawn(async move { KEY_VALUE_STORE.read_kvp(CHAT_PANEL_KEY) })
164 .await
165 .log_err()
166 .flatten()
167 {
168 Some(serde_json::from_str::<SerializedChatPanel>(&panel)?)
169 } else {
170 None
171 };
172
173 workspace.update(&mut cx, |workspace, cx| {
174 let panel = Self::new(workspace, cx);
175 if let Some(serialized_panel) = serialized_panel {
176 panel.update(cx, |panel, cx| {
177 panel.width = serialized_panel.width;
178 cx.notify();
179 });
180 }
181 panel
182 })
183 })
184 }
185
186 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
187 let width = self.width;
188 self.pending_serialization = cx.background_executor().spawn(
189 async move {
190 KEY_VALUE_STORE
191 .write_kvp(
192 CHAT_PANEL_KEY.into(),
193 serde_json::to_string(&SerializedChatPanel { width })?,
194 )
195 .await?;
196 anyhow::Ok(())
197 }
198 .log_err(),
199 );
200 }
201
202 fn set_active_chat(&mut self, chat: Model<ChannelChat>, cx: &mut ViewContext<Self>) {
203 if self.active_chat.as_ref().map(|e| &e.0) != Some(&chat) {
204 let channel_id = chat.read(cx).channel_id;
205 {
206 self.markdown_data.clear();
207 let chat = chat.read(cx);
208 self.message_list.reset(chat.message_count());
209
210 let channel_name = chat.channel(cx).map(|channel| channel.name.clone());
211 self.message_editor.update(cx, |editor, cx| {
212 editor.set_channel(channel_id, channel_name, cx);
213 });
214 };
215 let subscription = cx.subscribe(&chat, Self::channel_did_change);
216 self.active_chat = Some((chat, subscription));
217 self.acknowledge_last_message(cx);
218 cx.notify();
219 }
220 }
221
222 fn channel_did_change(
223 &mut self,
224 _: Model<ChannelChat>,
225 event: &ChannelChatEvent,
226 cx: &mut ViewContext<Self>,
227 ) {
228 match event {
229 ChannelChatEvent::MessagesUpdated {
230 old_range,
231 new_count,
232 } => {
233 self.message_list.splice(old_range.clone(), *new_count);
234 if self.active {
235 self.acknowledge_last_message(cx);
236 }
237 }
238 ChannelChatEvent::NewMessage {
239 channel_id,
240 message_id,
241 } => {
242 if !self.active {
243 self.channel_store.update(cx, |store, cx| {
244 store.new_message(*channel_id, *message_id, cx)
245 })
246 }
247 }
248 }
249 cx.notify();
250 }
251
252 fn acknowledge_last_message(&mut self, cx: &mut ViewContext<Self>) {
253 if self.active && self.is_scrolled_to_bottom {
254 if let Some((chat, _)) = &self.active_chat {
255 chat.update(cx, |chat, cx| {
256 chat.acknowledge_last_message(cx);
257 });
258 }
259 }
260 }
261
262 fn render_channel(&self, cx: &mut ViewContext<Self>) -> AnyElement {
263 v_stack()
264 .full()
265 .on_action(cx.listener(Self::send))
266 .child(
267 h_stack().z_index(1).child(
268 TabBar::new("chat_header")
269 .child(
270 h_stack()
271 .w_full()
272 .h(rems(ui::Tab::HEIGHT_IN_REMS))
273 .px_2()
274 .child(Label::new(
275 self.active_chat
276 .as_ref()
277 .and_then(|c| {
278 Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
279 })
280 .unwrap_or_default(),
281 )),
282 )
283 .end_child(
284 IconButton::new("notes", Icon::File)
285 .on_click(cx.listener(Self::open_notes))
286 .tooltip(|cx| Tooltip::text("Open notes", cx)),
287 )
288 .end_child(
289 IconButton::new("call", Icon::AudioOn)
290 .on_click(cx.listener(Self::join_call))
291 .tooltip(|cx| Tooltip::text("Join call", cx)),
292 ),
293 ),
294 )
295 .child(div().flex_grow().px_2().py_1().map(|this| {
296 if self.active_chat.is_some() {
297 this.child(list(self.message_list.clone()).full())
298 } else {
299 this
300 }
301 }))
302 .child(h_stack().p_2().child(self.message_editor.clone()))
303 .into_any()
304 }
305
306 fn render_message(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> impl IntoElement {
307 let active_chat = &self.active_chat.as_ref().unwrap().0;
308 let (message, is_continuation_from_previous, is_continuation_to_next, is_admin) =
309 active_chat.update(cx, |active_chat, cx| {
310 let is_admin = self
311 .channel_store
312 .read(cx)
313 .is_channel_admin(active_chat.channel_id);
314
315 let last_message = active_chat.message(ix.saturating_sub(1));
316 let this_message = active_chat.message(ix).clone();
317 let next_message =
318 active_chat.message(ix.saturating_add(1).min(active_chat.message_count() - 1));
319
320 let is_continuation_from_previous = last_message.id != this_message.id
321 && last_message.sender.id == this_message.sender.id;
322 let is_continuation_to_next = this_message.id != next_message.id
323 && this_message.sender.id == next_message.sender.id;
324
325 if let ChannelMessageId::Saved(id) = this_message.id {
326 if this_message
327 .mentions
328 .iter()
329 .any(|(_, user_id)| Some(*user_id) == self.client.user_id())
330 {
331 active_chat.acknowledge_message(id);
332 }
333 }
334
335 (
336 this_message,
337 is_continuation_from_previous,
338 is_continuation_to_next,
339 is_admin,
340 )
341 });
342
343 let _is_pending = message.is_pending();
344 let text = self.markdown_data.entry(message.id).or_insert_with(|| {
345 Self::render_markdown_with_mentions(&self.languages, self.client.id(), &message)
346 });
347
348 let now = OffsetDateTime::now_utc();
349
350 let belongs_to_user = Some(message.sender.id) == self.client.user_id();
351 let message_id_to_remove = if let (ChannelMessageId::Saved(id), true) =
352 (message.id, belongs_to_user || is_admin)
353 {
354 Some(id)
355 } else {
356 None
357 };
358
359 let element_id: ElementId = match message.id {
360 ChannelMessageId::Saved(id) => ("saved-message", id).into(),
361 ChannelMessageId::Pending(id) => ("pending-message", id).into(),
362 };
363
364 v_stack()
365 .w_full()
366 .id(element_id)
367 .relative()
368 .overflow_hidden()
369 .group("")
370 .when(!is_continuation_from_previous, |this| {
371 this.child(
372 h_stack()
373 .gap_2()
374 .child(Avatar::new(message.sender.avatar_uri.clone()))
375 .child(Label::new(message.sender.github_login.clone()))
376 .child(
377 Label::new(format_timestamp(
378 message.timestamp,
379 now,
380 self.local_timezone,
381 ))
382 .color(Color::Muted),
383 ),
384 )
385 })
386 .when(!is_continuation_to_next, |this|
387 // HACK: This should really be a margin, but margins seem to get collapsed.
388 this.pb_2())
389 .child(text.element("body".into(), cx))
390 .child(
391 div()
392 .absolute()
393 .top_1()
394 .right_2()
395 .w_8()
396 .visible_on_hover("")
397 .children(message_id_to_remove.map(|message_id| {
398 IconButton::new(("remove", message_id), Icon::XCircle).on_click(
399 cx.listener(move |this, _, cx| {
400 this.remove_message(message_id, cx);
401 }),
402 )
403 })),
404 )
405 }
406
407 fn render_markdown_with_mentions(
408 language_registry: &Arc<LanguageRegistry>,
409 current_user_id: u64,
410 message: &channel::ChannelMessage,
411 ) -> RichText {
412 let mentions = message
413 .mentions
414 .iter()
415 .map(|(range, user_id)| rich_text::Mention {
416 range: range.clone(),
417 is_self_mention: *user_id == current_user_id,
418 })
419 .collect::<Vec<_>>();
420
421 rich_text::render_markdown(message.body.clone(), &mentions, language_registry, None)
422 }
423
424 fn render_sign_in_prompt(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
425 v_stack()
426 .gap_2()
427 .p_4()
428 .child(
429 Button::new("sign-in", "Sign in")
430 .style(ButtonStyle::Filled)
431 .icon_color(Color::Muted)
432 .icon(Icon::Github)
433 .icon_position(IconPosition::Start)
434 .full_width()
435 .on_click(cx.listener(move |this, _, cx| {
436 let client = this.client.clone();
437 cx.spawn(|this, mut cx| async move {
438 if client
439 .authenticate_and_connect(true, &cx)
440 .log_err()
441 .await
442 .is_some()
443 {
444 this.update(&mut cx, |_, cx| {
445 cx.focus_self();
446 })
447 .ok();
448 }
449 })
450 .detach();
451 })),
452 )
453 .child(
454 div().flex().w_full().items_center().child(
455 Label::new("Sign in to chat.")
456 .color(Color::Muted)
457 .size(LabelSize::Small),
458 ),
459 )
460 }
461
462 fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
463 if let Some((chat, _)) = self.active_chat.as_ref() {
464 let message = self
465 .message_editor
466 .update(cx, |editor, cx| editor.take_message(cx));
467
468 if let Some(task) = chat
469 .update(cx, |chat, cx| chat.send_message(message, cx))
470 .log_err()
471 {
472 task.detach();
473 }
474 }
475 }
476
477 fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
478 if let Some((chat, _)) = self.active_chat.as_ref() {
479 chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
480 }
481 }
482
483 fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
484 if let Some((chat, _)) = self.active_chat.as_ref() {
485 chat.update(cx, |channel, cx| {
486 if let Some(task) = channel.load_more_messages(cx) {
487 task.detach();
488 }
489 })
490 }
491 }
492
493 pub fn select_channel(
494 &mut self,
495 selected_channel_id: u64,
496 scroll_to_message_id: Option<u64>,
497 cx: &mut ViewContext<ChatPanel>,
498 ) -> Task<Result<()>> {
499 let open_chat = self
500 .active_chat
501 .as_ref()
502 .and_then(|(chat, _)| {
503 (chat.read(cx).channel_id == selected_channel_id)
504 .then(|| Task::ready(anyhow::Ok(chat.clone())))
505 })
506 .unwrap_or_else(|| {
507 self.channel_store.update(cx, |store, cx| {
508 store.open_channel_chat(selected_channel_id, cx)
509 })
510 });
511
512 cx.spawn(|this, mut cx| async move {
513 let chat = open_chat.await?;
514 this.update(&mut cx, |this, cx| {
515 this.set_active_chat(chat.clone(), cx);
516 })?;
517
518 if let Some(message_id) = scroll_to_message_id {
519 if let Some(item_ix) =
520 ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
521 .await
522 {
523 this.update(&mut cx, |this, cx| {
524 if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
525 this.message_list.scroll_to(ListOffset {
526 item_ix,
527 offset_in_item: px(0.0),
528 });
529 cx.notify();
530 }
531 })?;
532 }
533 }
534
535 Ok(())
536 })
537 }
538
539 fn open_notes(&mut self, _: &ClickEvent, cx: &mut ViewContext<Self>) {
540 if let Some((chat, _)) = &self.active_chat {
541 let channel_id = chat.read(cx).channel_id;
542 if let Some(workspace) = self.workspace.upgrade() {
543 ChannelView::open(channel_id, workspace, cx).detach();
544 }
545 }
546 }
547
548 fn join_call(&mut self, _: &ClickEvent, cx: &mut ViewContext<Self>) {
549 if let Some((chat, _)) = &self.active_chat {
550 let channel_id = chat.read(cx).channel_id;
551 ActiveCall::global(cx)
552 .update(cx, |call, cx| call.join_channel(channel_id, cx))
553 .detach_and_log_err(cx);
554 }
555 }
556}
557
558impl EventEmitter<Event> for ChatPanel {}
559
560impl Render for ChatPanel {
561 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
562 v_stack()
563 .size_full()
564 .map(|this| match (self.client.user_id(), self.active_chat()) {
565 (Some(_), Some(_)) => this.child(self.render_channel(cx)),
566 (Some(_), None) => this.child(
567 div().p_4().child(
568 Label::new("Select a channel to chat in.")
569 .size(LabelSize::Small)
570 .color(Color::Muted),
571 ),
572 ),
573 (None, _) => this.child(self.render_sign_in_prompt(cx)),
574 })
575 .min_w(px(150.))
576 }
577}
578
579impl FocusableView for ChatPanel {
580 fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
581 self.message_editor.read(cx).focus_handle(cx)
582 }
583}
584
585impl Panel for ChatPanel {
586 fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
587 ChatPanelSettings::get_global(cx).dock
588 }
589
590 fn position_is_valid(&self, position: DockPosition) -> bool {
591 matches!(position, DockPosition::Left | DockPosition::Right)
592 }
593
594 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
595 settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
596 settings.dock = Some(position)
597 });
598 }
599
600 fn size(&self, cx: &gpui::WindowContext) -> Pixels {
601 self.width
602 .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
603 }
604
605 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
606 self.width = size;
607 self.serialize(cx);
608 cx.notify();
609 }
610
611 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
612 self.active = active;
613 if active {
614 self.acknowledge_last_message(cx);
615 if !is_channels_feature_enabled(cx) {
616 cx.emit(Event::Dismissed);
617 }
618 }
619 }
620
621 fn persistent_name() -> &'static str {
622 "ChatPanel"
623 }
624
625 fn icon(&self, cx: &WindowContext) -> Option<ui::Icon> {
626 if !is_channels_feature_enabled(cx) {
627 return None;
628 }
629
630 Some(ui::Icon::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
631 }
632
633 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
634 Some("Chat Panel")
635 }
636
637 fn toggle_action(&self) -> Box<dyn gpui::Action> {
638 Box::new(ToggleFocus)
639 }
640}
641
642impl EventEmitter<PanelEvent> for ChatPanel {}
643
644fn format_timestamp(
645 mut timestamp: OffsetDateTime,
646 mut now: OffsetDateTime,
647 local_timezone: UtcOffset,
648) -> String {
649 timestamp = timestamp.to_offset(local_timezone);
650 now = now.to_offset(local_timezone);
651
652 let today = now.date();
653 let date = timestamp.date();
654 let mut hour = timestamp.hour();
655 let mut part = "am";
656 if hour > 12 {
657 hour -= 12;
658 part = "pm";
659 }
660 if date == today {
661 format!("{:02}:{:02}{}", hour, timestamp.minute(), part)
662 } else if date.next_day() == Some(today) {
663 format!("yesterday at {:02}:{:02}{}", hour, timestamp.minute(), part)
664 } else {
665 format!("{:02}/{}/{}", date.month() as u32, date.day(), date.year())
666 }
667}
668
669#[cfg(test)]
670mod tests {
671 use super::*;
672 use gpui::HighlightStyle;
673 use pretty_assertions::assert_eq;
674 use rich_text::Highlight;
675 use util::test::marked_text_ranges;
676
677 #[gpui::test]
678 fn test_render_markdown_with_mentions() {
679 let language_registry = Arc::new(LanguageRegistry::test());
680 let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
681 let message = channel::ChannelMessage {
682 id: ChannelMessageId::Saved(0),
683 body,
684 timestamp: OffsetDateTime::now_utc(),
685 sender: Arc::new(client::User {
686 github_login: "fgh".into(),
687 avatar_uri: "avatar_fgh".into(),
688 id: 103,
689 }),
690 nonce: 5,
691 mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
692 };
693
694 let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
695
696 // Note that the "'" was replaced with ’ due to smart punctuation.
697 let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
698 assert_eq!(message.text, body);
699 assert_eq!(
700 message.highlights,
701 vec![
702 (
703 ranges[0].clone(),
704 HighlightStyle {
705 font_style: Some(gpui::FontStyle::Italic),
706 ..Default::default()
707 }
708 .into()
709 ),
710 (ranges[1].clone(), Highlight::Mention),
711 (
712 ranges[2].clone(),
713 HighlightStyle {
714 font_weight: Some(gpui::FontWeight::BOLD),
715 ..Default::default()
716 }
717 .into()
718 ),
719 (ranges[3].clone(), Highlight::SelfMention)
720 ]
721 );
722 }
723}