chat_panel.rs

   1use crate::{collab_panel, ChatPanelSettings};
   2use anyhow::Result;
   3use call::{room, ActiveCall};
   4use channel::{ChannelChat, ChannelChatEvent, ChannelMessage, ChannelMessageId, ChannelStore};
   5use client::{ChannelId, Client};
   6use collections::HashMap;
   7use db::kvp::KEY_VALUE_STORE;
   8use editor::{actions, Editor};
   9use gpui::{
  10    actions, div, list, prelude::*, px, Action, AppContext, AsyncWindowContext, ClipboardItem,
  11    CursorStyle, DismissEvent, ElementId, EventEmitter, FocusHandle, FocusableView, FontWeight,
  12    HighlightStyle, ListOffset, ListScrollEvent, ListState, Model, Render, Stateful, Subscription,
  13    Task, View, ViewContext, VisualContext, WeakView,
  14};
  15use language::LanguageRegistry;
  16use menu::Confirm;
  17use message_editor::MessageEditor;
  18use project::Fs;
  19use rich_text::{Highlight, RichText};
  20use serde::{Deserialize, Serialize};
  21use settings::Settings;
  22use std::{sync::Arc, time::Duration};
  23use time::{OffsetDateTime, UtcOffset};
  24use ui::{
  25    popover_menu, prelude::*, Avatar, Button, ContextMenu, IconButton, IconName, KeyBinding, Label,
  26    TabBar, 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: &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    message_editor: View<MessageEditor>,
  55    local_timezone: UtcOffset,
  56    fs: Arc<dyn Fs>,
  57    width: Option<Pixels>,
  58    active: bool,
  59    pending_serialization: Task<Option<()>>,
  60    subscriptions: Vec<gpui::Subscription>,
  61    is_scrolled_to_bottom: bool,
  62    markdown_data: HashMap<ChannelMessageId, RichText>,
  63    focus_handle: FocusHandle,
  64    open_context_menu: Option<(u64, Subscription)>,
  65    highlighted_message: Option<(u64, Task<()>)>,
  66    last_acknowledged_message_id: Option<u64>,
  67}
  68
  69#[derive(Serialize, Deserialize)]
  70struct SerializedChatPanel {
  71    width: Option<Pixels>,
  72}
  73
  74actions!(chat_panel, [ToggleFocus]);
  75
  76impl ChatPanel {
  77    pub fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> View<Self> {
  78        let fs = workspace.app_state().fs.clone();
  79        let client = workspace.app_state().client.clone();
  80        let channel_store = ChannelStore::global(cx);
  81        let languages = workspace.app_state().languages.clone();
  82
  83        let input_editor = cx.new_view(|cx| {
  84            MessageEditor::new(
  85                languages.clone(),
  86                channel_store.clone(),
  87                cx.new_view(|cx| Editor::auto_height(4, cx)),
  88                cx,
  89            )
  90        });
  91
  92        cx.new_view(|cx: &mut ViewContext<Self>| {
  93            let view = cx.view().downgrade();
  94            let message_list =
  95                ListState::new(0, gpui::ListAlignment::Bottom, px(1000.), move |ix, cx| {
  96                    if let Some(view) = view.upgrade() {
  97                        view.update(cx, |view, cx| {
  98                            view.render_message(ix, cx).into_any_element()
  99                        })
 100                    } else {
 101                        div().into_any()
 102                    }
 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.is_scrolled;
 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                message_editor: input_editor,
 121                local_timezone: cx.local_timezone(),
 122                subscriptions: Vec::new(),
 123                is_scrolled_to_bottom: true,
 124                active: false,
 125                width: None,
 126                markdown_data: Default::default(),
 127                focus_handle: cx.focus_handle(),
 128                open_context_menu: None,
 129                highlighted_message: None,
 130                last_acknowledged_message_id: None,
 131            };
 132
 133            if let Some(channel_id) = ActiveCall::global(cx)
 134                .read(cx)
 135                .room()
 136                .and_then(|room| room.read(cx).channel_id())
 137            {
 138                this.select_channel(channel_id, None, cx)
 139                    .detach_and_log_err(cx);
 140            }
 141
 142            this.subscriptions.push(cx.subscribe(
 143                &ActiveCall::global(cx),
 144                move |this: &mut Self, call, event: &room::Event, cx| match event {
 145                    room::Event::RoomJoined { channel_id } => {
 146                        if let Some(channel_id) = channel_id {
 147                            this.select_channel(*channel_id, None, cx)
 148                                .detach_and_log_err(cx);
 149
 150                            if call
 151                                .read(cx)
 152                                .room()
 153                                .is_some_and(|room| room.read(cx).contains_guests())
 154                            {
 155                                cx.emit(PanelEvent::Activate)
 156                            }
 157                        }
 158                    }
 159                    room::Event::RoomLeft { channel_id } => {
 160                        if channel_id == &this.channel_id(cx) {
 161                            cx.emit(PanelEvent::Close)
 162                        }
 163                    }
 164                    _ => {}
 165                },
 166            ));
 167
 168            this
 169        })
 170    }
 171
 172    pub fn channel_id(&self, cx: &AppContext) -> Option<ChannelId> {
 173        self.active_chat
 174            .as_ref()
 175            .map(|(chat, _)| chat.read(cx).channel_id)
 176    }
 177
 178    pub fn is_scrolled_to_bottom(&self) -> bool {
 179        self.is_scrolled_to_bottom
 180    }
 181
 182    pub fn active_chat(&self) -> Option<Model<ChannelChat>> {
 183        self.active_chat.as_ref().map(|(chat, _)| chat.clone())
 184    }
 185
 186    pub fn load(
 187        workspace: WeakView<Workspace>,
 188        cx: AsyncWindowContext,
 189    ) -> Task<Result<View<Self>>> {
 190        cx.spawn(|mut cx| async move {
 191            let serialized_panel = if let Some(panel) = cx
 192                .background_executor()
 193                .spawn(async move { KEY_VALUE_STORE.read_kvp(CHAT_PANEL_KEY) })
 194                .await
 195                .log_err()
 196                .flatten()
 197            {
 198                Some(serde_json::from_str::<SerializedChatPanel>(&panel)?)
 199            } else {
 200                None
 201            };
 202
 203            workspace.update(&mut cx, |workspace, cx| {
 204                let panel = Self::new(workspace, cx);
 205                if let Some(serialized_panel) = serialized_panel {
 206                    panel.update(cx, |panel, cx| {
 207                        panel.width = serialized_panel.width.map(|r| r.round());
 208                        cx.notify();
 209                    });
 210                }
 211                panel
 212            })
 213        })
 214    }
 215
 216    fn serialize(&mut self, cx: &mut ViewContext<Self>) {
 217        let width = self.width;
 218        self.pending_serialization = cx.background_executor().spawn(
 219            async move {
 220                KEY_VALUE_STORE
 221                    .write_kvp(
 222                        CHAT_PANEL_KEY.into(),
 223                        serde_json::to_string(&SerializedChatPanel { width })?,
 224                    )
 225                    .await?;
 226                anyhow::Ok(())
 227            }
 228            .log_err(),
 229        );
 230    }
 231
 232    fn set_active_chat(&mut self, chat: Model<ChannelChat>, cx: &mut ViewContext<Self>) {
 233        if self.active_chat.as_ref().map(|e| &e.0) != Some(&chat) {
 234            let channel_id = chat.read(cx).channel_id;
 235            {
 236                self.markdown_data.clear();
 237
 238                let chat = chat.read(cx);
 239                let channel_name = chat.channel(cx).map(|channel| channel.name.clone());
 240                let message_count = chat.message_count();
 241                self.message_list.reset(message_count);
 242                self.message_editor.update(cx, |editor, cx| {
 243                    editor.set_channel(channel_id, channel_name, cx);
 244                    editor.clear_reply_to_message_id();
 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::UpdateMessage {
 271                message_id,
 272                message_ix,
 273            } => {
 274                self.message_list.splice(*message_ix..*message_ix + 1, 1);
 275                self.markdown_data.remove(message_id);
 276            }
 277            ChannelChatEvent::NewMessage {
 278                channel_id,
 279                message_id,
 280            } => {
 281                if !self.active {
 282                    self.channel_store.update(cx, |store, cx| {
 283                        store.update_latest_message_id(*channel_id, *message_id, cx)
 284                    })
 285                }
 286            }
 287        }
 288        cx.notify();
 289    }
 290
 291    fn acknowledge_last_message(&mut self, cx: &mut ViewContext<Self>) {
 292        if self.active && self.is_scrolled_to_bottom {
 293            if let Some((chat, _)) = &self.active_chat {
 294                if let Some(channel_id) = self.channel_id(cx) {
 295                    self.last_acknowledged_message_id = self
 296                        .channel_store
 297                        .read(cx)
 298                        .last_acknowledge_message_id(channel_id);
 299                }
 300
 301                chat.update(cx, |chat, cx| {
 302                    chat.acknowledge_last_message(cx);
 303                });
 304            }
 305        }
 306    }
 307
 308    fn render_replied_to_message(
 309        &mut self,
 310        message_id: Option<ChannelMessageId>,
 311        reply_to_message: &Option<ChannelMessage>,
 312        cx: &mut ViewContext<Self>,
 313    ) -> impl IntoElement {
 314        let reply_to_message = match reply_to_message {
 315            None => {
 316                return div().child(
 317                    h_flex()
 318                        .text_ui_xs(cx)
 319                        .my_0p5()
 320                        .px_0p5()
 321                        .gap_x_1()
 322                        .rounded_md()
 323                        .child(Icon::new(IconName::ReplyArrowRight).color(Color::Muted))
 324                        .when(reply_to_message.is_none(), |el| {
 325                            el.child(
 326                                Label::new("Message has been deleted...")
 327                                    .size(LabelSize::XSmall)
 328                                    .color(Color::Muted),
 329                            )
 330                        }),
 331                )
 332            }
 333            Some(val) => val,
 334        };
 335
 336        let user_being_replied_to = reply_to_message.sender.clone();
 337        let message_being_replied_to = reply_to_message.clone();
 338
 339        let message_element_id: ElementId = match message_id {
 340            Some(ChannelMessageId::Saved(id)) => ("reply-to-saved-message-container", id).into(),
 341            Some(ChannelMessageId::Pending(id)) => {
 342                ("reply-to-pending-message-container", id).into()
 343            } // This should never happen
 344            None => ("composing-reply-container").into(),
 345        };
 346
 347        let current_channel_id = self.channel_id(cx);
 348        let reply_to_message_id = reply_to_message.id;
 349
 350        div().child(
 351            h_flex()
 352                .id(message_element_id)
 353                .text_ui_xs(cx)
 354                .my_0p5()
 355                .px_0p5()
 356                .gap_x_1()
 357                .rounded_md()
 358                .overflow_hidden()
 359                .hover(|style| style.bg(cx.theme().colors().element_background))
 360                .child(Icon::new(IconName::ReplyArrowRight).color(Color::Muted))
 361                .child(Avatar::new(user_being_replied_to.avatar_uri.clone()).size(rems(0.7)))
 362                .child(
 363                    div().font_weight(FontWeight::SEMIBOLD).child(
 364                        Label::new(format!("@{}", user_being_replied_to.github_login))
 365                            .size(LabelSize::XSmall)
 366                            .color(Color::Muted),
 367                    ),
 368                )
 369                .child(
 370                    div().overflow_y_hidden().child(
 371                        Label::new(message_being_replied_to.body.replace('\n', " "))
 372                            .size(LabelSize::XSmall)
 373                            .color(Color::Default),
 374                    ),
 375                )
 376                .cursor(CursorStyle::PointingHand)
 377                .tooltip(|cx| Tooltip::text("Go to message", cx))
 378                .on_click(cx.listener(move |chat_panel, _, cx| {
 379                    if let Some(channel_id) = current_channel_id {
 380                        chat_panel
 381                            .select_channel(channel_id, reply_to_message_id.into(), cx)
 382                            .detach_and_log_err(cx)
 383                    }
 384                })),
 385        )
 386    }
 387
 388    fn render_message(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> impl IntoElement {
 389        let active_chat = &self.active_chat.as_ref().unwrap().0;
 390        let (message, is_continuation_from_previous, is_admin) =
 391            active_chat.update(cx, |active_chat, cx| {
 392                let is_admin = self
 393                    .channel_store
 394                    .read(cx)
 395                    .is_channel_admin(active_chat.channel_id);
 396
 397                let last_message = active_chat.message(ix.saturating_sub(1));
 398                let this_message = active_chat.message(ix).clone();
 399
 400                let duration_since_last_message = this_message.timestamp - last_message.timestamp;
 401                let is_continuation_from_previous = last_message.sender.id
 402                    == this_message.sender.id
 403                    && last_message.id != this_message.id
 404                    && duration_since_last_message < Duration::from_secs(5 * 60);
 405
 406                if let ChannelMessageId::Saved(id) = this_message.id {
 407                    if this_message
 408                        .mentions
 409                        .iter()
 410                        .any(|(_, user_id)| Some(*user_id) == self.client.user_id())
 411                    {
 412                        active_chat.acknowledge_message(id);
 413                    }
 414                }
 415
 416                (this_message, is_continuation_from_previous, is_admin)
 417            });
 418
 419        let _is_pending = message.is_pending();
 420
 421        let belongs_to_user = Some(message.sender.id) == self.client.user_id();
 422        let can_delete_message = belongs_to_user || is_admin;
 423        let can_edit_message = belongs_to_user;
 424
 425        let element_id: ElementId = match message.id {
 426            ChannelMessageId::Saved(id) => ("saved-message", id).into(),
 427            ChannelMessageId::Pending(id) => ("pending-message", id).into(),
 428        };
 429
 430        let mentioning_you = message
 431            .mentions
 432            .iter()
 433            .any(|m| Some(m.1) == self.client.user_id());
 434
 435        let message_id = match message.id {
 436            ChannelMessageId::Saved(id) => Some(id),
 437            ChannelMessageId::Pending(_) => None,
 438        };
 439
 440        let reply_to_message = message
 441            .reply_to_message_id
 442            .and_then(|id| active_chat.read(cx).find_loaded_message(id))
 443            .cloned();
 444
 445        let replied_to_you =
 446            reply_to_message.as_ref().map(|m| m.sender.id) == self.client.user_id();
 447
 448        let is_highlighted_message = self
 449            .highlighted_message
 450            .as_ref()
 451            .is_some_and(|(id, _)| Some(id) == message_id.as_ref());
 452        let background = if is_highlighted_message {
 453            cx.theme().status().info_background
 454        } else if mentioning_you || replied_to_you {
 455            cx.theme().colors().background
 456        } else {
 457            cx.theme().colors().panel_background
 458        };
 459
 460        let reply_to_message_id = self.message_editor.read(cx).reply_to_message_id();
 461
 462        v_flex()
 463            .w_full()
 464            .relative()
 465            .group("")
 466            .when(!is_continuation_from_previous, |this| this.pt_2())
 467            .child(
 468                div()
 469                    .group("")
 470                    .bg(background)
 471                    .rounded_md()
 472                    .overflow_hidden()
 473                    .px_1p5()
 474                    .py_0p5()
 475                    .when_some(reply_to_message_id, |el, reply_id| {
 476                        el.when_some(message_id, |el, message_id| {
 477                            el.when(reply_id == message_id, |el| {
 478                                el.bg(cx.theme().colors().element_selected)
 479                            })
 480                        })
 481                    })
 482                    .when(!self.has_open_menu(message_id), |this| {
 483                        this.hover(|style| style.bg(cx.theme().colors().element_hover))
 484                    })
 485                    .when(message.reply_to_message_id.is_some(), |el| {
 486                        el.child(self.render_replied_to_message(
 487                            Some(message.id),
 488                            &reply_to_message,
 489                            cx,
 490                        ))
 491                        .when(is_continuation_from_previous, |this| this.mt_2())
 492                    })
 493                    .when(
 494                        !is_continuation_from_previous || message.reply_to_message_id.is_some(),
 495                        |this| {
 496                            this.child(
 497                                h_flex()
 498                                    .text_ui_sm(cx)
 499                                    .child(
 500                                        div().absolute().child(
 501                                            Avatar::new(message.sender.avatar_uri.clone())
 502                                                .size(rems(1.)),
 503                                        ),
 504                                    )
 505                                    .child(
 506                                        div()
 507                                            .pl(cx.rem_size() + px(6.0))
 508                                            .pr(px(8.0))
 509                                            .font_weight(FontWeight::BOLD)
 510                                            .child(
 511                                                Label::new(message.sender.github_login.clone())
 512                                                    .size(LabelSize::Small),
 513                                            ),
 514                                    )
 515                                    .child(
 516                                        Label::new(time_format::format_localized_timestamp(
 517                                            message.timestamp,
 518                                            OffsetDateTime::now_utc(),
 519                                            self.local_timezone,
 520                                            time_format::TimestampFormat::EnhancedAbsolute,
 521                                        ))
 522                                        .size(LabelSize::Small)
 523                                        .color(Color::Muted),
 524                                    ),
 525                            )
 526                        },
 527                    )
 528                    .when(mentioning_you || replied_to_you, |this| this.my_0p5())
 529                    .map(|el| {
 530                        let text = self.markdown_data.entry(message.id).or_insert_with(|| {
 531                            Self::render_markdown_with_mentions(
 532                                &self.languages,
 533                                self.client.id(),
 534                                &message,
 535                                self.local_timezone,
 536                                cx,
 537                            )
 538                        });
 539                        el.child(
 540                            v_flex()
 541                                .w_full()
 542                                .text_ui_sm(cx)
 543                                .id(element_id)
 544                                .child(text.element("body".into(), cx)),
 545                        )
 546                        .when(self.has_open_menu(message_id), |el| {
 547                            el.bg(cx.theme().colors().element_selected)
 548                        })
 549                    }),
 550            )
 551            .when(
 552                self.last_acknowledged_message_id
 553                    .is_some_and(|l| Some(l) == message_id),
 554                |this| {
 555                    this.child(
 556                        h_flex()
 557                            .py_2()
 558                            .gap_1()
 559                            .items_center()
 560                            .child(div().w_full().h_0p5().bg(cx.theme().colors().border))
 561                            .child(
 562                                div()
 563                                    .px_1()
 564                                    .rounded_md()
 565                                    .text_ui_xs(cx)
 566                                    .bg(cx.theme().colors().background)
 567                                    .child("New messages"),
 568                            )
 569                            .child(div().w_full().h_0p5().bg(cx.theme().colors().border)),
 570                    )
 571                },
 572            )
 573            .child(
 574                self.render_popover_buttons(&cx, message_id, can_delete_message, can_edit_message)
 575                    .neg_mt_2p5(),
 576            )
 577    }
 578
 579    fn has_open_menu(&self, message_id: Option<u64>) -> bool {
 580        match self.open_context_menu.as_ref() {
 581            Some((id, _)) => Some(*id) == message_id,
 582            None => false,
 583        }
 584    }
 585
 586    fn render_popover_button(&self, cx: &ViewContext<Self>, child: Stateful<Div>) -> Div {
 587        div()
 588            .w_6()
 589            .bg(cx.theme().colors().element_background)
 590            .hover(|style| style.bg(cx.theme().colors().element_hover).rounded_md())
 591            .child(child)
 592    }
 593
 594    fn render_popover_buttons(
 595        &self,
 596        cx: &ViewContext<Self>,
 597        message_id: Option<u64>,
 598        can_delete_message: bool,
 599        can_edit_message: bool,
 600    ) -> Div {
 601        h_flex()
 602            .absolute()
 603            .right_2()
 604            .overflow_hidden()
 605            .rounded_md()
 606            .border_color(cx.theme().colors().element_selected)
 607            .border_1()
 608            .when(!self.has_open_menu(message_id), |el| {
 609                el.visible_on_hover("")
 610            })
 611            .bg(cx.theme().colors().element_background)
 612            .when_some(message_id, |el, message_id| {
 613                el.child(
 614                    self.render_popover_button(
 615                        cx,
 616                        div()
 617                            .id("reply")
 618                            .child(
 619                                IconButton::new(("reply", message_id), IconName::ReplyArrowRight)
 620                                    .on_click(cx.listener(move |this, _, cx| {
 621                                        this.cancel_edit_message(cx);
 622
 623                                        this.message_editor.update(cx, |editor, cx| {
 624                                            editor.set_reply_to_message_id(message_id);
 625                                            editor.focus_handle(cx).focus(cx);
 626                                        })
 627                                    })),
 628                            )
 629                            .tooltip(|cx| Tooltip::text("Reply", cx)),
 630                    ),
 631                )
 632            })
 633            .when_some(message_id, |el, message_id| {
 634                el.when(can_edit_message, |el| {
 635                    el.child(
 636                        self.render_popover_button(
 637                            cx,
 638                            div()
 639                                .id("edit")
 640                                .child(
 641                                    IconButton::new(("edit", message_id), IconName::Pencil)
 642                                        .on_click(cx.listener(move |this, _, cx| {
 643                                            this.message_editor.update(cx, |editor, cx| {
 644                                                editor.clear_reply_to_message_id();
 645
 646                                                let message = this
 647                                                    .active_chat()
 648                                                    .and_then(|active_chat| {
 649                                                        active_chat
 650                                                            .read(cx)
 651                                                            .find_loaded_message(message_id)
 652                                                    })
 653                                                    .cloned();
 654
 655                                                if let Some(message) = message {
 656                                                    let buffer = editor
 657                                                        .editor
 658                                                        .read(cx)
 659                                                        .buffer()
 660                                                        .read(cx)
 661                                                        .as_singleton()
 662                                                        .expect("message editor must be singleton");
 663
 664                                                    buffer.update(cx, |buffer, cx| {
 665                                                        buffer.set_text(message.body.clone(), cx)
 666                                                    });
 667
 668                                                    editor.set_edit_message_id(message_id);
 669                                                    editor.focus_handle(cx).focus(cx);
 670                                                }
 671                                            })
 672                                        })),
 673                                )
 674                                .tooltip(|cx| Tooltip::text("Edit", cx)),
 675                        ),
 676                    )
 677                })
 678            })
 679            .when_some(message_id, |el, message_id| {
 680                let this = cx.view().clone();
 681
 682                el.child(
 683                    self.render_popover_button(
 684                        cx,
 685                        div()
 686                            .child(
 687                                popover_menu(("menu", message_id))
 688                                    .trigger(IconButton::new(
 689                                        ("trigger", message_id),
 690                                        IconName::Ellipsis,
 691                                    ))
 692                                    .menu(move |cx| {
 693                                        Some(Self::render_message_menu(
 694                                            &this,
 695                                            message_id,
 696                                            can_delete_message,
 697                                            cx,
 698                                        ))
 699                                    }),
 700                            )
 701                            .id("more")
 702                            .tooltip(|cx| Tooltip::text("More", cx)),
 703                    ),
 704                )
 705            })
 706    }
 707
 708    fn render_message_menu(
 709        this: &View<Self>,
 710        message_id: u64,
 711        can_delete_message: bool,
 712        cx: &mut WindowContext,
 713    ) -> View<ContextMenu> {
 714        let menu = {
 715            ContextMenu::build(cx, move |menu, cx| {
 716                menu.entry(
 717                    "Copy message text",
 718                    None,
 719                    cx.handler_for(&this, move |this, cx| {
 720                        if let Some(message) = this.active_chat().and_then(|active_chat| {
 721                            active_chat.read(cx).find_loaded_message(message_id)
 722                        }) {
 723                            let text = message.body.clone();
 724                            cx.write_to_clipboard(ClipboardItem::new(text))
 725                        }
 726                    }),
 727                )
 728                .when(can_delete_message, |menu| {
 729                    menu.entry(
 730                        "Delete message",
 731                        None,
 732                        cx.handler_for(&this, move |this, cx| this.remove_message(message_id, cx)),
 733                    )
 734                })
 735            })
 736        };
 737        this.update(cx, |this, cx| {
 738            let subscription = cx.subscribe(&menu, |this: &mut Self, _, _: &DismissEvent, _| {
 739                this.open_context_menu = None;
 740            });
 741            this.open_context_menu = Some((message_id, subscription));
 742        });
 743        menu
 744    }
 745
 746    fn render_markdown_with_mentions(
 747        language_registry: &Arc<LanguageRegistry>,
 748        current_user_id: u64,
 749        message: &channel::ChannelMessage,
 750        local_timezone: UtcOffset,
 751        cx: &AppContext,
 752    ) -> RichText {
 753        let mentions = message
 754            .mentions
 755            .iter()
 756            .map(|(range, user_id)| rich_text::Mention {
 757                range: range.clone(),
 758                is_self_mention: *user_id == current_user_id,
 759            })
 760            .collect::<Vec<_>>();
 761
 762        const MESSAGE_EDITED: &str = " (edited)";
 763
 764        let mut body = message.body.clone();
 765
 766        if message.edited_at.is_some() {
 767            body.push_str(MESSAGE_EDITED);
 768        }
 769
 770        let mut rich_text = RichText::new(body, &mentions, language_registry);
 771
 772        if message.edited_at.is_some() {
 773            let range = (rich_text.text.len() - MESSAGE_EDITED.len())..rich_text.text.len();
 774            rich_text.highlights.push((
 775                range.clone(),
 776                Highlight::Highlight(HighlightStyle {
 777                    color: Some(cx.theme().colors().text_muted),
 778                    ..Default::default()
 779                }),
 780            ));
 781
 782            if let Some(edit_timestamp) = message.edited_at {
 783                let edit_timestamp_text = time_format::format_localized_timestamp(
 784                    edit_timestamp,
 785                    OffsetDateTime::now_utc(),
 786                    local_timezone,
 787                    time_format::TimestampFormat::Absolute,
 788                );
 789
 790                rich_text.custom_ranges.push(range);
 791                rich_text.set_tooltip_builder_for_custom_ranges(move |_, _, cx| {
 792                    Some(Tooltip::text(edit_timestamp_text.clone(), cx))
 793                })
 794            }
 795        }
 796        rich_text
 797    }
 798
 799    fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
 800        if let Some((chat, _)) = self.active_chat.as_ref() {
 801            let message = self
 802                .message_editor
 803                .update(cx, |editor, cx| editor.take_message(cx));
 804
 805            if let Some(id) = self.message_editor.read(cx).edit_message_id() {
 806                self.message_editor.update(cx, |editor, _| {
 807                    editor.clear_edit_message_id();
 808                });
 809
 810                if let Some(task) = chat
 811                    .update(cx, |chat, cx| chat.update_message(id, message, cx))
 812                    .log_err()
 813                {
 814                    task.detach();
 815                }
 816            } else {
 817                if let Some(task) = chat
 818                    .update(cx, |chat, cx| chat.send_message(message, cx))
 819                    .log_err()
 820                {
 821                    task.detach();
 822                }
 823            }
 824        }
 825    }
 826
 827    fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
 828        if let Some((chat, _)) = self.active_chat.as_ref() {
 829            chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
 830        }
 831    }
 832
 833    fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
 834        if let Some((chat, _)) = self.active_chat.as_ref() {
 835            chat.update(cx, |channel, cx| {
 836                if let Some(task) = channel.load_more_messages(cx) {
 837                    task.detach();
 838                }
 839            })
 840        }
 841    }
 842
 843    pub fn select_channel(
 844        &mut self,
 845        selected_channel_id: ChannelId,
 846        scroll_to_message_id: Option<u64>,
 847        cx: &mut ViewContext<ChatPanel>,
 848    ) -> Task<Result<()>> {
 849        let open_chat = self
 850            .active_chat
 851            .as_ref()
 852            .and_then(|(chat, _)| {
 853                (chat.read(cx).channel_id == selected_channel_id)
 854                    .then(|| Task::ready(anyhow::Ok(chat.clone())))
 855            })
 856            .unwrap_or_else(|| {
 857                self.channel_store.update(cx, |store, cx| {
 858                    store.open_channel_chat(selected_channel_id, cx)
 859                })
 860            });
 861
 862        cx.spawn(|this, mut cx| async move {
 863            let chat = open_chat.await?;
 864            let highlight_message_id = scroll_to_message_id;
 865            let scroll_to_message_id = this.update(&mut cx, |this, cx| {
 866                this.set_active_chat(chat.clone(), cx);
 867
 868                scroll_to_message_id.or_else(|| this.last_acknowledged_message_id)
 869            })?;
 870
 871            if let Some(message_id) = scroll_to_message_id {
 872                if let Some(item_ix) =
 873                    ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
 874                        .await
 875                {
 876                    this.update(&mut cx, |this, cx| {
 877                        if let Some(highlight_message_id) = highlight_message_id {
 878                            let task = cx.spawn({
 879                                |this, mut cx| async move {
 880                                    cx.background_executor().timer(Duration::from_secs(2)).await;
 881                                    this.update(&mut cx, |this, cx| {
 882                                        this.highlighted_message.take();
 883                                        cx.notify();
 884                                    })
 885                                    .ok();
 886                                }
 887                            });
 888
 889                            this.highlighted_message = Some((highlight_message_id, task));
 890                        }
 891
 892                        if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
 893                            this.message_list.scroll_to(ListOffset {
 894                                item_ix,
 895                                offset_in_item: px(0.0),
 896                            });
 897                            cx.notify();
 898                        }
 899                    })?;
 900                }
 901            }
 902
 903            Ok(())
 904        })
 905    }
 906
 907    fn close_reply_preview(&mut self, cx: &mut ViewContext<Self>) {
 908        self.message_editor
 909            .update(cx, |editor, _| editor.clear_reply_to_message_id());
 910    }
 911
 912    fn cancel_edit_message(&mut self, cx: &mut ViewContext<Self>) {
 913        self.message_editor.update(cx, |editor, cx| {
 914            // only clear the editor input if we were editing a message
 915            if editor.edit_message_id().is_none() {
 916                return;
 917            }
 918
 919            editor.clear_edit_message_id();
 920
 921            let buffer = editor
 922                .editor
 923                .read(cx)
 924                .buffer()
 925                .read(cx)
 926                .as_singleton()
 927                .expect("message editor must be singleton");
 928
 929            buffer.update(cx, |buffer, cx| buffer.set_text("", cx));
 930        });
 931    }
 932}
 933
 934impl Render for ChatPanel {
 935    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 936        let channel_id = self
 937            .active_chat
 938            .as_ref()
 939            .map(|(c, _)| c.read(cx).channel_id);
 940        let message_editor = self.message_editor.read(cx);
 941
 942        let reply_to_message_id = message_editor.reply_to_message_id();
 943        let edit_message_id = message_editor.edit_message_id();
 944
 945        v_flex()
 946            .key_context("ChatPanel")
 947            .track_focus(&self.focus_handle)
 948            .size_full()
 949            .on_action(cx.listener(Self::send))
 950            .child(
 951                h_flex().child(
 952                    TabBar::new("chat_header").child(
 953                        h_flex()
 954                            .w_full()
 955                            .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
 956                            .px_2()
 957                            .child(Label::new(
 958                                self.active_chat
 959                                    .as_ref()
 960                                    .and_then(|c| {
 961                                        Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
 962                                    })
 963                                    .unwrap_or("Chat".to_string()),
 964                            )),
 965                    ),
 966                ),
 967            )
 968            .child(div().flex_grow().px_2().map(|this| {
 969                if self.active_chat.is_some() {
 970                    this.child(list(self.message_list.clone()).size_full())
 971                } else {
 972                    this.child(
 973                        div()
 974                            .size_full()
 975                            .p_4()
 976                            .child(
 977                                Label::new("Select a channel to chat in.")
 978                                    .size(LabelSize::Small)
 979                                    .color(Color::Muted),
 980                            )
 981                            .child(
 982                                div().pt_1().w_full().items_center().child(
 983                                    Button::new("toggle-collab", "Open")
 984                                        .full_width()
 985                                        .key_binding(KeyBinding::for_action(
 986                                            &collab_panel::ToggleFocus,
 987                                            cx,
 988                                        ))
 989                                        .on_click(|_, cx| {
 990                                            cx.dispatch_action(
 991                                                collab_panel::ToggleFocus.boxed_clone(),
 992                                            )
 993                                        }),
 994                                ),
 995                            ),
 996                    )
 997                }
 998            }))
 999            .when(!self.is_scrolled_to_bottom, |el| {
1000                el.child(div().border_t_1().border_color(cx.theme().colors().border))
1001            })
1002            .when_some(edit_message_id, |el, _| {
1003                el.child(
1004                    h_flex()
1005                        .px_2()
1006                        .text_ui_xs(cx)
1007                        .justify_between()
1008                        .border_t_1()
1009                        .border_color(cx.theme().colors().border)
1010                        .bg(cx.theme().colors().background)
1011                        .child("Editing message")
1012                        .child(
1013                            IconButton::new("cancel-edit-message", IconName::Close)
1014                                .shape(ui::IconButtonShape::Square)
1015                                .tooltip(|cx| Tooltip::text("Cancel edit message", cx))
1016                                .on_click(cx.listener(move |this, _, cx| {
1017                                    this.cancel_edit_message(cx);
1018                                })),
1019                        ),
1020                )
1021            })
1022            .when_some(reply_to_message_id, |el, reply_to_message_id| {
1023                let reply_message = self
1024                    .active_chat()
1025                    .and_then(|active_chat| {
1026                        active_chat
1027                            .read(cx)
1028                            .find_loaded_message(reply_to_message_id)
1029                    })
1030                    .cloned();
1031
1032                el.when_some(reply_message, |el, reply_message| {
1033                    let user_being_replied_to = reply_message.sender.clone();
1034
1035                    el.child(
1036                        h_flex()
1037                            .when(!self.is_scrolled_to_bottom, |el| {
1038                                el.border_t_1().border_color(cx.theme().colors().border)
1039                            })
1040                            .justify_between()
1041                            .overflow_hidden()
1042                            .items_start()
1043                            .py_1()
1044                            .px_2()
1045                            .bg(cx.theme().colors().background)
1046                            .child(
1047                                div().flex_shrink().overflow_hidden().child(
1048                                    h_flex()
1049                                        .id(("reply-preview", reply_to_message_id))
1050                                        .child(Label::new("Replying to ").size(LabelSize::Small))
1051                                        .child(
1052                                            div().font_weight(FontWeight::BOLD).child(
1053                                                Label::new(format!(
1054                                                    "@{}",
1055                                                    user_being_replied_to.github_login.clone()
1056                                                ))
1057                                                .size(LabelSize::Small),
1058                                            ),
1059                                        )
1060                                        .when_some(channel_id, |this, channel_id| {
1061                                            this.cursor_pointer().on_click(cx.listener(
1062                                                move |chat_panel, _, cx| {
1063                                                    chat_panel
1064                                                        .select_channel(
1065                                                            channel_id,
1066                                                            reply_to_message_id.into(),
1067                                                            cx,
1068                                                        )
1069                                                        .detach_and_log_err(cx)
1070                                                },
1071                                            ))
1072                                        }),
1073                                ),
1074                            )
1075                            .child(
1076                                IconButton::new("close-reply-preview", IconName::Close)
1077                                    .shape(ui::IconButtonShape::Square)
1078                                    .tooltip(|cx| Tooltip::text("Close reply", cx))
1079                                    .on_click(cx.listener(move |this, _, cx| {
1080                                        this.close_reply_preview(cx);
1081                                    })),
1082                            ),
1083                    )
1084                })
1085            })
1086            .children(
1087                Some(
1088                    h_flex()
1089                        .p_2()
1090                        .on_action(cx.listener(|this, _: &actions::Cancel, cx| {
1091                            this.cancel_edit_message(cx);
1092                            this.close_reply_preview(cx);
1093                        }))
1094                        .map(|el| el.child(self.message_editor.clone())),
1095                )
1096                .filter(|_| self.active_chat.is_some()),
1097            )
1098            .into_any()
1099    }
1100}
1101
1102impl FocusableView for ChatPanel {
1103    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
1104        if self.active_chat.is_some() {
1105            self.message_editor.read(cx).focus_handle(cx)
1106        } else {
1107            self.focus_handle.clone()
1108        }
1109    }
1110}
1111
1112impl Panel for ChatPanel {
1113    fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
1114        ChatPanelSettings::get_global(cx).dock
1115    }
1116
1117    fn position_is_valid(&self, position: DockPosition) -> bool {
1118        matches!(position, DockPosition::Left | DockPosition::Right)
1119    }
1120
1121    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1122        settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
1123            settings.dock = Some(position)
1124        });
1125    }
1126
1127    fn size(&self, cx: &gpui::WindowContext) -> Pixels {
1128        self.width
1129            .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
1130    }
1131
1132    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1133        self.width = size;
1134        self.serialize(cx);
1135        cx.notify();
1136    }
1137
1138    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1139        self.active = active;
1140        if active {
1141            self.acknowledge_last_message(cx);
1142        }
1143    }
1144
1145    fn persistent_name() -> &'static str {
1146        "ChatPanel"
1147    }
1148
1149    fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
1150        Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
1151    }
1152
1153    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1154        Some("Chat Panel")
1155    }
1156
1157    fn toggle_action(&self) -> Box<dyn gpui::Action> {
1158        Box::new(ToggleFocus)
1159    }
1160
1161    fn starts_open(&self, cx: &WindowContext) -> bool {
1162        ActiveCall::global(cx)
1163            .read(cx)
1164            .room()
1165            .is_some_and(|room| room.read(cx).contains_guests())
1166    }
1167}
1168
1169impl EventEmitter<PanelEvent> for ChatPanel {}
1170
1171#[cfg(test)]
1172mod tests {
1173    use super::*;
1174    use gpui::HighlightStyle;
1175    use pretty_assertions::assert_eq;
1176    use rich_text::Highlight;
1177    use time::OffsetDateTime;
1178    use util::test::marked_text_ranges;
1179
1180    #[gpui::test]
1181    fn test_render_markdown_with_mentions(cx: &mut AppContext) {
1182        let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1183        let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
1184        let message = channel::ChannelMessage {
1185            id: ChannelMessageId::Saved(0),
1186            body,
1187            timestamp: OffsetDateTime::now_utc(),
1188            sender: Arc::new(client::User {
1189                github_login: "fgh".into(),
1190                avatar_uri: "avatar_fgh".into(),
1191                id: 103,
1192            }),
1193            nonce: 5,
1194            mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
1195            reply_to_message_id: None,
1196            edited_at: None,
1197        };
1198
1199        let message = ChatPanel::render_markdown_with_mentions(
1200            &language_registry,
1201            102,
1202            &message,
1203            UtcOffset::UTC,
1204            cx,
1205        );
1206
1207        // Note that the "'" was replaced with ’ due to smart punctuation.
1208        let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
1209        assert_eq!(message.text, body);
1210        assert_eq!(
1211            message.highlights,
1212            vec![
1213                (
1214                    ranges[0].clone(),
1215                    HighlightStyle {
1216                        font_style: Some(gpui::FontStyle::Italic),
1217                        ..Default::default()
1218                    }
1219                    .into()
1220                ),
1221                (ranges[1].clone(), Highlight::Mention),
1222                (
1223                    ranges[2].clone(),
1224                    HighlightStyle {
1225                        font_weight: Some(gpui::FontWeight::BOLD),
1226                        ..Default::default()
1227                    }
1228                    .into()
1229                ),
1230                (ranges[3].clone(), Highlight::SelfMention)
1231            ]
1232        );
1233    }
1234
1235    #[gpui::test]
1236    fn test_render_markdown_with_auto_detect_links(cx: &mut AppContext) {
1237        let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1238        let message = channel::ChannelMessage {
1239            id: ChannelMessageId::Saved(0),
1240            body: "Here is a link https://zed.dev to zeds website".to_string(),
1241            timestamp: OffsetDateTime::now_utc(),
1242            sender: Arc::new(client::User {
1243                github_login: "fgh".into(),
1244                avatar_uri: "avatar_fgh".into(),
1245                id: 103,
1246            }),
1247            nonce: 5,
1248            mentions: Vec::new(),
1249            reply_to_message_id: None,
1250            edited_at: None,
1251        };
1252
1253        let message = ChatPanel::render_markdown_with_mentions(
1254            &language_registry,
1255            102,
1256            &message,
1257            UtcOffset::UTC,
1258            cx,
1259        );
1260
1261        // Note that the "'" was replaced with ’ due to smart punctuation.
1262        let (body, ranges) =
1263            marked_text_ranges("Here is a link «https://zed.dev» to zeds website", false);
1264        assert_eq!(message.text, body);
1265        assert_eq!(1, ranges.len());
1266        assert_eq!(
1267            message.highlights,
1268            vec![(
1269                ranges[0].clone(),
1270                HighlightStyle {
1271                    underline: Some(gpui::UnderlineStyle {
1272                        thickness: 1.0.into(),
1273                        ..Default::default()
1274                    }),
1275                    ..Default::default()
1276                }
1277                .into()
1278            ),]
1279        );
1280    }
1281
1282    #[gpui::test]
1283    fn test_render_markdown_with_auto_detect_links_and_additional_formatting(cx: &mut AppContext) {
1284        let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1285        let message = channel::ChannelMessage {
1286            id: ChannelMessageId::Saved(0),
1287            body: "**Here is a link https://zed.dev to zeds website**".to_string(),
1288            timestamp: OffsetDateTime::now_utc(),
1289            sender: Arc::new(client::User {
1290                github_login: "fgh".into(),
1291                avatar_uri: "avatar_fgh".into(),
1292                id: 103,
1293            }),
1294            nonce: 5,
1295            mentions: Vec::new(),
1296            reply_to_message_id: None,
1297            edited_at: None,
1298        };
1299
1300        let message = ChatPanel::render_markdown_with_mentions(
1301            &language_registry,
1302            102,
1303            &message,
1304            UtcOffset::UTC,
1305            cx,
1306        );
1307
1308        // Note that the "'" was replaced with ’ due to smart punctuation.
1309        let (body, ranges) = marked_text_ranges(
1310            "«Here is a link »«https://zed.dev»« to zeds website»",
1311            false,
1312        );
1313        assert_eq!(message.text, body);
1314        assert_eq!(3, ranges.len());
1315        assert_eq!(
1316            message.highlights,
1317            vec![
1318                (
1319                    ranges[0].clone(),
1320                    HighlightStyle {
1321                        font_weight: Some(gpui::FontWeight::BOLD),
1322                        ..Default::default()
1323                    }
1324                    .into()
1325                ),
1326                (
1327                    ranges[1].clone(),
1328                    HighlightStyle {
1329                        font_weight: Some(gpui::FontWeight::BOLD),
1330                        underline: Some(gpui::UnderlineStyle {
1331                            thickness: 1.0.into(),
1332                            ..Default::default()
1333                        }),
1334                        ..Default::default()
1335                    }
1336                    .into()
1337                ),
1338                (
1339                    ranges[2].clone(),
1340                    HighlightStyle {
1341                        font_weight: Some(gpui::FontWeight::BOLD),
1342                        ..Default::default()
1343                    }
1344                    .into()
1345                ),
1346            ]
1347        );
1348    }
1349}