chat_panel.rs

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