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