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