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::{prelude::*, Avatar, Button, Icon, IconButton, Label, Tooltip};
 25use util::{ResultExt, TryFutureExt};
 26use workspace::{
 27    dock::{DockPosition, Panel, PanelEvent},
 28    Workspace,
 29};
 30
 31mod message_editor;
 32
 33const MESSAGE_LOADING_THRESHOLD: usize = 50;
 34const CHAT_PANEL_KEY: &'static str = "ChatPanel";
 35
 36pub fn init(cx: &mut AppContext) {
 37    cx.observe_new_views(|workspace: &mut Workspace, _| {
 38        workspace.register_action(|workspace, _: &ToggleFocus, cx| {
 39            workspace.toggle_panel_focus::<ChatPanel>(cx);
 40        });
 41    })
 42    .detach();
 43}
 44
 45pub struct ChatPanel {
 46    client: Arc<Client>,
 47    channel_store: Model<ChannelStore>,
 48    languages: Arc<LanguageRegistry>,
 49    message_list: ListState,
 50    active_chat: Option<(Model<ChannelChat>, Subscription)>,
 51    input_editor: View<MessageEditor>,
 52    local_timezone: UtcOffset,
 53    fs: Arc<dyn Fs>,
 54    width: Option<f32>,
 55    active: bool,
 56    pending_serialization: Task<Option<()>>,
 57    subscriptions: Vec<gpui::Subscription>,
 58    workspace: WeakView<Workspace>,
 59    is_scrolled_to_bottom: bool,
 60    markdown_data: HashMap<ChannelMessageId, RichText>,
 61}
 62
 63#[derive(Serialize, Deserialize)]
 64struct SerializedChatPanel {
 65    width: Option<f32>,
 66}
 67
 68#[derive(Debug)]
 69pub enum Event {
 70    DockPositionChanged,
 71    Focus,
 72    Dismissed,
 73}
 74
 75actions!(chat_panel, [ToggleFocus]);
 76
 77impl ChatPanel {
 78    pub fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> View<Self> {
 79        let fs = workspace.app_state().fs.clone();
 80        let client = workspace.app_state().client.clone();
 81        let channel_store = ChannelStore::global(cx);
 82        let languages = workspace.app_state().languages.clone();
 83
 84        let input_editor = cx.build_view(|cx| {
 85            MessageEditor::new(
 86                languages.clone(),
 87                channel_store.clone(),
 88                cx.build_view(|cx| Editor::auto_height(4, cx)),
 89                cx,
 90            )
 91        });
 92
 93        let workspace_handle = workspace.weak_handle();
 94
 95        cx.build_view(|cx| {
 96            let view: View<ChatPanel> = cx.view().clone();
 97            let message_list =
 98                ListState::new(0, gpui::ListAlignment::Bottom, px(1000.), move |ix, cx| {
 99                    view.update(cx, |view, cx| view.render_message(ix, cx))
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.visible_range.end == event.count;
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                input_editor,
118                local_timezone: cx.local_timezone(),
119                subscriptions: Vec::new(),
120                workspace: workspace_handle,
121                is_scrolled_to_bottom: true,
122                active: false,
123                width: None,
124                markdown_data: Default::default(),
125            };
126
127            let mut old_dock_position = this.position(cx);
128            this.subscriptions.push(cx.observe_global::<SettingsStore>(
129                move |this: &mut Self, cx| {
130                    let new_dock_position = this.position(cx);
131                    if new_dock_position != old_dock_position {
132                        old_dock_position = new_dock_position;
133                        cx.emit(Event::DockPositionChanged);
134                    }
135                    cx.notify();
136                },
137            ));
138
139            this
140        })
141    }
142
143    pub fn is_scrolled_to_bottom(&self) -> bool {
144        self.is_scrolled_to_bottom
145    }
146
147    pub fn active_chat(&self) -> Option<Model<ChannelChat>> {
148        self.active_chat.as_ref().map(|(chat, _)| chat.clone())
149    }
150
151    pub fn load(
152        workspace: WeakView<Workspace>,
153        cx: AsyncWindowContext,
154    ) -> Task<Result<View<Self>>> {
155        cx.spawn(|mut cx| async move {
156            let serialized_panel = if let Some(panel) = cx
157                .background_executor()
158                .spawn(async move { KEY_VALUE_STORE.read_kvp(CHAT_PANEL_KEY) })
159                .await
160                .log_err()
161                .flatten()
162            {
163                Some(serde_json::from_str::<SerializedChatPanel>(&panel)?)
164            } else {
165                None
166            };
167
168            workspace.update(&mut cx, |workspace, cx| {
169                let panel = Self::new(workspace, cx);
170                if let Some(serialized_panel) = serialized_panel {
171                    panel.update(cx, |panel, cx| {
172                        panel.width = serialized_panel.width;
173                        cx.notify();
174                    });
175                }
176                panel
177            })
178        })
179    }
180
181    fn serialize(&mut self, cx: &mut ViewContext<Self>) {
182        let width = self.width;
183        self.pending_serialization = cx.background_executor().spawn(
184            async move {
185                KEY_VALUE_STORE
186                    .write_kvp(
187                        CHAT_PANEL_KEY.into(),
188                        serde_json::to_string(&SerializedChatPanel { width })?,
189                    )
190                    .await?;
191                anyhow::Ok(())
192            }
193            .log_err(),
194        );
195    }
196
197    fn set_active_chat(&mut self, chat: Model<ChannelChat>, cx: &mut ViewContext<Self>) {
198        if self.active_chat.as_ref().map(|e| &e.0) != Some(&chat) {
199            let channel_id = chat.read(cx).channel_id;
200            {
201                self.markdown_data.clear();
202                let chat = chat.read(cx);
203                self.message_list.reset(chat.message_count());
204
205                let channel_name = chat.channel(cx).map(|channel| channel.name.clone());
206                self.input_editor.update(cx, |editor, cx| {
207                    editor.set_channel(channel_id, channel_name, cx);
208                });
209            };
210            let subscription = cx.subscribe(&chat, Self::channel_did_change);
211            self.active_chat = Some((chat, subscription));
212            self.acknowledge_last_message(cx);
213            cx.notify();
214        }
215    }
216
217    fn channel_did_change(
218        &mut self,
219        _: Model<ChannelChat>,
220        event: &ChannelChatEvent,
221        cx: &mut ViewContext<Self>,
222    ) {
223        match event {
224            ChannelChatEvent::MessagesUpdated {
225                old_range,
226                new_count,
227            } => {
228                self.message_list.splice(old_range.clone(), *new_count);
229                if self.active {
230                    self.acknowledge_last_message(cx);
231                }
232            }
233            ChannelChatEvent::NewMessage {
234                channel_id,
235                message_id,
236            } => {
237                if !self.active {
238                    self.channel_store.update(cx, |store, cx| {
239                        store.new_message(*channel_id, *message_id, cx)
240                    })
241                }
242            }
243        }
244        cx.notify();
245    }
246
247    fn acknowledge_last_message(&mut self, cx: &mut ViewContext<Self>) {
248        if self.active && self.is_scrolled_to_bottom {
249            if let Some((chat, _)) = &self.active_chat {
250                chat.update(cx, |chat, cx| {
251                    chat.acknowledge_last_message(cx);
252                });
253            }
254        }
255    }
256
257    fn render_channel(&self, cx: &mut ViewContext<Self>) -> AnyElement {
258        v_stack()
259            .full()
260            .on_action(cx.listener(Self::send))
261            .child(
262                h_stack()
263                    .w_full()
264                    .h_7()
265                    .justify_between()
266                    .z_index(1)
267                    .bg(cx.theme().colors().background)
268                    .child(Label::new(
269                        self.active_chat
270                            .as_ref()
271                            .and_then(|c| Some(format!("#{}", c.0.read(cx).channel(cx)?.name)))
272                            .unwrap_or_default(),
273                    ))
274                    .child(
275                        h_stack()
276                            .child(
277                                IconButton::new("notes", Icon::File)
278                                    .on_click(cx.listener(Self::open_notes))
279                                    .tooltip(|cx| Tooltip::text("Open notes", cx)),
280                            )
281                            .child(
282                                IconButton::new("call", Icon::AudioOn)
283                                    .on_click(cx.listener(Self::join_call))
284                                    .tooltip(|cx| Tooltip::text("Join call", cx)),
285                            ),
286                    ),
287            )
288            .child(
289                div()
290                    .flex_grow()
291                    .child(self.render_active_channel_messages(cx)),
292            )
293            .child(
294                div()
295                    .z_index(1)
296                    .p_2()
297                    .bg(cx.theme().colors().background)
298                    .child(self.input_editor.clone()),
299            )
300            .into_any()
301    }
302
303    fn render_active_channel_messages(&self, _cx: &mut ViewContext<Self>) -> AnyElement {
304        if self.active_chat.is_some() {
305            list(self.message_list.clone()).full().into_any_element()
306        } else {
307            div().into_any_element()
308        }
309    }
310
311    fn render_message(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> AnyElement {
312        let active_chat = &self.active_chat.as_ref().unwrap().0;
313        let (message, is_continuation, is_admin) = active_chat.update(cx, |active_chat, cx| {
314            let is_admin = self
315                .channel_store
316                .read(cx)
317                .is_channel_admin(active_chat.channel_id);
318
319            let last_message = active_chat.message(ix.saturating_sub(1));
320            let this_message = active_chat.message(ix).clone();
321            let is_continuation = last_message.id != this_message.id
322                && this_message.sender.id == last_message.sender.id;
323
324            if let ChannelMessageId::Saved(id) = this_message.id {
325                if this_message
326                    .mentions
327                    .iter()
328                    .any(|(_, user_id)| Some(*user_id) == self.client.user_id())
329                {
330                    active_chat.acknowledge_message(id);
331                }
332            }
333
334            (this_message, is_continuation, is_admin)
335        });
336
337        let _is_pending = message.is_pending();
338        let text = self.markdown_data.entry(message.id).or_insert_with(|| {
339            Self::render_markdown_with_mentions(&self.languages, self.client.id(), &message)
340        });
341
342        let now = OffsetDateTime::now_utc();
343
344        let belongs_to_user = Some(message.sender.id) == self.client.user_id();
345        let message_id_to_remove = if let (ChannelMessageId::Saved(id), true) =
346            (message.id, belongs_to_user || is_admin)
347        {
348            Some(id)
349        } else {
350            None
351        };
352
353        let element_id: ElementId = match message.id {
354            ChannelMessageId::Saved(id) => ("saved-message", id).into(),
355            ChannelMessageId::Pending(id) => ("pending-message", id).into(),
356        };
357
358        let mut result = v_stack()
359            .w_full()
360            .id(element_id)
361            .relative()
362            .group("")
363            .mb_1();
364
365        if !is_continuation {
366            result = result.child(
367                h_stack()
368                    .child(Avatar::new(message.sender.avatar_uri.clone()))
369                    .child(Label::new(message.sender.github_login.clone()))
370                    .child(Label::new(format_timestamp(
371                        message.timestamp,
372                        now,
373                        self.local_timezone,
374                    ))),
375            );
376        }
377
378        result
379            .child(text.element("body".into(), cx))
380            .child(
381                div()
382                    .absolute()
383                    .top_1()
384                    .right_2()
385                    .w_8()
386                    .visible_on_hover("")
387                    .children(message_id_to_remove.map(|message_id| {
388                        IconButton::new(("remove", message_id), Icon::XCircle).on_click(
389                            cx.listener(move |this, _, cx| {
390                                this.remove_message(message_id, cx);
391                            }),
392                        )
393                    })),
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
533impl EventEmitter<Event> for ChatPanel {}
534
535impl Render for ChatPanel {
536    type Element = Div;
537
538    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
539        div()
540            .full()
541            .child(if self.client.user_id().is_some() {
542                self.render_channel(cx)
543            } else {
544                self.render_sign_in_prompt(cx)
545            })
546            .min_w(px(150.))
547    }
548}
549
550impl FocusableView for ChatPanel {
551    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
552        self.input_editor.read(cx).focus_handle(cx)
553    }
554}
555
556impl Panel for ChatPanel {
557    fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
558        ChatPanelSettings::get_global(cx).dock
559    }
560
561    fn position_is_valid(&self, position: DockPosition) -> bool {
562        matches!(position, DockPosition::Left | DockPosition::Right)
563    }
564
565    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
566        settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
567            settings.dock = Some(position)
568        });
569    }
570
571    fn size(&self, cx: &gpui::WindowContext) -> f32 {
572        self.width
573            .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
574    }
575
576    fn set_size(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>) {
577        self.width = size;
578        self.serialize(cx);
579        cx.notify();
580    }
581
582    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
583        self.active = active;
584        if active {
585            self.acknowledge_last_message(cx);
586            if !is_channels_feature_enabled(cx) {
587                cx.emit(Event::Dismissed);
588            }
589        }
590    }
591
592    fn persistent_name() -> &'static str {
593        "ChatPanel"
594    }
595
596    fn icon(&self, _cx: &WindowContext) -> Option<ui::Icon> {
597        Some(ui::Icon::MessageBubbles)
598    }
599
600    fn toggle_action(&self) -> Box<dyn gpui::Action> {
601        Box::new(ToggleFocus)
602    }
603}
604
605impl EventEmitter<PanelEvent> for ChatPanel {}
606
607fn format_timestamp(
608    mut timestamp: OffsetDateTime,
609    mut now: OffsetDateTime,
610    local_timezone: UtcOffset,
611) -> String {
612    timestamp = timestamp.to_offset(local_timezone);
613    now = now.to_offset(local_timezone);
614
615    let today = now.date();
616    let date = timestamp.date();
617    let mut hour = timestamp.hour();
618    let mut part = "am";
619    if hour > 12 {
620        hour -= 12;
621        part = "pm";
622    }
623    if date == today {
624        format!("{:02}:{:02}{}", hour, timestamp.minute(), part)
625    } else if date.next_day() == Some(today) {
626        format!("yesterday at {:02}:{:02}{}", hour, timestamp.minute(), part)
627    } else {
628        format!("{:02}/{}/{}", date.month() as u32, date.day(), date.year())
629    }
630}
631
632#[cfg(test)]
633mod tests {
634    use super::*;
635    use gpui::HighlightStyle;
636    use pretty_assertions::assert_eq;
637    use rich_text::Highlight;
638    use util::test::marked_text_ranges;
639
640    #[gpui::test]
641    fn test_render_markdown_with_mentions() {
642        let language_registry = Arc::new(LanguageRegistry::test());
643        let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
644        let message = channel::ChannelMessage {
645            id: ChannelMessageId::Saved(0),
646            body,
647            timestamp: OffsetDateTime::now_utc(),
648            sender: Arc::new(client::User {
649                github_login: "fgh".into(),
650                avatar_uri: "avatar_fgh".into(),
651                id: 103,
652            }),
653            nonce: 5,
654            mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
655        };
656
657        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
658
659        // Note that the "'" was replaced with ’ due to smart punctuation.
660        let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
661        assert_eq!(message.text, body);
662        assert_eq!(
663            message.highlights,
664            vec![
665                (
666                    ranges[0].clone(),
667                    HighlightStyle {
668                        font_style: Some(gpui::FontStyle::Italic),
669                        ..Default::default()
670                    }
671                    .into()
672                ),
673                (ranges[1].clone(), Highlight::Mention),
674                (
675                    ranges[2].clone(),
676                    HighlightStyle {
677                        font_weight: Some(gpui::FontWeight::BOLD),
678                        ..Default::default()
679                    }
680                    .into()
681                ),
682                (ranges[3].clone(), Highlight::SelfMention)
683            ]
684        );
685    }
686}