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::Left { 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.message_editor.update(cx, |editor, cx| {
 619                                            editor.set_reply_to_message_id(message_id);
 620                                            editor.focus_handle(cx).focus(cx);
 621                                        })
 622                                    })),
 623                            )
 624                            .tooltip(|cx| Tooltip::text("Reply", cx)),
 625                    ),
 626                )
 627            })
 628            .when_some(message_id, |el, message_id| {
 629                el.when(can_edit_message, |el| {
 630                    el.child(
 631                        self.render_popover_button(
 632                            cx,
 633                            div()
 634                                .id("edit")
 635                                .child(
 636                                    IconButton::new(("edit", message_id), IconName::Pencil)
 637                                        .on_click(cx.listener(move |this, _, cx| {
 638                                            this.message_editor.update(cx, |editor, cx| {
 639                                                let message = this
 640                                                    .active_chat()
 641                                                    .and_then(|active_chat| {
 642                                                        active_chat
 643                                                            .read(cx)
 644                                                            .find_loaded_message(message_id)
 645                                                    })
 646                                                    .cloned();
 647
 648                                                if let Some(message) = message {
 649                                                    let buffer = editor
 650                                                        .editor
 651                                                        .read(cx)
 652                                                        .buffer()
 653                                                        .read(cx)
 654                                                        .as_singleton()
 655                                                        .expect("message editor must be singleton");
 656
 657                                                    buffer.update(cx, |buffer, cx| {
 658                                                        buffer.set_text(message.body.clone(), cx)
 659                                                    });
 660
 661                                                    editor.set_edit_message_id(message_id);
 662                                                    editor.focus_handle(cx).focus(cx);
 663                                                }
 664                                            })
 665                                        })),
 666                                )
 667                                .tooltip(|cx| Tooltip::text("Edit", cx)),
 668                        ),
 669                    )
 670                })
 671            })
 672            .when_some(message_id, |el, message_id| {
 673                let this = cx.view().clone();
 674
 675                el.child(
 676                    self.render_popover_button(
 677                        cx,
 678                        div()
 679                            .child(
 680                                popover_menu(("menu", message_id))
 681                                    .trigger(IconButton::new(
 682                                        ("trigger", message_id),
 683                                        IconName::Ellipsis,
 684                                    ))
 685                                    .menu(move |cx| {
 686                                        Some(Self::render_message_menu(
 687                                            &this,
 688                                            message_id,
 689                                            can_delete_message,
 690                                            cx,
 691                                        ))
 692                                    }),
 693                            )
 694                            .id("more")
 695                            .tooltip(|cx| Tooltip::text("More", cx)),
 696                    ),
 697                )
 698            })
 699    }
 700
 701    fn render_message_menu(
 702        this: &View<Self>,
 703        message_id: u64,
 704        can_delete_message: bool,
 705        cx: &mut WindowContext,
 706    ) -> View<ContextMenu> {
 707        let menu = {
 708            ContextMenu::build(cx, move |menu, cx| {
 709                menu.entry(
 710                    "Copy message text",
 711                    None,
 712                    cx.handler_for(&this, move |this, cx| {
 713                        if let Some(message) = this.active_chat().and_then(|active_chat| {
 714                            active_chat.read(cx).find_loaded_message(message_id)
 715                        }) {
 716                            let text = message.body.clone();
 717                            cx.write_to_clipboard(ClipboardItem::new(text))
 718                        }
 719                    }),
 720                )
 721                .when(can_delete_message, |menu| {
 722                    menu.entry(
 723                        "Delete message",
 724                        None,
 725                        cx.handler_for(&this, move |this, cx| this.remove_message(message_id, cx)),
 726                    )
 727                })
 728            })
 729        };
 730        this.update(cx, |this, cx| {
 731            let subscription = cx.subscribe(&menu, |this: &mut Self, _, _: &DismissEvent, _| {
 732                this.open_context_menu = None;
 733            });
 734            this.open_context_menu = Some((message_id, subscription));
 735        });
 736        menu
 737    }
 738
 739    fn render_markdown_with_mentions(
 740        language_registry: &Arc<LanguageRegistry>,
 741        current_user_id: u64,
 742        message: &channel::ChannelMessage,
 743    ) -> RichText {
 744        let mentions = message
 745            .mentions
 746            .iter()
 747            .map(|(range, user_id)| rich_text::Mention {
 748                range: range.clone(),
 749                is_self_mention: *user_id == current_user_id,
 750            })
 751            .collect::<Vec<_>>();
 752
 753        const MESSAGE_UPDATED: &str = " (edited)";
 754
 755        let mut body = message.body.clone();
 756
 757        if message.edited_at.is_some() {
 758            body.push_str(MESSAGE_UPDATED);
 759        }
 760
 761        let mut rich_text = rich_text::render_rich_text(body, &mentions, language_registry, None);
 762
 763        if message.edited_at.is_some() {
 764            rich_text.highlights.push((
 765                (rich_text.text.len() - MESSAGE_UPDATED.len())..rich_text.text.len(),
 766                Highlight::Highlight(HighlightStyle {
 767                    fade_out: Some(0.8),
 768                    ..Default::default()
 769                }),
 770            ));
 771        }
 772        rich_text
 773    }
 774
 775    fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
 776        if let Some((chat, _)) = self.active_chat.as_ref() {
 777            let message = self
 778                .message_editor
 779                .update(cx, |editor, cx| editor.take_message(cx));
 780
 781            if let Some(id) = self.message_editor.read(cx).edit_message_id() {
 782                self.message_editor.update(cx, |editor, _| {
 783                    editor.clear_edit_message_id();
 784                });
 785
 786                if let Some(task) = chat
 787                    .update(cx, |chat, cx| chat.update_message(id, message, cx))
 788                    .log_err()
 789                {
 790                    task.detach();
 791                }
 792            } else {
 793                if let Some(task) = chat
 794                    .update(cx, |chat, cx| chat.send_message(message, cx))
 795                    .log_err()
 796                {
 797                    task.detach();
 798                }
 799            }
 800        }
 801    }
 802
 803    fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
 804        if let Some((chat, _)) = self.active_chat.as_ref() {
 805            chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
 806        }
 807    }
 808
 809    fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
 810        if let Some((chat, _)) = self.active_chat.as_ref() {
 811            chat.update(cx, |channel, cx| {
 812                if let Some(task) = channel.load_more_messages(cx) {
 813                    task.detach();
 814                }
 815            })
 816        }
 817    }
 818
 819    pub fn select_channel(
 820        &mut self,
 821        selected_channel_id: ChannelId,
 822        scroll_to_message_id: Option<u64>,
 823        cx: &mut ViewContext<ChatPanel>,
 824    ) -> Task<Result<()>> {
 825        let open_chat = self
 826            .active_chat
 827            .as_ref()
 828            .and_then(|(chat, _)| {
 829                (chat.read(cx).channel_id == selected_channel_id)
 830                    .then(|| Task::ready(anyhow::Ok(chat.clone())))
 831            })
 832            .unwrap_or_else(|| {
 833                self.channel_store.update(cx, |store, cx| {
 834                    store.open_channel_chat(selected_channel_id, cx)
 835                })
 836            });
 837
 838        cx.spawn(|this, mut cx| async move {
 839            let chat = open_chat.await?;
 840            let highlight_message_id = scroll_to_message_id;
 841            let scroll_to_message_id = this.update(&mut cx, |this, cx| {
 842                this.set_active_chat(chat.clone(), cx);
 843
 844                scroll_to_message_id.or_else(|| this.last_acknowledged_message_id)
 845            })?;
 846
 847            if let Some(message_id) = scroll_to_message_id {
 848                if let Some(item_ix) =
 849                    ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
 850                        .await
 851                {
 852                    this.update(&mut cx, |this, cx| {
 853                        if let Some(highlight_message_id) = highlight_message_id {
 854                            let task = cx.spawn({
 855                                |this, mut cx| async move {
 856                                    cx.background_executor().timer(Duration::from_secs(2)).await;
 857                                    this.update(&mut cx, |this, cx| {
 858                                        this.highlighted_message.take();
 859                                        cx.notify();
 860                                    })
 861                                    .ok();
 862                                }
 863                            });
 864
 865                            this.highlighted_message = Some((highlight_message_id, task));
 866                        }
 867
 868                        if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
 869                            this.message_list.scroll_to(ListOffset {
 870                                item_ix,
 871                                offset_in_item: px(0.0),
 872                            });
 873                            cx.notify();
 874                        }
 875                    })?;
 876                }
 877            }
 878
 879            Ok(())
 880        })
 881    }
 882
 883    fn close_reply_preview(&mut self, cx: &mut ViewContext<Self>) {
 884        self.message_editor
 885            .update(cx, |editor, _| editor.clear_reply_to_message_id());
 886    }
 887
 888    fn cancel_edit_message(&mut self, cx: &mut ViewContext<Self>) {
 889        self.message_editor.update(cx, |editor, cx| {
 890            // only clear the editor input if we were editing a message
 891            if editor.edit_message_id().is_none() {
 892                return;
 893            }
 894
 895            editor.clear_edit_message_id();
 896
 897            let buffer = editor
 898                .editor
 899                .read(cx)
 900                .buffer()
 901                .read(cx)
 902                .as_singleton()
 903                .expect("message editor must be singleton");
 904
 905            buffer.update(cx, |buffer, cx| buffer.set_text("", cx));
 906        });
 907    }
 908}
 909
 910impl Render for ChatPanel {
 911    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 912        let message_editor = self.message_editor.read(cx);
 913
 914        let reply_to_message_id = message_editor.reply_to_message_id();
 915        let edit_message_id = message_editor.edit_message_id();
 916
 917        v_flex()
 918            .key_context("ChatPanel")
 919            .track_focus(&self.focus_handle)
 920            .size_full()
 921            .on_action(cx.listener(Self::send))
 922            .child(
 923                h_flex().child(
 924                    TabBar::new("chat_header").child(
 925                        h_flex()
 926                            .w_full()
 927                            .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
 928                            .px_2()
 929                            .child(Label::new(
 930                                self.active_chat
 931                                    .as_ref()
 932                                    .and_then(|c| {
 933                                        Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
 934                                    })
 935                                    .unwrap_or("Chat".to_string()),
 936                            )),
 937                    ),
 938                ),
 939            )
 940            .child(div().flex_grow().px_2().map(|this| {
 941                if self.active_chat.is_some() {
 942                    this.child(list(self.message_list.clone()).size_full())
 943                } else {
 944                    this.child(
 945                        div()
 946                            .size_full()
 947                            .p_4()
 948                            .child(
 949                                Label::new("Select a channel to chat in.")
 950                                    .size(LabelSize::Small)
 951                                    .color(Color::Muted),
 952                            )
 953                            .child(
 954                                div().pt_1().w_full().items_center().child(
 955                                    Button::new("toggle-collab", "Open")
 956                                        .full_width()
 957                                        .key_binding(KeyBinding::for_action(
 958                                            &collab_panel::ToggleFocus,
 959                                            cx,
 960                                        ))
 961                                        .on_click(|_, cx| {
 962                                            cx.dispatch_action(
 963                                                collab_panel::ToggleFocus.boxed_clone(),
 964                                            )
 965                                        }),
 966                                ),
 967                            ),
 968                    )
 969                }
 970            }))
 971            .when(!self.is_scrolled_to_bottom, |el| {
 972                el.child(div().border_t_1().border_color(cx.theme().colors().border))
 973            })
 974            .when_some(edit_message_id, |el, _| {
 975                el.child(
 976                    h_flex()
 977                        .px_2()
 978                        .text_ui_xs()
 979                        .justify_between()
 980                        .border_t_1()
 981                        .border_color(cx.theme().colors().border)
 982                        .bg(cx.theme().colors().background)
 983                        .child("Editing message")
 984                        .child(
 985                            IconButton::new("cancel-edit-message", IconName::Close)
 986                                .shape(ui::IconButtonShape::Square)
 987                                .tooltip(|cx| Tooltip::text("Cancel edit message", cx))
 988                                .on_click(cx.listener(move |this, _, cx| {
 989                                    this.cancel_edit_message(cx);
 990                                })),
 991                        ),
 992                )
 993            })
 994            .when_some(reply_to_message_id, |el, reply_to_message_id| {
 995                let reply_message = self
 996                    .active_chat()
 997                    .and_then(|active_chat| {
 998                        active_chat
 999                            .read(cx)
1000                            .find_loaded_message(reply_to_message_id)
1001                    })
1002                    .cloned();
1003
1004                el.when_some(reply_message, |el, reply_message| {
1005                    let user_being_replied_to = reply_message.sender.clone();
1006
1007                    el.child(
1008                        h_flex()
1009                            .when(!self.is_scrolled_to_bottom, |el| {
1010                                el.border_t_1().border_color(cx.theme().colors().border)
1011                            })
1012                            .justify_between()
1013                            .overflow_hidden()
1014                            .items_start()
1015                            .py_1()
1016                            .px_2()
1017                            .bg(cx.theme().colors().background)
1018                            .child(
1019                                div().flex_shrink().overflow_hidden().child(
1020                                    h_flex()
1021                                        .child(Label::new("Replying to ").size(LabelSize::Small))
1022                                        .child(
1023                                            div().font_weight(FontWeight::BOLD).child(
1024                                                Label::new(format!(
1025                                                    "@{}",
1026                                                    user_being_replied_to.github_login.clone()
1027                                                ))
1028                                                .size(LabelSize::Small),
1029                                            ),
1030                                        ),
1031                                ),
1032                            )
1033                            .child(
1034                                IconButton::new("close-reply-preview", IconName::Close)
1035                                    .shape(ui::IconButtonShape::Square)
1036                                    .tooltip(|cx| Tooltip::text("Close reply", cx))
1037                                    .on_click(cx.listener(move |this, _, cx| {
1038                                        this.close_reply_preview(cx);
1039                                    })),
1040                            ),
1041                    )
1042                })
1043            })
1044            .children(
1045                Some(
1046                    h_flex()
1047                        .p_2()
1048                        .on_action(cx.listener(|this, _: &actions::Cancel, cx| {
1049                            this.cancel_edit_message(cx);
1050                            this.close_reply_preview(cx);
1051                        }))
1052                        .map(|el| el.child(self.message_editor.clone())),
1053                )
1054                .filter(|_| self.active_chat.is_some()),
1055            )
1056            .into_any()
1057    }
1058}
1059
1060impl FocusableView for ChatPanel {
1061    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
1062        if self.active_chat.is_some() {
1063            self.message_editor.read(cx).focus_handle(cx)
1064        } else {
1065            self.focus_handle.clone()
1066        }
1067    }
1068}
1069
1070impl Panel for ChatPanel {
1071    fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
1072        ChatPanelSettings::get_global(cx).dock
1073    }
1074
1075    fn position_is_valid(&self, position: DockPosition) -> bool {
1076        matches!(position, DockPosition::Left | DockPosition::Right)
1077    }
1078
1079    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1080        settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
1081            settings.dock = Some(position)
1082        });
1083    }
1084
1085    fn size(&self, cx: &gpui::WindowContext) -> Pixels {
1086        self.width
1087            .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
1088    }
1089
1090    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1091        self.width = size;
1092        self.serialize(cx);
1093        cx.notify();
1094    }
1095
1096    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1097        self.active = active;
1098        if active {
1099            self.acknowledge_last_message(cx);
1100        }
1101    }
1102
1103    fn persistent_name() -> &'static str {
1104        "ChatPanel"
1105    }
1106
1107    fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
1108        Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
1109    }
1110
1111    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1112        Some("Chat Panel")
1113    }
1114
1115    fn toggle_action(&self) -> Box<dyn gpui::Action> {
1116        Box::new(ToggleFocus)
1117    }
1118
1119    fn starts_open(&self, cx: &WindowContext) -> bool {
1120        ActiveCall::global(cx)
1121            .read(cx)
1122            .room()
1123            .is_some_and(|room| room.read(cx).contains_guests())
1124    }
1125}
1126
1127impl EventEmitter<PanelEvent> for ChatPanel {}
1128
1129#[cfg(test)]
1130mod tests {
1131    use super::*;
1132    use gpui::HighlightStyle;
1133    use pretty_assertions::assert_eq;
1134    use rich_text::Highlight;
1135    use time::OffsetDateTime;
1136    use util::test::marked_text_ranges;
1137
1138    #[gpui::test]
1139    fn test_render_markdown_with_mentions(cx: &mut AppContext) {
1140        let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1141        let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
1142        let message = channel::ChannelMessage {
1143            id: ChannelMessageId::Saved(0),
1144            body,
1145            timestamp: OffsetDateTime::now_utc(),
1146            sender: Arc::new(client::User {
1147                github_login: "fgh".into(),
1148                avatar_uri: "avatar_fgh".into(),
1149                id: 103,
1150            }),
1151            nonce: 5,
1152            mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
1153            reply_to_message_id: None,
1154            edited_at: None,
1155        };
1156
1157        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
1158
1159        // Note that the "'" was replaced with ’ due to smart punctuation.
1160        let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
1161        assert_eq!(message.text, body);
1162        assert_eq!(
1163            message.highlights,
1164            vec![
1165                (
1166                    ranges[0].clone(),
1167                    HighlightStyle {
1168                        font_style: Some(gpui::FontStyle::Italic),
1169                        ..Default::default()
1170                    }
1171                    .into()
1172                ),
1173                (ranges[1].clone(), Highlight::Mention),
1174                (
1175                    ranges[2].clone(),
1176                    HighlightStyle {
1177                        font_weight: Some(gpui::FontWeight::BOLD),
1178                        ..Default::default()
1179                    }
1180                    .into()
1181                ),
1182                (ranges[3].clone(), Highlight::SelfMention)
1183            ]
1184        );
1185    }
1186
1187    #[gpui::test]
1188    fn test_render_markdown_with_auto_detect_links(cx: &mut AppContext) {
1189        let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1190        let message = channel::ChannelMessage {
1191            id: ChannelMessageId::Saved(0),
1192            body: "Here is a link https://zed.dev to zeds website".to_string(),
1193            timestamp: OffsetDateTime::now_utc(),
1194            sender: Arc::new(client::User {
1195                github_login: "fgh".into(),
1196                avatar_uri: "avatar_fgh".into(),
1197                id: 103,
1198            }),
1199            nonce: 5,
1200            mentions: Vec::new(),
1201            reply_to_message_id: None,
1202            edited_at: None,
1203        };
1204
1205        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
1206
1207        // Note that the "'" was replaced with ’ due to smart punctuation.
1208        let (body, ranges) =
1209            marked_text_ranges("Here is a link «https://zed.dev» to zeds website", false);
1210        assert_eq!(message.text, body);
1211        assert_eq!(1, ranges.len());
1212        assert_eq!(
1213            message.highlights,
1214            vec![(
1215                ranges[0].clone(),
1216                HighlightStyle {
1217                    underline: Some(gpui::UnderlineStyle {
1218                        thickness: 1.0.into(),
1219                        ..Default::default()
1220                    }),
1221                    ..Default::default()
1222                }
1223                .into()
1224            ),]
1225        );
1226    }
1227
1228    #[gpui::test]
1229    fn test_render_markdown_with_auto_detect_links_and_additional_formatting(cx: &mut AppContext) {
1230        let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1231        let message = channel::ChannelMessage {
1232            id: ChannelMessageId::Saved(0),
1233            body: "**Here is a link https://zed.dev to zeds website**".to_string(),
1234            timestamp: OffsetDateTime::now_utc(),
1235            sender: Arc::new(client::User {
1236                github_login: "fgh".into(),
1237                avatar_uri: "avatar_fgh".into(),
1238                id: 103,
1239            }),
1240            nonce: 5,
1241            mentions: Vec::new(),
1242            reply_to_message_id: None,
1243            edited_at: None,
1244        };
1245
1246        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
1247
1248        // Note that the "'" was replaced with ’ due to smart punctuation.
1249        let (body, ranges) = marked_text_ranges(
1250            "«Here is a link »«https://zed.dev»« to zeds website»",
1251            false,
1252        );
1253        assert_eq!(message.text, body);
1254        assert_eq!(3, ranges.len());
1255        assert_eq!(
1256            message.highlights,
1257            vec![
1258                (
1259                    ranges[0].clone(),
1260                    HighlightStyle {
1261                        font_weight: Some(gpui::FontWeight::BOLD),
1262                        ..Default::default()
1263                    }
1264                    .into()
1265                ),
1266                (
1267                    ranges[1].clone(),
1268                    HighlightStyle {
1269                        font_weight: Some(gpui::FontWeight::BOLD),
1270                        underline: Some(gpui::UnderlineStyle {
1271                            thickness: 1.0.into(),
1272                            ..Default::default()
1273                        }),
1274                        ..Default::default()
1275                    }
1276                    .into()
1277                ),
1278                (
1279                    ranges[2].clone(),
1280                    HighlightStyle {
1281                        font_weight: Some(gpui::FontWeight::BOLD),
1282                        ..Default::default()
1283                    }
1284                    .into()
1285                ),
1286            ]
1287        );
1288    }
1289}