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