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                        .child(
353                            div().absolute().child(
354                                Avatar::new(message.sender.avatar_uri.clone())
355                                    .size(cx.rem_size() * 1.5),
356                            ),
357                        )
358                        .child(
359                            div()
360                                .pl(cx.rem_size() * 1.5 + px(6.0))
361                                .pr(px(8.0))
362                                .font_weight(FontWeight::BOLD)
363                                .child(Label::new(message.sender.github_login.clone())),
364                        )
365                        .child(
366                            Label::new(format_timestamp(
367                                message.timestamp,
368                                now,
369                                self.local_timezone,
370                            ))
371                            .size(LabelSize::Small)
372                            .color(Color::Muted),
373                        ),
374                )
375            })
376            .when(is_continuation_from_previous, |this| this.pt_1())
377            .child(
378                v_flex()
379                    .w_full()
380                    .text_ui_sm()
381                    .id(element_id)
382                    .group("")
383                    .child(text.element("body".into(), cx))
384                    .child(
385                        div()
386                            .absolute()
387                            .z_index(1)
388                            .right_0()
389                            .w_6()
390                            .bg(cx.theme().colors().panel_background)
391                            .when(!self.has_open_menu(message_id_to_remove), |el| {
392                                el.visible_on_hover("")
393                            })
394                            .children(message_id_to_remove.map(|message_id| {
395                                popover_menu(("menu", message_id))
396                                    .trigger(IconButton::new(
397                                        ("trigger", message_id),
398                                        IconName::Ellipsis,
399                                    ))
400                                    .menu(move |cx| {
401                                        Some(Self::render_message_menu(&this, message_id, cx))
402                                    })
403                            })),
404                    ),
405            )
406    }
407
408    fn has_open_menu(&self, message_id: Option<u64>) -> bool {
409        match self.open_context_menu.as_ref() {
410            Some((id, _)) => Some(*id) == message_id,
411            None => false,
412        }
413    }
414
415    fn render_message_menu(
416        this: &View<Self>,
417        message_id: u64,
418        cx: &mut WindowContext,
419    ) -> View<ContextMenu> {
420        let menu = {
421            let this = this.clone();
422            ContextMenu::build(cx, move |menu, _| {
423                menu.entry("Delete message", None, move |cx| {
424                    this.update(cx, |this, cx| this.remove_message(message_id, cx))
425                })
426            })
427        };
428        this.update(cx, |this, cx| {
429            let subscription = cx.subscribe(&menu, |this: &mut Self, _, _: &DismissEvent, _| {
430                this.open_context_menu = None;
431            });
432            this.open_context_menu = Some((message_id, subscription));
433        });
434        menu
435    }
436
437    fn render_markdown_with_mentions(
438        language_registry: &Arc<LanguageRegistry>,
439        current_user_id: u64,
440        message: &channel::ChannelMessage,
441    ) -> RichText {
442        let mentions = message
443            .mentions
444            .iter()
445            .map(|(range, user_id)| rich_text::Mention {
446                range: range.clone(),
447                is_self_mention: *user_id == current_user_id,
448            })
449            .collect::<Vec<_>>();
450
451        rich_text::render_markdown(message.body.clone(), &mentions, language_registry, None)
452    }
453
454    fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
455        if let Some((chat, _)) = self.active_chat.as_ref() {
456            let message = self
457                .message_editor
458                .update(cx, |editor, cx| editor.take_message(cx));
459
460            if let Some(task) = chat
461                .update(cx, |chat, cx| chat.send_message(message, cx))
462                .log_err()
463            {
464                task.detach();
465            }
466        }
467    }
468
469    fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
470        if let Some((chat, _)) = self.active_chat.as_ref() {
471            chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
472        }
473    }
474
475    fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
476        if let Some((chat, _)) = self.active_chat.as_ref() {
477            chat.update(cx, |channel, cx| {
478                if let Some(task) = channel.load_more_messages(cx) {
479                    task.detach();
480                }
481            })
482        }
483    }
484
485    pub fn select_channel(
486        &mut self,
487        selected_channel_id: u64,
488        scroll_to_message_id: Option<u64>,
489        cx: &mut ViewContext<ChatPanel>,
490    ) -> Task<Result<()>> {
491        let open_chat = self
492            .active_chat
493            .as_ref()
494            .and_then(|(chat, _)| {
495                (chat.read(cx).channel_id == selected_channel_id)
496                    .then(|| Task::ready(anyhow::Ok(chat.clone())))
497            })
498            .unwrap_or_else(|| {
499                self.channel_store.update(cx, |store, cx| {
500                    store.open_channel_chat(selected_channel_id, cx)
501                })
502            });
503
504        cx.spawn(|this, mut cx| async move {
505            let chat = open_chat.await?;
506            this.update(&mut cx, |this, cx| {
507                this.set_active_chat(chat.clone(), cx);
508            })?;
509
510            if let Some(message_id) = scroll_to_message_id {
511                if let Some(item_ix) =
512                    ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
513                        .await
514                {
515                    this.update(&mut cx, |this, cx| {
516                        if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
517                            this.message_list.scroll_to(ListOffset {
518                                item_ix,
519                                offset_in_item: px(0.0),
520                            });
521                            cx.notify();
522                        }
523                    })?;
524                }
525            }
526
527            Ok(())
528        })
529    }
530}
531
532impl Render for ChatPanel {
533    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
534        v_flex()
535            .track_focus(&self.focus_handle)
536            .full()
537            .on_action(cx.listener(Self::send))
538            .child(
539                h_flex().z_index(1).child(
540                    TabBar::new("chat_header").child(
541                        h_flex()
542                            .w_full()
543                            .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
544                            .px_2()
545                            .child(Label::new(
546                                self.active_chat
547                                    .as_ref()
548                                    .and_then(|c| {
549                                        Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
550                                    })
551                                    .unwrap_or("Chat".to_string()),
552                            )),
553                    ),
554                ),
555            )
556            .child(div().flex_grow().px_2().pt_1().map(|this| {
557                if self.active_chat.is_some() {
558                    this.child(list(self.message_list.clone()).full())
559                } else {
560                    this.child(
561                        div()
562                            .p_4()
563                            .child(
564                                Label::new("Select a channel to chat in.")
565                                    .size(LabelSize::Small)
566                                    .color(Color::Muted),
567                            )
568                            .child(
569                                div().pt_1().w_full().items_center().child(
570                                    Button::new("toggle-collab", "Open")
571                                        .full_width()
572                                        .key_binding(KeyBinding::for_action(
573                                            &collab_panel::ToggleFocus,
574                                            cx,
575                                        ))
576                                        .on_click(|_, cx| {
577                                            cx.dispatch_action(
578                                                collab_panel::ToggleFocus.boxed_clone(),
579                                            )
580                                        }),
581                                ),
582                            ),
583                    )
584                }
585            }))
586            .child(
587                h_flex()
588                    .when(!self.is_scrolled_to_bottom, |el| {
589                        el.border_t_1().border_color(cx.theme().colors().border)
590                    })
591                    .p_2()
592                    .map(|el| {
593                        if self.active_chat.is_some() {
594                            el.child(self.message_editor.clone())
595                        } else {
596                            el.child(
597                                div()
598                                    .rounded_md()
599                                    .h_7()
600                                    .w_full()
601                                    .bg(cx.theme().colors().editor_background),
602                            )
603                        }
604                    }),
605            )
606            .into_any()
607    }
608}
609
610impl FocusableView for ChatPanel {
611    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
612        if self.active_chat.is_some() {
613            self.message_editor.read(cx).focus_handle(cx)
614        } else {
615            self.focus_handle.clone()
616        }
617    }
618}
619
620impl Panel for ChatPanel {
621    fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
622        ChatPanelSettings::get_global(cx).dock
623    }
624
625    fn position_is_valid(&self, position: DockPosition) -> bool {
626        matches!(position, DockPosition::Left | DockPosition::Right)
627    }
628
629    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
630        settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
631            settings.dock = Some(position)
632        });
633    }
634
635    fn size(&self, cx: &gpui::WindowContext) -> Pixels {
636        self.width
637            .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
638    }
639
640    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
641        self.width = size;
642        self.serialize(cx);
643        cx.notify();
644    }
645
646    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
647        self.active = active;
648        if active {
649            self.acknowledge_last_message(cx);
650        }
651    }
652
653    fn persistent_name() -> &'static str {
654        "ChatPanel"
655    }
656
657    fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
658        Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
659    }
660
661    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
662        Some("Chat Panel")
663    }
664
665    fn toggle_action(&self) -> Box<dyn gpui::Action> {
666        Box::new(ToggleFocus)
667    }
668}
669
670impl EventEmitter<PanelEvent> for ChatPanel {}
671
672fn format_timestamp(
673    mut timestamp: OffsetDateTime,
674    mut now: OffsetDateTime,
675    local_timezone: UtcOffset,
676) -> String {
677    timestamp = timestamp.to_offset(local_timezone);
678    now = now.to_offset(local_timezone);
679
680    let today = now.date();
681    let date = timestamp.date();
682    let mut hour = timestamp.hour();
683    let mut part = "am";
684    if hour > 12 {
685        hour -= 12;
686        part = "pm";
687    }
688    if date == today {
689        format!("{:02}:{:02}{}", hour, timestamp.minute(), part)
690    } else if date.next_day() == Some(today) {
691        format!("yesterday at {:02}:{:02}{}", hour, timestamp.minute(), part)
692    } else {
693        format!("{:02}/{}/{}", date.month() as u32, date.day(), date.year())
694    }
695}
696
697#[cfg(test)]
698mod tests {
699    use super::*;
700    use gpui::HighlightStyle;
701    use pretty_assertions::assert_eq;
702    use rich_text::Highlight;
703    use util::test::marked_text_ranges;
704
705    #[gpui::test]
706    fn test_render_markdown_with_mentions() {
707        let language_registry = Arc::new(LanguageRegistry::test());
708        let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
709        let message = channel::ChannelMessage {
710            id: ChannelMessageId::Saved(0),
711            body,
712            timestamp: OffsetDateTime::now_utc(),
713            sender: Arc::new(client::User {
714                github_login: "fgh".into(),
715                avatar_uri: "avatar_fgh".into(),
716                id: 103,
717            }),
718            nonce: 5,
719            mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
720        };
721
722        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
723
724        // Note that the "'" was replaced with ’ due to smart punctuation.
725        let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
726        assert_eq!(message.text, body);
727        assert_eq!(
728            message.highlights,
729            vec![
730                (
731                    ranges[0].clone(),
732                    HighlightStyle {
733                        font_style: Some(gpui::FontStyle::Italic),
734                        ..Default::default()
735                    }
736                    .into()
737                ),
738                (ranges[1].clone(), Highlight::Mention),
739                (
740                    ranges[2].clone(),
741                    HighlightStyle {
742                        font_weight: Some(gpui::FontWeight::BOLD),
743                        ..Default::default()
744                    }
745                    .into()
746                ),
747                (ranges[3].clone(), Highlight::SelfMention)
748            ]
749        );
750    }
751}