chat_panel.rs

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