chat_panel.rs

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