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: &'static 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        let this = cx.view().clone();
 434
 435        let mentioning_you = message
 436            .mentions
 437            .iter()
 438            .any(|m| Some(m.1) == self.client.user_id());
 439
 440        let message_id = match message.id {
 441            ChannelMessageId::Saved(id) => Some(id),
 442            ChannelMessageId::Pending(_) => None,
 443        };
 444
 445        let reply_to_message = message
 446            .reply_to_message_id
 447            .map(|id| active_chat.read(cx).find_loaded_message(id))
 448            .flatten()
 449            .cloned();
 450
 451        let replied_to_you =
 452            reply_to_message.as_ref().map(|m| m.sender.id) == self.client.user_id();
 453
 454        let is_highlighted_message = self
 455            .highlighted_message
 456            .as_ref()
 457            .is_some_and(|(id, _)| Some(id) == message_id.as_ref());
 458        let background = if is_highlighted_message {
 459            cx.theme().status().info_background
 460        } else if mentioning_you || replied_to_you {
 461            cx.theme().colors().background
 462        } else {
 463            cx.theme().colors().panel_background
 464        };
 465
 466        v_flex()
 467            .w_full()
 468            .relative()
 469            .child(
 470                div()
 471                    .bg(background)
 472                    .rounded_md()
 473                    .overflow_hidden()
 474                    .px_1()
 475                    .py_0p5()
 476                    .when(!is_continuation_from_previous, |this| {
 477                        this.mt_2().child(
 478                            h_flex()
 479                                .text_ui_sm()
 480                                .child(div().absolute().child(
 481                                    Avatar::new(message.sender.avatar_uri.clone()).size(rems(1.)),
 482                                ))
 483                                .child(
 484                                    div()
 485                                        .pl(cx.rem_size() + px(6.0))
 486                                        .pr(px(8.0))
 487                                        .font_weight(FontWeight::BOLD)
 488                                        .child(Label::new(message.sender.github_login.clone())),
 489                                )
 490                                .child(
 491                                    Label::new(time_format::format_localized_timestamp(
 492                                        OffsetDateTime::now_utc(),
 493                                        message.timestamp,
 494                                        self.local_timezone,
 495                                    ))
 496                                    .size(LabelSize::Small)
 497                                    .color(Color::Muted),
 498                                ),
 499                        )
 500                    })
 501                    .when(
 502                        message.reply_to_message_id.is_some() && reply_to_message.is_none(),
 503                        |this| {
 504                            const MESSAGE_DELETED: &str = "Message has been deleted";
 505
 506                            let body_text = StyledText::new(MESSAGE_DELETED).with_highlights(
 507                                &cx.text_style(),
 508                                vec![(
 509                                    0..MESSAGE_DELETED.len(),
 510                                    HighlightStyle {
 511                                        font_style: Some(FontStyle::Italic),
 512                                        ..Default::default()
 513                                    },
 514                                )],
 515                            );
 516
 517                            this.child(
 518                                div()
 519                                    .border_l_2()
 520                                    .text_ui_xs()
 521                                    .border_color(cx.theme().colors().border)
 522                                    .px_1()
 523                                    .py_0p5()
 524                                    .child(body_text),
 525                            )
 526                        },
 527                    )
 528                    .when_some(reply_to_message, |el, reply_to_message| {
 529                        el.child(self.render_replied_to_message(
 530                            Some(message.id),
 531                            &reply_to_message,
 532                            cx,
 533                        ))
 534                    })
 535                    .when(mentioning_you || replied_to_you, |this| this.my_0p5())
 536                    .map(|el| {
 537                        let text = self.markdown_data.entry(message.id).or_insert_with(|| {
 538                            Self::render_markdown_with_mentions(
 539                                &self.languages,
 540                                self.client.id(),
 541                                &message,
 542                            )
 543                        });
 544                        el.child(
 545                            v_flex()
 546                                .w_full()
 547                                .text_ui_sm()
 548                                .id(element_id)
 549                                .group("")
 550                                .child(text.element("body".into(), cx))
 551                                .child(
 552                                    div()
 553                                        .absolute()
 554                                        .z_index(1)
 555                                        .right_0()
 556                                        .w_6()
 557                                        .bg(background)
 558                                        .when(!self.has_open_menu(message_id), |el| {
 559                                            el.visible_on_hover("")
 560                                        })
 561                                        .when_some(message_id, |el, message_id| {
 562                                            el.child(
 563                                                popover_menu(("menu", message_id))
 564                                                    .trigger(IconButton::new(
 565                                                        ("trigger", message_id),
 566                                                        IconName::Ellipsis,
 567                                                    ))
 568                                                    .menu(move |cx| {
 569                                                        Some(Self::render_message_menu(
 570                                                            &this,
 571                                                            message_id,
 572                                                            can_delete_message,
 573                                                            cx,
 574                                                        ))
 575                                                    }),
 576                                            )
 577                                        }),
 578                                ),
 579                        )
 580                    }),
 581            )
 582            .when(
 583                self.last_acknowledged_message_id
 584                    .is_some_and(|l| Some(l) == message_id),
 585                |this| {
 586                    this.child(
 587                        h_flex()
 588                            .py_2()
 589                            .gap_1()
 590                            .items_center()
 591                            .child(div().w_full().h_0p5().bg(cx.theme().colors().border))
 592                            .child(
 593                                div()
 594                                    .px_1()
 595                                    .rounded_md()
 596                                    .text_ui_xs()
 597                                    .bg(cx.theme().colors().background)
 598                                    .child("New messages"),
 599                            )
 600                            .child(div().w_full().h_0p5().bg(cx.theme().colors().border)),
 601                    )
 602                },
 603            )
 604    }
 605
 606    fn has_open_menu(&self, message_id: Option<u64>) -> bool {
 607        match self.open_context_menu.as_ref() {
 608            Some((id, _)) => Some(*id) == message_id,
 609            None => false,
 610        }
 611    }
 612
 613    fn render_message_menu(
 614        this: &View<Self>,
 615        message_id: u64,
 616        can_delete_message: bool,
 617        cx: &mut WindowContext,
 618    ) -> View<ContextMenu> {
 619        let menu = {
 620            ContextMenu::build(cx, move |menu, cx| {
 621                menu.entry(
 622                    "Reply to message",
 623                    None,
 624                    cx.handler_for(&this, move |this, cx| {
 625                        this.message_editor.update(cx, |editor, cx| {
 626                            editor.set_reply_to_message_id(message_id);
 627                            editor.focus_handle(cx).focus(cx);
 628                        })
 629                    }),
 630                )
 631                .entry(
 632                    "Copy message text",
 633                    None,
 634                    cx.handler_for(&this, move |this, cx| {
 635                        this.active_chat().map(|active_chat| {
 636                            if let Some(message) =
 637                                active_chat.read(cx).find_loaded_message(message_id)
 638                            {
 639                                let text = message.body.clone();
 640                                cx.write_to_clipboard(ClipboardItem::new(text))
 641                            }
 642                        });
 643                    }),
 644                )
 645                .when(can_delete_message, move |menu| {
 646                    menu.entry(
 647                        "Delete message",
 648                        None,
 649                        cx.handler_for(&this, move |this, cx| this.remove_message(message_id, cx)),
 650                    )
 651                })
 652            })
 653        };
 654        this.update(cx, |this, cx| {
 655            let subscription = cx.subscribe(&menu, |this: &mut Self, _, _: &DismissEvent, _| {
 656                this.open_context_menu = None;
 657            });
 658            this.open_context_menu = Some((message_id, subscription));
 659        });
 660        menu
 661    }
 662
 663    fn render_markdown_with_mentions(
 664        language_registry: &Arc<LanguageRegistry>,
 665        current_user_id: u64,
 666        message: &channel::ChannelMessage,
 667    ) -> RichText {
 668        let mentions = message
 669            .mentions
 670            .iter()
 671            .map(|(range, user_id)| rich_text::Mention {
 672                range: range.clone(),
 673                is_self_mention: *user_id == current_user_id,
 674            })
 675            .collect::<Vec<_>>();
 676
 677        rich_text::render_rich_text(message.body.clone(), &mentions, language_registry, None)
 678    }
 679
 680    fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
 681        if let Some((chat, _)) = self.active_chat.as_ref() {
 682            let message = self
 683                .message_editor
 684                .update(cx, |editor, cx| editor.take_message(cx));
 685
 686            if let Some(task) = chat
 687                .update(cx, |chat, cx| chat.send_message(message, cx))
 688                .log_err()
 689            {
 690                task.detach();
 691            }
 692        }
 693    }
 694
 695    fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
 696        if let Some((chat, _)) = self.active_chat.as_ref() {
 697            chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
 698        }
 699    }
 700
 701    fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
 702        if let Some((chat, _)) = self.active_chat.as_ref() {
 703            chat.update(cx, |channel, cx| {
 704                if let Some(task) = channel.load_more_messages(cx) {
 705                    task.detach();
 706                }
 707            })
 708        }
 709    }
 710
 711    pub fn select_channel(
 712        &mut self,
 713        selected_channel_id: ChannelId,
 714        scroll_to_message_id: Option<u64>,
 715        cx: &mut ViewContext<ChatPanel>,
 716    ) -> Task<Result<()>> {
 717        let open_chat = self
 718            .active_chat
 719            .as_ref()
 720            .and_then(|(chat, _)| {
 721                (chat.read(cx).channel_id == selected_channel_id)
 722                    .then(|| Task::ready(anyhow::Ok(chat.clone())))
 723            })
 724            .unwrap_or_else(|| {
 725                self.channel_store.update(cx, |store, cx| {
 726                    store.open_channel_chat(selected_channel_id, cx)
 727                })
 728            });
 729
 730        cx.spawn(|this, mut cx| async move {
 731            let chat = open_chat.await?;
 732            let highlight_message_id = scroll_to_message_id;
 733            let scroll_to_message_id = this.update(&mut cx, |this, cx| {
 734                this.set_active_chat(chat.clone(), cx);
 735
 736                scroll_to_message_id.or_else(|| this.last_acknowledged_message_id)
 737            })?;
 738
 739            if let Some(message_id) = scroll_to_message_id {
 740                if let Some(item_ix) =
 741                    ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
 742                        .await
 743                {
 744                    this.update(&mut cx, |this, cx| {
 745                        if let Some(highlight_message_id) = highlight_message_id {
 746                            let task = cx.spawn({
 747                                |this, mut cx| async move {
 748                                    cx.background_executor().timer(Duration::from_secs(2)).await;
 749                                    this.update(&mut cx, |this, cx| {
 750                                        this.highlighted_message.take();
 751                                        cx.notify();
 752                                    })
 753                                    .ok();
 754                                }
 755                            });
 756
 757                            this.highlighted_message = Some((highlight_message_id, task));
 758                        }
 759
 760                        if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
 761                            this.message_list.scroll_to(ListOffset {
 762                                item_ix,
 763                                offset_in_item: px(0.0),
 764                            });
 765                            cx.notify();
 766                        }
 767                    })?;
 768                }
 769            }
 770
 771            Ok(())
 772        })
 773    }
 774
 775    fn close_reply_preview(&mut self, _: &CloseReplyPreview, cx: &mut ViewContext<Self>) {
 776        self.message_editor
 777            .update(cx, |editor, _| editor.clear_reply_to_message_id());
 778    }
 779}
 780
 781impl Render for ChatPanel {
 782    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 783        let reply_to_message_id = self.message_editor.read(cx).reply_to_message_id();
 784
 785        v_flex()
 786            .key_context("ChatPanel")
 787            .track_focus(&self.focus_handle)
 788            .size_full()
 789            .on_action(cx.listener(Self::send))
 790            .child(
 791                h_flex().z_index(1).child(
 792                    TabBar::new("chat_header").child(
 793                        h_flex()
 794                            .w_full()
 795                            .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
 796                            .px_2()
 797                            .child(Label::new(
 798                                self.active_chat
 799                                    .as_ref()
 800                                    .and_then(|c| {
 801                                        Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
 802                                    })
 803                                    .unwrap_or("Chat".to_string()),
 804                            )),
 805                    ),
 806                ),
 807            )
 808            .child(div().flex_grow().px_2().map(|this| {
 809                if self.active_chat.is_some() {
 810                    this.child(list(self.message_list.clone()).size_full())
 811                } else {
 812                    this.child(
 813                        div()
 814                            .size_full()
 815                            .p_4()
 816                            .child(
 817                                Label::new("Select a channel to chat in.")
 818                                    .size(LabelSize::Small)
 819                                    .color(Color::Muted),
 820                            )
 821                            .child(
 822                                div().pt_1().w_full().items_center().child(
 823                                    Button::new("toggle-collab", "Open")
 824                                        .full_width()
 825                                        .key_binding(KeyBinding::for_action(
 826                                            &collab_panel::ToggleFocus,
 827                                            cx,
 828                                        ))
 829                                        .on_click(|_, cx| {
 830                                            cx.dispatch_action(
 831                                                collab_panel::ToggleFocus.boxed_clone(),
 832                                            )
 833                                        }),
 834                                ),
 835                            ),
 836                    )
 837                }
 838            }))
 839            .when_some(reply_to_message_id, |el, reply_to_message_id| {
 840                let reply_message = self
 841                    .active_chat()
 842                    .map(|active_chat| {
 843                        active_chat.read(cx).messages().iter().find_map(|m| {
 844                            if m.id == ChannelMessageId::Saved(reply_to_message_id) {
 845                                Some(m)
 846                            } else {
 847                                None
 848                            }
 849                        })
 850                    })
 851                    .flatten()
 852                    .cloned();
 853
 854                el.when_some(reply_message, |el, reply_message| {
 855                    el.child(
 856                        h_flex()
 857                            .when(!self.is_scrolled_to_bottom, |el| {
 858                                el.border_t_1().border_color(cx.theme().colors().border)
 859                            })
 860                            .justify_between()
 861                            .overflow_hidden()
 862                            .items_start()
 863                            .py_1()
 864                            .px_2()
 865                            .bg(cx.theme().colors().background)
 866                            .child(
 867                                div().flex_shrink().overflow_hidden().child(
 868                                    self.render_replied_to_message(None, &reply_message, cx),
 869                                ),
 870                            )
 871                            .child(
 872                                IconButton::new("close-reply-preview", IconName::Close)
 873                                    .shape(ui::IconButtonShape::Square)
 874                                    .tooltip(|cx| {
 875                                        Tooltip::for_action(
 876                                            "Close reply preview",
 877                                            &CloseReplyPreview,
 878                                            cx,
 879                                        )
 880                                    })
 881                                    .on_click(cx.listener(move |_, _, cx| {
 882                                        cx.dispatch_action(CloseReplyPreview.boxed_clone())
 883                                    })),
 884                            ),
 885                    )
 886                })
 887            })
 888            .children(
 889                Some(
 890                    h_flex()
 891                        .key_context("MessageEditor")
 892                        .on_action(cx.listener(ChatPanel::close_reply_preview))
 893                        .when(
 894                            !self.is_scrolled_to_bottom && reply_to_message_id.is_none(),
 895                            |el| el.border_t_1().border_color(cx.theme().colors().border),
 896                        )
 897                        .p_2()
 898                        .map(|el| el.child(self.message_editor.clone())),
 899                )
 900                .filter(|_| self.active_chat.is_some()),
 901            )
 902            .into_any()
 903    }
 904}
 905
 906impl FocusableView for ChatPanel {
 907    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
 908        if self.active_chat.is_some() {
 909            self.message_editor.read(cx).focus_handle(cx)
 910        } else {
 911            self.focus_handle.clone()
 912        }
 913    }
 914}
 915
 916impl Panel for ChatPanel {
 917    fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
 918        ChatPanelSettings::get_global(cx).dock
 919    }
 920
 921    fn position_is_valid(&self, position: DockPosition) -> bool {
 922        matches!(position, DockPosition::Left | DockPosition::Right)
 923    }
 924
 925    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
 926        settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
 927            settings.dock = Some(position)
 928        });
 929    }
 930
 931    fn size(&self, cx: &gpui::WindowContext) -> Pixels {
 932        self.width
 933            .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
 934    }
 935
 936    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
 937        self.width = size;
 938        self.serialize(cx);
 939        cx.notify();
 940    }
 941
 942    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
 943        self.active = active;
 944        if active {
 945            self.acknowledge_last_message(cx);
 946        }
 947    }
 948
 949    fn persistent_name() -> &'static str {
 950        "ChatPanel"
 951    }
 952
 953    fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
 954        Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
 955    }
 956
 957    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
 958        Some("Chat Panel")
 959    }
 960
 961    fn toggle_action(&self) -> Box<dyn gpui::Action> {
 962        Box::new(ToggleFocus)
 963    }
 964
 965    fn starts_open(&self, cx: &WindowContext) -> bool {
 966        ActiveCall::global(cx)
 967            .read(cx)
 968            .room()
 969            .is_some_and(|room| room.read(cx).contains_guests())
 970    }
 971}
 972
 973impl EventEmitter<PanelEvent> for ChatPanel {}
 974
 975#[cfg(test)]
 976mod tests {
 977    use super::*;
 978    use gpui::HighlightStyle;
 979    use pretty_assertions::assert_eq;
 980    use rich_text::Highlight;
 981    use time::OffsetDateTime;
 982    use util::test::marked_text_ranges;
 983
 984    #[gpui::test]
 985    fn test_render_markdown_with_mentions() {
 986        let language_registry = Arc::new(LanguageRegistry::test());
 987        let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
 988        let message = channel::ChannelMessage {
 989            id: ChannelMessageId::Saved(0),
 990            body,
 991            timestamp: OffsetDateTime::now_utc(),
 992            sender: Arc::new(client::User {
 993                github_login: "fgh".into(),
 994                avatar_uri: "avatar_fgh".into(),
 995                id: 103,
 996            }),
 997            nonce: 5,
 998            mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
 999            reply_to_message_id: None,
1000        };
1001
1002        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
1003
1004        // Note that the "'" was replaced with ’ due to smart punctuation.
1005        let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
1006        assert_eq!(message.text, body);
1007        assert_eq!(
1008            message.highlights,
1009            vec![
1010                (
1011                    ranges[0].clone(),
1012                    HighlightStyle {
1013                        font_style: Some(gpui::FontStyle::Italic),
1014                        ..Default::default()
1015                    }
1016                    .into()
1017                ),
1018                (ranges[1].clone(), Highlight::Mention),
1019                (
1020                    ranges[2].clone(),
1021                    HighlightStyle {
1022                        font_weight: Some(gpui::FontWeight::BOLD),
1023                        ..Default::default()
1024                    }
1025                    .into()
1026                ),
1027                (ranges[3].clone(), Highlight::SelfMention)
1028            ]
1029        );
1030    }
1031
1032    #[gpui::test]
1033    fn test_render_markdown_with_auto_detect_links() {
1034        let language_registry = Arc::new(LanguageRegistry::test());
1035        let message = channel::ChannelMessage {
1036            id: ChannelMessageId::Saved(0),
1037            body: "Here is a link https://zed.dev to zeds website".to_string(),
1038            timestamp: OffsetDateTime::now_utc(),
1039            sender: Arc::new(client::User {
1040                github_login: "fgh".into(),
1041                avatar_uri: "avatar_fgh".into(),
1042                id: 103,
1043            }),
1044            nonce: 5,
1045            mentions: Vec::new(),
1046            reply_to_message_id: None,
1047        };
1048
1049        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
1050
1051        // Note that the "'" was replaced with ’ due to smart punctuation.
1052        let (body, ranges) =
1053            marked_text_ranges("Here is a link «https://zed.dev» to zeds website", false);
1054        assert_eq!(message.text, body);
1055        assert_eq!(1, ranges.len());
1056        assert_eq!(
1057            message.highlights,
1058            vec![(
1059                ranges[0].clone(),
1060                HighlightStyle {
1061                    underline: Some(gpui::UnderlineStyle {
1062                        thickness: 1.0.into(),
1063                        ..Default::default()
1064                    }),
1065                    ..Default::default()
1066                }
1067                .into()
1068            ),]
1069        );
1070    }
1071
1072    #[gpui::test]
1073    fn test_render_markdown_with_auto_detect_links_and_additional_formatting() {
1074        let language_registry = Arc::new(LanguageRegistry::test());
1075        let message = channel::ChannelMessage {
1076            id: ChannelMessageId::Saved(0),
1077            body: "**Here is a link https://zed.dev to zeds website**".to_string(),
1078            timestamp: OffsetDateTime::now_utc(),
1079            sender: Arc::new(client::User {
1080                github_login: "fgh".into(),
1081                avatar_uri: "avatar_fgh".into(),
1082                id: 103,
1083            }),
1084            nonce: 5,
1085            mentions: Vec::new(),
1086            reply_to_message_id: None,
1087        };
1088
1089        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
1090
1091        // Note that the "'" was replaced with ’ due to smart punctuation.
1092        let (body, ranges) = marked_text_ranges(
1093            "«Here is a link »«https://zed.dev»« to zeds website»",
1094            false,
1095        );
1096        assert_eq!(message.text, body);
1097        assert_eq!(3, ranges.len());
1098        assert_eq!(
1099            message.highlights,
1100            vec![
1101                (
1102                    ranges[0].clone(),
1103                    HighlightStyle {
1104                        font_weight: Some(gpui::FontWeight::BOLD),
1105                        ..Default::default()
1106                    }
1107                    .into()
1108                ),
1109                (
1110                    ranges[1].clone(),
1111                    HighlightStyle {
1112                        font_weight: Some(gpui::FontWeight::BOLD),
1113                        underline: Some(gpui::UnderlineStyle {
1114                            thickness: 1.0.into(),
1115                            ..Default::default()
1116                        }),
1117                        ..Default::default()
1118                    }
1119                    .into()
1120                ),
1121                (
1122                    ranges[2].clone(),
1123                    HighlightStyle {
1124                        font_weight: Some(gpui::FontWeight::BOLD),
1125                        ..Default::default()
1126                    }
1127                    .into()
1128                ),
1129            ]
1130        );
1131    }
1132}