chat_panel.rs

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