chat_panel.rs

  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(
292                div()
293                    .flex_grow()
294                    .child(self.render_active_channel_messages(cx)),
295            )
296            .child(
297                div()
298                    .z_index(1)
299                    .p_2()
300                    .bg(cx.theme().colors().background)
301                    .child(self.input_editor.clone()),
302            )
303            .into_any()
304    }
305
306    fn render_active_channel_messages(&self, _cx: &mut ViewContext<Self>) -> AnyElement {
307        if self.active_chat.is_some() {
308            list(self.message_list.clone()).full().into_any_element()
309        } else {
310            div().into_any_element()
311        }
312    }
313
314    fn render_message(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> AnyElement {
315        let active_chat = &self.active_chat.as_ref().unwrap().0;
316        let (message, is_continuation, is_admin) = active_chat.update(cx, |active_chat, cx| {
317            let is_admin = self
318                .channel_store
319                .read(cx)
320                .is_channel_admin(active_chat.channel_id);
321
322            let last_message = active_chat.message(ix.saturating_sub(1));
323            let this_message = active_chat.message(ix).clone();
324            let is_continuation = last_message.id != this_message.id
325                && this_message.sender.id == last_message.sender.id;
326
327            if let ChannelMessageId::Saved(id) = this_message.id {
328                if this_message
329                    .mentions
330                    .iter()
331                    .any(|(_, user_id)| Some(*user_id) == self.client.user_id())
332                {
333                    active_chat.acknowledge_message(id);
334                }
335            }
336
337            (this_message, is_continuation, is_admin)
338        });
339
340        let _is_pending = message.is_pending();
341        let text = self.markdown_data.entry(message.id).or_insert_with(|| {
342            Self::render_markdown_with_mentions(&self.languages, self.client.id(), &message)
343        });
344
345        let now = OffsetDateTime::now_utc();
346
347        let belongs_to_user = Some(message.sender.id) == self.client.user_id();
348        let message_id_to_remove = if let (ChannelMessageId::Saved(id), true) =
349            (message.id, belongs_to_user || is_admin)
350        {
351            Some(id)
352        } else {
353            None
354        };
355
356        let element_id: ElementId = match message.id {
357            ChannelMessageId::Saved(id) => ("saved-message", id).into(),
358            ChannelMessageId::Pending(id) => ("pending-message", id).into(),
359        };
360
361        let mut result = v_stack()
362            .w_full()
363            .id(element_id)
364            .relative()
365            .group("")
366            .mb_1();
367
368        if !is_continuation {
369            result = result.child(
370                h_stack()
371                    .child(Avatar::new(message.sender.avatar_uri.clone()))
372                    .child(Label::new(message.sender.github_login.clone()))
373                    .child(Label::new(format_timestamp(
374                        message.timestamp,
375                        now,
376                        self.local_timezone,
377                    ))),
378            );
379        }
380
381        result
382            .child(text.element("body".into(), cx))
383            .child(
384                div()
385                    .invisible()
386                    .absolute()
387                    .top_1()
388                    .right_2()
389                    .w_8()
390                    .group_hover("", |this| this.visible())
391                    .child(render_remove(message_id_to_remove, cx)),
392            )
393            .into_any()
394    }
395
396    fn render_markdown_with_mentions(
397        language_registry: &Arc<LanguageRegistry>,
398        current_user_id: u64,
399        message: &channel::ChannelMessage,
400    ) -> RichText {
401        let mentions = message
402            .mentions
403            .iter()
404            .map(|(range, user_id)| rich_text::Mention {
405                range: range.clone(),
406                is_self_mention: *user_id == current_user_id,
407            })
408            .collect::<Vec<_>>();
409
410        rich_text::render_markdown(message.body.clone(), &mentions, language_registry, None)
411    }
412
413    fn render_sign_in_prompt(&self, cx: &mut ViewContext<Self>) -> AnyElement {
414        Button::new("sign-in", "Sign in to use chat")
415            .on_click(cx.listener(move |this, _, cx| {
416                let client = this.client.clone();
417                cx.spawn(|this, mut cx| async move {
418                    if client
419                        .authenticate_and_connect(true, &cx)
420                        .log_err()
421                        .await
422                        .is_some()
423                    {
424                        this.update(&mut cx, |_, cx| {
425                            cx.focus_self();
426                        })
427                        .ok();
428                    }
429                })
430                .detach();
431            }))
432            .into_any_element()
433    }
434
435    fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
436        if let Some((chat, _)) = self.active_chat.as_ref() {
437            let message = self
438                .input_editor
439                .update(cx, |editor, cx| editor.take_message(cx));
440
441            if let Some(task) = chat
442                .update(cx, |chat, cx| chat.send_message(message, cx))
443                .log_err()
444            {
445                task.detach();
446            }
447        }
448    }
449
450    fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
451        if let Some((chat, _)) = self.active_chat.as_ref() {
452            chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
453        }
454    }
455
456    fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
457        if let Some((chat, _)) = self.active_chat.as_ref() {
458            chat.update(cx, |channel, cx| {
459                if let Some(task) = channel.load_more_messages(cx) {
460                    task.detach();
461                }
462            })
463        }
464    }
465
466    pub fn select_channel(
467        &mut self,
468        selected_channel_id: u64,
469        scroll_to_message_id: Option<u64>,
470        cx: &mut ViewContext<ChatPanel>,
471    ) -> Task<Result<()>> {
472        let open_chat = self
473            .active_chat
474            .as_ref()
475            .and_then(|(chat, _)| {
476                (chat.read(cx).channel_id == selected_channel_id)
477                    .then(|| Task::ready(anyhow::Ok(chat.clone())))
478            })
479            .unwrap_or_else(|| {
480                self.channel_store.update(cx, |store, cx| {
481                    store.open_channel_chat(selected_channel_id, cx)
482                })
483            });
484
485        cx.spawn(|this, mut cx| async move {
486            let chat = open_chat.await?;
487            this.update(&mut cx, |this, cx| {
488                this.set_active_chat(chat.clone(), cx);
489            })?;
490
491            if let Some(message_id) = scroll_to_message_id {
492                if let Some(item_ix) =
493                    ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
494                        .await
495                {
496                    this.update(&mut cx, |this, cx| {
497                        if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
498                            this.message_list.scroll_to(ListOffset {
499                                item_ix,
500                                offset_in_item: px(0.0),
501                            });
502                            cx.notify();
503                        }
504                    })?;
505                }
506            }
507
508            Ok(())
509        })
510    }
511
512    fn open_notes(&mut self, _: &ClickEvent, cx: &mut ViewContext<Self>) {
513        if let Some((chat, _)) = &self.active_chat {
514            let channel_id = chat.read(cx).channel_id;
515            if let Some(workspace) = self.workspace.upgrade() {
516                ChannelView::open(channel_id, workspace, cx).detach();
517            }
518        }
519    }
520
521    fn join_call(&mut self, _: &ClickEvent, cx: &mut ViewContext<Self>) {
522        if let Some((chat, _)) = &self.active_chat {
523            let channel_id = chat.read(cx).channel_id;
524            ActiveCall::global(cx)
525                .update(cx, |call, cx| call.join_channel(channel_id, cx))
526                .detach_and_log_err(cx);
527        }
528    }
529}
530
531fn render_remove(message_id_to_remove: Option<u64>, cx: &mut ViewContext<ChatPanel>) -> AnyElement {
532    if let Some(message_id) = message_id_to_remove {
533        IconButton::new(("remove", message_id), Icon::XCircle)
534            .on_click(cx.listener(move |this, _, cx| {
535                this.remove_message(message_id, cx);
536            }))
537            .into_any_element()
538    } else {
539        div().into_any_element()
540    }
541}
542
543impl EventEmitter<Event> for ChatPanel {}
544
545impl Render for ChatPanel {
546    type Element = Div;
547
548    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
549        div()
550            .full()
551            .child(if self.client.user_id().is_some() {
552                self.render_channel(cx)
553            } else {
554                self.render_sign_in_prompt(cx)
555            })
556            .min_w(px(150.))
557    }
558}
559
560impl FocusableView for ChatPanel {
561    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
562        self.input_editor.read(cx).focus_handle(cx)
563    }
564}
565
566impl Panel for ChatPanel {
567    fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
568        ChatPanelSettings::get_global(cx).dock
569    }
570
571    fn position_is_valid(&self, position: DockPosition) -> bool {
572        matches!(position, DockPosition::Left | DockPosition::Right)
573    }
574
575    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
576        settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
577            settings.dock = Some(position)
578        });
579    }
580
581    fn size(&self, cx: &gpui::WindowContext) -> f32 {
582        self.width
583            .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
584    }
585
586    fn set_size(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>) {
587        self.width = size;
588        self.serialize(cx);
589        cx.notify();
590    }
591
592    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
593        self.active = active;
594        if active {
595            self.acknowledge_last_message(cx);
596            if !is_channels_feature_enabled(cx) {
597                cx.emit(Event::Dismissed);
598            }
599        }
600    }
601
602    fn persistent_name() -> &'static str {
603        "ChatPanel"
604    }
605
606    fn icon(&self, _cx: &WindowContext) -> Option<ui::Icon> {
607        Some(ui::Icon::MessageBubbles)
608    }
609
610    fn toggle_action(&self) -> Box<dyn gpui::Action> {
611        Box::new(ToggleFocus)
612    }
613}
614
615impl EventEmitter<PanelEvent> for ChatPanel {}
616
617fn format_timestamp(
618    mut timestamp: OffsetDateTime,
619    mut now: OffsetDateTime,
620    local_timezone: UtcOffset,
621) -> String {
622    timestamp = timestamp.to_offset(local_timezone);
623    now = now.to_offset(local_timezone);
624
625    let today = now.date();
626    let date = timestamp.date();
627    let mut hour = timestamp.hour();
628    let mut part = "am";
629    if hour > 12 {
630        hour -= 12;
631        part = "pm";
632    }
633    if date == today {
634        format!("{:02}:{:02}{}", hour, timestamp.minute(), part)
635    } else if date.next_day() == Some(today) {
636        format!("yesterday at {:02}:{:02}{}", hour, timestamp.minute(), part)
637    } else {
638        format!("{:02}/{}/{}", date.month() as u32, date.day(), date.year())
639    }
640}
641
642#[cfg(test)]
643mod tests {
644    use super::*;
645    use gpui::HighlightStyle;
646    use pretty_assertions::assert_eq;
647    use rich_text::Highlight;
648    use util::test::marked_text_ranges;
649
650    #[gpui::test]
651    fn test_render_markdown_with_mentions() {
652        let language_registry = Arc::new(LanguageRegistry::test());
653        let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
654        let message = channel::ChannelMessage {
655            id: ChannelMessageId::Saved(0),
656            body,
657            timestamp: OffsetDateTime::now_utc(),
658            sender: Arc::new(client::User {
659                github_login: "fgh".into(),
660                avatar_uri: "avatar_fgh".into(),
661                id: 103,
662            }),
663            nonce: 5,
664            mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
665        };
666
667        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
668
669        // Note that the "'" was replaced with ’ due to smart punctuation.
670        let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
671        assert_eq!(message.text, body);
672        assert_eq!(
673            message.highlights,
674            vec![
675                (
676                    ranges[0].clone(),
677                    HighlightStyle {
678                        font_style: Some(gpui::FontStyle::Italic),
679                        ..Default::default()
680                    }
681                    .into()
682                ),
683                (ranges[1].clone(), Highlight::Mention),
684                (
685                    ranges[2].clone(),
686                    HighlightStyle {
687                        font_weight: Some(gpui::FontWeight::BOLD),
688                        ..Default::default()
689                    }
690                    .into()
691                ),
692                (ranges[3].clone(), Highlight::SelfMention)
693            ]
694        );
695    }
696}