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