chat_panel.rs

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