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