chat_panel.rs

   1use crate::{collab_panel, ChatPanelSettings};
   2use anyhow::Result;
   3use call::{room, ActiveCall};
   4use channel::{ChannelChat, ChannelChatEvent, ChannelMessage, ChannelMessageId, ChannelStore};
   5use client::Client;
   6use collections::HashMap;
   7use db::kvp::KEY_VALUE_STORE;
   8use editor::Editor;
   9use gpui::{
  10    actions, div, list, prelude::*, px, Action, AppContext, AsyncWindowContext, CursorStyle,
  11    DismissEvent, ElementId, EventEmitter, FocusHandle, FocusableView, FontStyle, FontWeight,
  12    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}
  67
  68#[derive(Serialize, Deserialize)]
  69struct SerializedChatPanel {
  70    width: Option<Pixels>,
  71}
  72
  73actions!(chat_panel, [ToggleFocus]);
  74
  75impl ChatPanel {
  76    pub fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> View<Self> {
  77        let fs = workspace.app_state().fs.clone();
  78        let client = workspace.app_state().client.clone();
  79        let channel_store = ChannelStore::global(cx);
  80        let languages = workspace.app_state().languages.clone();
  81
  82        let input_editor = cx.new_view(|cx| {
  83            MessageEditor::new(
  84                languages.clone(),
  85                channel_store.clone(),
  86                cx.new_view(|cx| Editor::auto_height(4, cx)),
  87                cx,
  88            )
  89        });
  90
  91        cx.new_view(|cx: &mut ViewContext<Self>| {
  92            let view = cx.view().downgrade();
  93            let message_list =
  94                ListState::new(0, gpui::ListAlignment::Bottom, px(1000.), move |ix, cx| {
  95                    if let Some(view) = view.upgrade() {
  96                        view.update(cx, |view, cx| {
  97                            view.render_message(ix, cx).into_any_element()
  98                        })
  99                    } else {
 100                        div().into_any()
 101                    }
 102                });
 103
 104            message_list.set_scroll_handler(cx.listener(|this, event: &ListScrollEvent, cx| {
 105                if event.visible_range.start < MESSAGE_LOADING_THRESHOLD {
 106                    this.load_more_messages(cx);
 107                }
 108                this.is_scrolled_to_bottom = !event.is_scrolled;
 109            }));
 110
 111            let mut this = Self {
 112                fs,
 113                client,
 114                channel_store,
 115                languages,
 116                message_list,
 117                active_chat: Default::default(),
 118                pending_serialization: Task::ready(None),
 119                message_editor: input_editor,
 120                local_timezone: cx.local_timezone(),
 121                subscriptions: Vec::new(),
 122                is_scrolled_to_bottom: true,
 123                active: false,
 124                width: None,
 125                markdown_data: Default::default(),
 126                focus_handle: cx.focus_handle(),
 127                open_context_menu: None,
 128                highlighted_message: None,
 129            };
 130
 131            if let Some(channel_id) = ActiveCall::global(cx)
 132                .read(cx)
 133                .room()
 134                .and_then(|room| room.read(cx).channel_id())
 135            {
 136                this.select_channel(channel_id, None, cx)
 137                    .detach_and_log_err(cx);
 138            }
 139
 140            this.subscriptions.push(cx.subscribe(
 141                &ActiveCall::global(cx),
 142                move |this: &mut Self, call, event: &room::Event, cx| match event {
 143                    room::Event::RoomJoined { channel_id } => {
 144                        if let Some(channel_id) = channel_id {
 145                            this.select_channel(*channel_id, None, cx)
 146                                .detach_and_log_err(cx);
 147
 148                            if call
 149                                .read(cx)
 150                                .room()
 151                                .is_some_and(|room| room.read(cx).contains_guests())
 152                            {
 153                                cx.emit(PanelEvent::Activate)
 154                            }
 155                        }
 156                    }
 157                    room::Event::Left { channel_id } => {
 158                        if channel_id == &this.channel_id(cx) {
 159                            cx.emit(PanelEvent::Close)
 160                        }
 161                    }
 162                    _ => {}
 163                },
 164            ));
 165
 166            this
 167        })
 168    }
 169
 170    pub fn channel_id(&self, cx: &AppContext) -> Option<u64> {
 171        self.active_chat
 172            .as_ref()
 173            .map(|(chat, _)| chat.read(cx).channel_id)
 174    }
 175
 176    pub fn is_scrolled_to_bottom(&self) -> bool {
 177        self.is_scrolled_to_bottom
 178    }
 179
 180    pub fn active_chat(&self) -> Option<Model<ChannelChat>> {
 181        self.active_chat.as_ref().map(|(chat, _)| chat.clone())
 182    }
 183
 184    pub fn load(
 185        workspace: WeakView<Workspace>,
 186        cx: AsyncWindowContext,
 187    ) -> Task<Result<View<Self>>> {
 188        cx.spawn(|mut cx| async move {
 189            let serialized_panel = if let Some(panel) = cx
 190                .background_executor()
 191                .spawn(async move { KEY_VALUE_STORE.read_kvp(CHAT_PANEL_KEY) })
 192                .await
 193                .log_err()
 194                .flatten()
 195            {
 196                Some(serde_json::from_str::<SerializedChatPanel>(&panel)?)
 197            } else {
 198                None
 199            };
 200
 201            workspace.update(&mut cx, |workspace, cx| {
 202                let panel = Self::new(workspace, cx);
 203                if let Some(serialized_panel) = serialized_panel {
 204                    panel.update(cx, |panel, cx| {
 205                        panel.width = serialized_panel.width;
 206                        cx.notify();
 207                    });
 208                }
 209                panel
 210            })
 211        })
 212    }
 213
 214    fn serialize(&mut self, cx: &mut ViewContext<Self>) {
 215        let width = self.width;
 216        self.pending_serialization = cx.background_executor().spawn(
 217            async move {
 218                KEY_VALUE_STORE
 219                    .write_kvp(
 220                        CHAT_PANEL_KEY.into(),
 221                        serde_json::to_string(&SerializedChatPanel { width })?,
 222                    )
 223                    .await?;
 224                anyhow::Ok(())
 225            }
 226            .log_err(),
 227        );
 228    }
 229
 230    fn set_active_chat(&mut self, chat: Model<ChannelChat>, cx: &mut ViewContext<Self>) {
 231        if self.active_chat.as_ref().map(|e| &e.0) != Some(&chat) {
 232            let channel_id = chat.read(cx).channel_id;
 233            {
 234                self.markdown_data.clear();
 235                let chat = chat.read(cx);
 236                self.message_list.reset(chat.message_count());
 237
 238                let channel_name = chat.channel(cx).map(|channel| channel.name.clone());
 239                self.message_editor.update(cx, |editor, cx| {
 240                    editor.set_channel(channel_id, channel_name, cx);
 241                    editor.clear_reply_to_message_id();
 242                });
 243            };
 244            let subscription = cx.subscribe(&chat, Self::channel_did_change);
 245            self.active_chat = Some((chat, subscription));
 246            self.acknowledge_last_message(cx);
 247            cx.notify();
 248        }
 249    }
 250
 251    fn channel_did_change(
 252        &mut self,
 253        _: Model<ChannelChat>,
 254        event: &ChannelChatEvent,
 255        cx: &mut ViewContext<Self>,
 256    ) {
 257        match event {
 258            ChannelChatEvent::MessagesUpdated {
 259                old_range,
 260                new_count,
 261            } => {
 262                self.message_list.splice(old_range.clone(), *new_count);
 263                if self.active {
 264                    self.acknowledge_last_message(cx);
 265                }
 266            }
 267            ChannelChatEvent::NewMessage {
 268                channel_id,
 269                message_id,
 270            } => {
 271                if !self.active {
 272                    self.channel_store.update(cx, |store, cx| {
 273                        store.update_latest_message_id(*channel_id, *message_id, cx)
 274                    })
 275                }
 276            }
 277        }
 278        cx.notify();
 279    }
 280
 281    fn acknowledge_last_message(&mut self, cx: &mut ViewContext<Self>) {
 282        if self.active && self.is_scrolled_to_bottom {
 283            if let Some((chat, _)) = &self.active_chat {
 284                chat.update(cx, |chat, cx| {
 285                    chat.acknowledge_last_message(cx);
 286                });
 287            }
 288        }
 289    }
 290
 291    fn render_replied_to_message(
 292        &mut self,
 293        message_id: Option<ChannelMessageId>,
 294        reply_to_message: &ChannelMessage,
 295        cx: &mut ViewContext<Self>,
 296    ) -> impl IntoElement {
 297        let body_element_id: ElementId = match message_id {
 298            Some(ChannelMessageId::Saved(id)) => ("reply-to-saved-message", id).into(),
 299            Some(ChannelMessageId::Pending(id)) => ("reply-to-pending-message", id).into(), // This should never happen
 300            None => ("composing-reply").into(),
 301        };
 302
 303        let message_element_id: ElementId = match message_id {
 304            Some(ChannelMessageId::Saved(id)) => ("reply-to-saved-message-container", id).into(),
 305            Some(ChannelMessageId::Pending(id)) => {
 306                ("reply-to-pending-message-container", id).into()
 307            } // This should never happen
 308            None => ("composing-reply-container").into(),
 309        };
 310
 311        let current_channel_id = self.channel_id(cx);
 312        let reply_to_message_id = reply_to_message.id;
 313
 314        let reply_to_message_body = self
 315            .markdown_data
 316            .entry(reply_to_message.id)
 317            .or_insert_with(|| {
 318                Self::render_markdown_with_mentions(
 319                    &self.languages,
 320                    self.client.id(),
 321                    reply_to_message,
 322                )
 323            });
 324
 325        const REPLY_TO_PREFIX: &str = "Reply to @";
 326
 327        div().flex_grow().child(
 328            v_flex()
 329                .id(message_element_id)
 330                .text_ui_xs()
 331                .child(
 332                    h_flex()
 333                        .gap_x_1()
 334                        .items_center()
 335                        .justify_start()
 336                        .overflow_x_hidden()
 337                        .whitespace_nowrap()
 338                        .child(
 339                            StyledText::new(format!(
 340                                "{}{}",
 341                                REPLY_TO_PREFIX,
 342                                reply_to_message.sender.github_login.clone()
 343                            ))
 344                            .with_highlights(
 345                                &cx.text_style(),
 346                                vec![(
 347                                    (REPLY_TO_PREFIX.len() - 1)
 348                                        ..(reply_to_message.sender.github_login.len()
 349                                            + REPLY_TO_PREFIX.len()),
 350                                    HighlightStyle {
 351                                        font_weight: Some(FontWeight::BOLD),
 352                                        ..Default::default()
 353                                    },
 354                                )],
 355                            ),
 356                        ),
 357                )
 358                .child(
 359                    div()
 360                        .border_l_2()
 361                        .border_color(cx.theme().colors().border)
 362                        .px_1()
 363                        .py_0p5()
 364                        .mb_1()
 365                        .overflow_hidden()
 366                        .child(
 367                            div()
 368                                .max_h_12()
 369                                .child(reply_to_message_body.element(body_element_id, cx)),
 370                        ),
 371                )
 372                .cursor(CursorStyle::PointingHand)
 373                .tooltip(|cx| Tooltip::text("Go to message", cx))
 374                .on_click(cx.listener(move |chat_panel, _, cx| {
 375                    if let Some(channel_id) = current_channel_id {
 376                        chat_panel
 377                            .select_channel(channel_id, reply_to_message_id.into(), cx)
 378                            .detach_and_log_err(cx)
 379                    }
 380                })),
 381        )
 382    }
 383
 384    fn render_message(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> impl IntoElement {
 385        let active_chat = &self.active_chat.as_ref().unwrap().0;
 386        let (message, is_continuation_from_previous, is_admin) =
 387            active_chat.update(cx, |active_chat, cx| {
 388                let is_admin = self
 389                    .channel_store
 390                    .read(cx)
 391                    .is_channel_admin(active_chat.channel_id);
 392
 393                let last_message = active_chat.message(ix.saturating_sub(1));
 394                let this_message = active_chat.message(ix).clone();
 395
 396                let duration_since_last_message = this_message.timestamp - last_message.timestamp;
 397                let is_continuation_from_previous = last_message.sender.id
 398                    == this_message.sender.id
 399                    && last_message.id != this_message.id
 400                    && duration_since_last_message < Duration::from_secs(5 * 60);
 401
 402                if let ChannelMessageId::Saved(id) = this_message.id {
 403                    if this_message
 404                        .mentions
 405                        .iter()
 406                        .any(|(_, user_id)| Some(*user_id) == self.client.user_id())
 407                    {
 408                        active_chat.acknowledge_message(id);
 409                    }
 410                }
 411
 412                (this_message, is_continuation_from_previous, is_admin)
 413            });
 414
 415        let _is_pending = message.is_pending();
 416
 417        let belongs_to_user = Some(message.sender.id) == self.client.user_id();
 418        let can_delete_message = belongs_to_user || is_admin;
 419
 420        let element_id: ElementId = match message.id {
 421            ChannelMessageId::Saved(id) => ("saved-message", id).into(),
 422            ChannelMessageId::Pending(id) => ("pending-message", id).into(),
 423        };
 424        let this = cx.view().clone();
 425
 426        let mentioning_you = message
 427            .mentions
 428            .iter()
 429            .any(|m| Some(m.1) == self.client.user_id());
 430
 431        let message_id = match message.id {
 432            ChannelMessageId::Saved(id) => Some(id),
 433            ChannelMessageId::Pending(_) => None,
 434        };
 435
 436        let reply_to_message = message
 437            .reply_to_message_id
 438            .map(|id| active_chat.read(cx).find_loaded_message(id))
 439            .flatten()
 440            .cloned();
 441
 442        let replied_to_you =
 443            reply_to_message.as_ref().map(|m| m.sender.id) == self.client.user_id();
 444
 445        let is_highlighted_message = self
 446            .highlighted_message
 447            .as_ref()
 448            .is_some_and(|(id, _)| Some(id) == message_id.as_ref());
 449        let background = if is_highlighted_message {
 450            cx.theme().status().info_background
 451        } else if mentioning_you || replied_to_you {
 452            cx.theme().colors().background
 453        } else {
 454            cx.theme().colors().panel_background
 455        };
 456
 457        v_flex().w_full().relative().child(
 458            div()
 459                .bg(background)
 460                .rounded_md()
 461                .overflow_hidden()
 462                .px_1()
 463                .py_0p5()
 464                .when(!is_continuation_from_previous, |this| {
 465                    this.mt_2().child(
 466                        h_flex()
 467                            .text_ui_sm()
 468                            .child(div().absolute().child(
 469                                Avatar::new(message.sender.avatar_uri.clone()).size(rems(1.)),
 470                            ))
 471                            .child(
 472                                div()
 473                                    .pl(cx.rem_size() + px(6.0))
 474                                    .pr(px(8.0))
 475                                    .font_weight(FontWeight::BOLD)
 476                                    .child(Label::new(message.sender.github_login.clone())),
 477                            )
 478                            .child(
 479                                Label::new(format_timestamp(
 480                                    OffsetDateTime::now_utc(),
 481                                    message.timestamp,
 482                                    self.local_timezone,
 483                                ))
 484                                .size(LabelSize::Small)
 485                                .color(Color::Muted),
 486                            ),
 487                    )
 488                })
 489                .when(
 490                    message.reply_to_message_id.is_some() && reply_to_message.is_none(),
 491                    |this| {
 492                        const MESSAGE_DELETED: &str = "Message has been deleted";
 493
 494                        let body_text = StyledText::new(MESSAGE_DELETED).with_highlights(
 495                            &cx.text_style(),
 496                            vec![(
 497                                0..MESSAGE_DELETED.len(),
 498                                HighlightStyle {
 499                                    font_style: Some(FontStyle::Italic),
 500                                    ..Default::default()
 501                                },
 502                            )],
 503                        );
 504
 505                        this.child(
 506                            div()
 507                                .border_l_2()
 508                                .text_ui_xs()
 509                                .border_color(cx.theme().colors().border)
 510                                .px_1()
 511                                .py_0p5()
 512                                .child(body_text),
 513                        )
 514                    },
 515                )
 516                .when_some(reply_to_message, |el, reply_to_message| {
 517                    el.child(self.render_replied_to_message(
 518                        Some(message.id),
 519                        &reply_to_message,
 520                        cx,
 521                    ))
 522                })
 523                .when(mentioning_you || replied_to_you, |this| this.my_0p5())
 524                .map(|el| {
 525                    let text = self.markdown_data.entry(message.id).or_insert_with(|| {
 526                        Self::render_markdown_with_mentions(
 527                            &self.languages,
 528                            self.client.id(),
 529                            &message,
 530                        )
 531                    });
 532                    el.child(
 533                        v_flex()
 534                            .w_full()
 535                            .text_ui_sm()
 536                            .id(element_id)
 537                            .group("")
 538                            .child(text.element("body".into(), cx))
 539                            .child(
 540                                div()
 541                                    .absolute()
 542                                    .z_index(1)
 543                                    .right_0()
 544                                    .w_6()
 545                                    .bg(background)
 546                                    .when(!self.has_open_menu(message_id), |el| {
 547                                        el.visible_on_hover("")
 548                                    })
 549                                    .when_some(message_id, |el, message_id| {
 550                                        el.child(
 551                                            popover_menu(("menu", message_id))
 552                                                .trigger(IconButton::new(
 553                                                    ("trigger", message_id),
 554                                                    IconName::Ellipsis,
 555                                                ))
 556                                                .menu(move |cx| {
 557                                                    Some(Self::render_message_menu(
 558                                                        &this,
 559                                                        message_id,
 560                                                        can_delete_message,
 561                                                        cx,
 562                                                    ))
 563                                                }),
 564                                        )
 565                                    }),
 566                            ),
 567                    )
 568                }),
 569        )
 570    }
 571
 572    fn has_open_menu(&self, message_id: Option<u64>) -> bool {
 573        match self.open_context_menu.as_ref() {
 574            Some((id, _)) => Some(*id) == message_id,
 575            None => false,
 576        }
 577    }
 578
 579    fn render_message_menu(
 580        this: &View<Self>,
 581        message_id: u64,
 582        can_delete_message: bool,
 583        cx: &mut WindowContext,
 584    ) -> View<ContextMenu> {
 585        let menu = {
 586            ContextMenu::build(cx, move |menu, cx| {
 587                menu.entry(
 588                    "Reply to message",
 589                    None,
 590                    cx.handler_for(&this, move |this, cx| {
 591                        this.message_editor.update(cx, |editor, cx| {
 592                            editor.set_reply_to_message_id(message_id);
 593                            editor.focus_handle(cx).focus(cx);
 594                        })
 595                    }),
 596                )
 597                .when(can_delete_message, move |menu| {
 598                    menu.entry(
 599                        "Delete message",
 600                        None,
 601                        cx.handler_for(&this, move |this, cx| this.remove_message(message_id, cx)),
 602                    )
 603                })
 604            })
 605        };
 606        this.update(cx, |this, cx| {
 607            let subscription = cx.subscribe(&menu, |this: &mut Self, _, _: &DismissEvent, _| {
 608                this.open_context_menu = None;
 609            });
 610            this.open_context_menu = Some((message_id, subscription));
 611        });
 612        menu
 613    }
 614
 615    fn render_markdown_with_mentions(
 616        language_registry: &Arc<LanguageRegistry>,
 617        current_user_id: u64,
 618        message: &channel::ChannelMessage,
 619    ) -> RichText {
 620        let mentions = message
 621            .mentions
 622            .iter()
 623            .map(|(range, user_id)| rich_text::Mention {
 624                range: range.clone(),
 625                is_self_mention: *user_id == current_user_id,
 626            })
 627            .collect::<Vec<_>>();
 628
 629        rich_text::render_rich_text(message.body.clone(), &mentions, language_registry, None)
 630    }
 631
 632    fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
 633        if let Some((chat, _)) = self.active_chat.as_ref() {
 634            let message = self
 635                .message_editor
 636                .update(cx, |editor, cx| editor.take_message(cx));
 637
 638            if let Some(task) = chat
 639                .update(cx, |chat, cx| chat.send_message(message, cx))
 640                .log_err()
 641            {
 642                task.detach();
 643            }
 644        }
 645    }
 646
 647    fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
 648        if let Some((chat, _)) = self.active_chat.as_ref() {
 649            chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
 650        }
 651    }
 652
 653    fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
 654        if let Some((chat, _)) = self.active_chat.as_ref() {
 655            chat.update(cx, |channel, cx| {
 656                if let Some(task) = channel.load_more_messages(cx) {
 657                    task.detach();
 658                }
 659            })
 660        }
 661    }
 662
 663    pub fn select_channel(
 664        &mut self,
 665        selected_channel_id: u64,
 666        scroll_to_message_id: Option<u64>,
 667        cx: &mut ViewContext<ChatPanel>,
 668    ) -> Task<Result<()>> {
 669        let open_chat = self
 670            .active_chat
 671            .as_ref()
 672            .and_then(|(chat, _)| {
 673                (chat.read(cx).channel_id == selected_channel_id)
 674                    .then(|| Task::ready(anyhow::Ok(chat.clone())))
 675            })
 676            .unwrap_or_else(|| {
 677                self.channel_store.update(cx, |store, cx| {
 678                    store.open_channel_chat(selected_channel_id, cx)
 679                })
 680            });
 681
 682        cx.spawn(|this, mut cx| async move {
 683            let chat = open_chat.await?;
 684            this.update(&mut cx, |this, cx| {
 685                this.set_active_chat(chat.clone(), cx);
 686            })?;
 687
 688            if let Some(message_id) = scroll_to_message_id {
 689                if let Some(item_ix) =
 690                    ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
 691                        .await
 692                {
 693                    let task = cx.spawn({
 694                        let this = this.clone();
 695
 696                        |mut cx| async move {
 697                            cx.background_executor().timer(Duration::from_secs(2)).await;
 698                            this.update(&mut cx, |this, cx| {
 699                                this.highlighted_message.take();
 700                                cx.notify();
 701                            })
 702                            .ok();
 703                        }
 704                    });
 705
 706                    this.update(&mut cx, |this, cx| {
 707                        this.highlighted_message = Some((message_id, task));
 708                        if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
 709                            this.message_list.scroll_to(ListOffset {
 710                                item_ix,
 711                                offset_in_item: px(0.0),
 712                            });
 713                            cx.notify();
 714                        }
 715                    })?;
 716                }
 717            }
 718
 719            Ok(())
 720        })
 721    }
 722}
 723
 724impl Render for ChatPanel {
 725    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 726        let reply_to_message_id = self.message_editor.read(cx).reply_to_message_id();
 727
 728        v_flex()
 729            .track_focus(&self.focus_handle)
 730            .full()
 731            .on_action(cx.listener(Self::send))
 732            .child(
 733                h_flex().z_index(1).child(
 734                    TabBar::new("chat_header").child(
 735                        h_flex()
 736                            .w_full()
 737                            .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
 738                            .px_2()
 739                            .child(Label::new(
 740                                self.active_chat
 741                                    .as_ref()
 742                                    .and_then(|c| {
 743                                        Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
 744                                    })
 745                                    .unwrap_or("Chat".to_string()),
 746                            )),
 747                    ),
 748                ),
 749            )
 750            .child(div().flex_grow().px_2().map(|this| {
 751                if self.active_chat.is_some() {
 752                    this.child(list(self.message_list.clone()).full())
 753                } else {
 754                    this.child(
 755                        div()
 756                            .full()
 757                            .p_4()
 758                            .child(
 759                                Label::new("Select a channel to chat in.")
 760                                    .size(LabelSize::Small)
 761                                    .color(Color::Muted),
 762                            )
 763                            .child(
 764                                div().pt_1().w_full().items_center().child(
 765                                    Button::new("toggle-collab", "Open")
 766                                        .full_width()
 767                                        .key_binding(KeyBinding::for_action(
 768                                            &collab_panel::ToggleFocus,
 769                                            cx,
 770                                        ))
 771                                        .on_click(|_, cx| {
 772                                            cx.dispatch_action(
 773                                                collab_panel::ToggleFocus.boxed_clone(),
 774                                            )
 775                                        }),
 776                                ),
 777                            ),
 778                    )
 779                }
 780            }))
 781            .when_some(reply_to_message_id, |el, reply_to_message_id| {
 782                let reply_message = self
 783                    .active_chat()
 784                    .map(|active_chat| {
 785                        active_chat.read(cx).messages().iter().find_map(|m| {
 786                            if m.id == ChannelMessageId::Saved(reply_to_message_id) {
 787                                Some(m)
 788                            } else {
 789                                None
 790                            }
 791                        })
 792                    })
 793                    .flatten()
 794                    .cloned();
 795
 796                el.when_some(reply_message, |el, reply_message| {
 797                    el.child(
 798                        div()
 799                            .when(!self.is_scrolled_to_bottom, |el| {
 800                                el.border_t_1().border_color(cx.theme().colors().border)
 801                            })
 802                            .flex()
 803                            .w_full()
 804                            .items_start()
 805                            .overflow_hidden()
 806                            .py_1()
 807                            .px_2()
 808                            .bg(cx.theme().colors().background)
 809                            .child(self.render_replied_to_message(None, &reply_message, cx))
 810                            .child(
 811                                IconButton::new("close-reply-preview", IconName::Close)
 812                                    .shape(ui::IconButtonShape::Square)
 813                                    .on_click(cx.listener(move |this, _, cx| {
 814                                        this.message_editor.update(cx, |editor, _| {
 815                                            editor.clear_reply_to_message_id()
 816                                        });
 817                                    })),
 818                            ),
 819                    )
 820                })
 821            })
 822            .children(
 823                Some(
 824                    h_flex()
 825                        .when(
 826                            !self.is_scrolled_to_bottom && reply_to_message_id.is_none(),
 827                            |el| el.border_t_1().border_color(cx.theme().colors().border),
 828                        )
 829                        .p_2()
 830                        .map(|el| el.child(self.message_editor.clone())),
 831                )
 832                .filter(|_| self.active_chat.is_some()),
 833            )
 834            .into_any()
 835    }
 836}
 837
 838impl FocusableView for ChatPanel {
 839    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
 840        if self.active_chat.is_some() {
 841            self.message_editor.read(cx).focus_handle(cx)
 842        } else {
 843            self.focus_handle.clone()
 844        }
 845    }
 846}
 847
 848impl Panel for ChatPanel {
 849    fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
 850        ChatPanelSettings::get_global(cx).dock
 851    }
 852
 853    fn position_is_valid(&self, position: DockPosition) -> bool {
 854        matches!(position, DockPosition::Left | DockPosition::Right)
 855    }
 856
 857    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
 858        settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
 859            settings.dock = Some(position)
 860        });
 861    }
 862
 863    fn size(&self, cx: &gpui::WindowContext) -> Pixels {
 864        self.width
 865            .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
 866    }
 867
 868    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
 869        self.width = size;
 870        self.serialize(cx);
 871        cx.notify();
 872    }
 873
 874    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
 875        self.active = active;
 876        if active {
 877            self.acknowledge_last_message(cx);
 878        }
 879    }
 880
 881    fn persistent_name() -> &'static str {
 882        "ChatPanel"
 883    }
 884
 885    fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
 886        Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
 887    }
 888
 889    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
 890        Some("Chat Panel")
 891    }
 892
 893    fn toggle_action(&self) -> Box<dyn gpui::Action> {
 894        Box::new(ToggleFocus)
 895    }
 896
 897    fn starts_open(&self, cx: &WindowContext) -> bool {
 898        ActiveCall::global(cx)
 899            .read(cx)
 900            .room()
 901            .is_some_and(|room| room.read(cx).contains_guests())
 902    }
 903}
 904
 905impl EventEmitter<PanelEvent> for ChatPanel {}
 906
 907fn format_timestamp(
 908    reference: OffsetDateTime,
 909    timestamp: OffsetDateTime,
 910    timezone: UtcOffset,
 911) -> String {
 912    let timestamp_local = timestamp.to_offset(timezone);
 913    let timestamp_local_hour = timestamp_local.hour();
 914
 915    let hour_12 = match timestamp_local_hour {
 916        0 => 12,                              // Midnight
 917        13..=23 => timestamp_local_hour - 12, // PM hours
 918        _ => timestamp_local_hour,            // AM hours
 919    };
 920    let meridiem = if timestamp_local_hour >= 12 {
 921        "pm"
 922    } else {
 923        "am"
 924    };
 925    let timestamp_local_minute = timestamp_local.minute();
 926    let formatted_time = format!("{:02}:{:02} {}", hour_12, timestamp_local_minute, meridiem);
 927
 928    let reference_local = reference.to_offset(timezone);
 929    let reference_local_date = reference_local.date();
 930    let timestamp_local_date = timestamp_local.date();
 931
 932    if timestamp_local_date == reference_local_date {
 933        return formatted_time;
 934    }
 935
 936    if reference_local_date.previous_day() == Some(timestamp_local_date) {
 937        return format!("yesterday at {}", formatted_time);
 938    }
 939
 940    format!(
 941        "{:02}/{:02}/{}",
 942        timestamp_local_date.month() as u32,
 943        timestamp_local_date.day(),
 944        timestamp_local_date.year()
 945    )
 946}
 947
 948#[cfg(test)]
 949mod tests {
 950    use super::*;
 951    use gpui::HighlightStyle;
 952    use pretty_assertions::assert_eq;
 953    use rich_text::Highlight;
 954    use time::{Date, OffsetDateTime, Time, UtcOffset};
 955    use util::test::marked_text_ranges;
 956
 957    #[gpui::test]
 958    fn test_render_markdown_with_mentions() {
 959        let language_registry = Arc::new(LanguageRegistry::test());
 960        let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
 961        let message = channel::ChannelMessage {
 962            id: ChannelMessageId::Saved(0),
 963            body,
 964            timestamp: OffsetDateTime::now_utc(),
 965            sender: Arc::new(client::User {
 966                github_login: "fgh".into(),
 967                avatar_uri: "avatar_fgh".into(),
 968                id: 103,
 969            }),
 970            nonce: 5,
 971            mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
 972            reply_to_message_id: None,
 973        };
 974
 975        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
 976
 977        // Note that the "'" was replaced with ’ due to smart punctuation.
 978        let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
 979        assert_eq!(message.text, body);
 980        assert_eq!(
 981            message.highlights,
 982            vec![
 983                (
 984                    ranges[0].clone(),
 985                    HighlightStyle {
 986                        font_style: Some(gpui::FontStyle::Italic),
 987                        ..Default::default()
 988                    }
 989                    .into()
 990                ),
 991                (ranges[1].clone(), Highlight::Mention),
 992                (
 993                    ranges[2].clone(),
 994                    HighlightStyle {
 995                        font_weight: Some(gpui::FontWeight::BOLD),
 996                        ..Default::default()
 997                    }
 998                    .into()
 999                ),
1000                (ranges[3].clone(), Highlight::SelfMention)
1001            ]
1002        );
1003    }
1004
1005    #[test]
1006    fn test_format_today() {
1007        let reference = create_offset_datetime(1990, 4, 12, 16, 45, 0);
1008        let timestamp = create_offset_datetime(1990, 4, 12, 15, 30, 0);
1009
1010        assert_eq!(
1011            format_timestamp(reference, timestamp, test_timezone()),
1012            "03:30 pm"
1013        );
1014    }
1015
1016    #[test]
1017    fn test_format_yesterday() {
1018        let reference = create_offset_datetime(1990, 4, 12, 10, 30, 0);
1019        let timestamp = create_offset_datetime(1990, 4, 11, 9, 0, 0);
1020
1021        assert_eq!(
1022            format_timestamp(reference, timestamp, test_timezone()),
1023            "yesterday at 09:00 am"
1024        );
1025    }
1026
1027    #[test]
1028    fn test_format_yesterday_less_than_24_hours_ago() {
1029        let reference = create_offset_datetime(1990, 4, 12, 19, 59, 0);
1030        let timestamp = create_offset_datetime(1990, 4, 11, 20, 0, 0);
1031
1032        assert_eq!(
1033            format_timestamp(reference, timestamp, test_timezone()),
1034            "yesterday at 08:00 pm"
1035        );
1036    }
1037
1038    #[test]
1039    fn test_format_yesterday_more_than_24_hours_ago() {
1040        let reference = create_offset_datetime(1990, 4, 12, 19, 59, 0);
1041        let timestamp = create_offset_datetime(1990, 4, 11, 18, 0, 0);
1042
1043        assert_eq!(
1044            format_timestamp(reference, timestamp, test_timezone()),
1045            "yesterday at 06:00 pm"
1046        );
1047    }
1048
1049    #[test]
1050    fn test_format_yesterday_over_midnight() {
1051        let reference = create_offset_datetime(1990, 4, 12, 0, 5, 0);
1052        let timestamp = create_offset_datetime(1990, 4, 11, 23, 55, 0);
1053
1054        assert_eq!(
1055            format_timestamp(reference, timestamp, test_timezone()),
1056            "yesterday at 11:55 pm"
1057        );
1058    }
1059
1060    #[test]
1061    fn test_format_yesterday_over_month() {
1062        let reference = create_offset_datetime(1990, 4, 2, 9, 0, 0);
1063        let timestamp = create_offset_datetime(1990, 4, 1, 20, 0, 0);
1064
1065        assert_eq!(
1066            format_timestamp(reference, timestamp, test_timezone()),
1067            "yesterday at 08:00 pm"
1068        );
1069    }
1070
1071    #[test]
1072    fn test_format_before_yesterday() {
1073        let reference = create_offset_datetime(1990, 4, 12, 10, 30, 0);
1074        let timestamp = create_offset_datetime(1990, 4, 10, 20, 20, 0);
1075
1076        assert_eq!(
1077            format_timestamp(reference, timestamp, test_timezone()),
1078            "04/10/1990"
1079        );
1080    }
1081
1082    fn test_timezone() -> UtcOffset {
1083        UtcOffset::from_hms(0, 0, 0).expect("Valid timezone offset")
1084    }
1085
1086    fn create_offset_datetime(
1087        year: i32,
1088        month: u8,
1089        day: u8,
1090        hour: u8,
1091        minute: u8,
1092        second: u8,
1093    ) -> OffsetDateTime {
1094        let date =
1095            Date::from_calendar_date(year, time::Month::try_from(month).unwrap(), day).unwrap();
1096        let time = Time::from_hms(hour, minute, second).unwrap();
1097        date.with_time(time).assume_utc() // Assume UTC for simplicity
1098    }
1099}