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, CloseReplyPreview]);
  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                                    None,
 484                                ))
 485                                .size(LabelSize::Small)
 486                                .color(Color::Muted),
 487                            ),
 488                    )
 489                })
 490                .when(
 491                    message.reply_to_message_id.is_some() && reply_to_message.is_none(),
 492                    |this| {
 493                        const MESSAGE_DELETED: &str = "Message has been deleted";
 494
 495                        let body_text = StyledText::new(MESSAGE_DELETED).with_highlights(
 496                            &cx.text_style(),
 497                            vec![(
 498                                0..MESSAGE_DELETED.len(),
 499                                HighlightStyle {
 500                                    font_style: Some(FontStyle::Italic),
 501                                    ..Default::default()
 502                                },
 503                            )],
 504                        );
 505
 506                        this.child(
 507                            div()
 508                                .border_l_2()
 509                                .text_ui_xs()
 510                                .border_color(cx.theme().colors().border)
 511                                .px_1()
 512                                .py_0p5()
 513                                .child(body_text),
 514                        )
 515                    },
 516                )
 517                .when_some(reply_to_message, |el, reply_to_message| {
 518                    el.child(self.render_replied_to_message(
 519                        Some(message.id),
 520                        &reply_to_message,
 521                        cx,
 522                    ))
 523                })
 524                .when(mentioning_you || replied_to_you, |this| this.my_0p5())
 525                .map(|el| {
 526                    let text = self.markdown_data.entry(message.id).or_insert_with(|| {
 527                        Self::render_markdown_with_mentions(
 528                            &self.languages,
 529                            self.client.id(),
 530                            &message,
 531                        )
 532                    });
 533                    el.child(
 534                        v_flex()
 535                            .w_full()
 536                            .text_ui_sm()
 537                            .id(element_id)
 538                            .group("")
 539                            .child(text.element("body".into(), cx))
 540                            .child(
 541                                div()
 542                                    .absolute()
 543                                    .z_index(1)
 544                                    .right_0()
 545                                    .w_6()
 546                                    .bg(background)
 547                                    .when(!self.has_open_menu(message_id), |el| {
 548                                        el.visible_on_hover("")
 549                                    })
 550                                    .when_some(message_id, |el, message_id| {
 551                                        el.child(
 552                                            popover_menu(("menu", message_id))
 553                                                .trigger(IconButton::new(
 554                                                    ("trigger", message_id),
 555                                                    IconName::Ellipsis,
 556                                                ))
 557                                                .menu(move |cx| {
 558                                                    Some(Self::render_message_menu(
 559                                                        &this,
 560                                                        message_id,
 561                                                        can_delete_message,
 562                                                        cx,
 563                                                    ))
 564                                                }),
 565                                        )
 566                                    }),
 567                            ),
 568                    )
 569                }),
 570        )
 571    }
 572
 573    fn has_open_menu(&self, message_id: Option<u64>) -> bool {
 574        match self.open_context_menu.as_ref() {
 575            Some((id, _)) => Some(*id) == message_id,
 576            None => false,
 577        }
 578    }
 579
 580    fn render_message_menu(
 581        this: &View<Self>,
 582        message_id: u64,
 583        can_delete_message: bool,
 584        cx: &mut WindowContext,
 585    ) -> View<ContextMenu> {
 586        let menu = {
 587            ContextMenu::build(cx, move |menu, cx| {
 588                menu.entry(
 589                    "Reply to message",
 590                    None,
 591                    cx.handler_for(&this, move |this, cx| {
 592                        this.message_editor.update(cx, |editor, cx| {
 593                            editor.set_reply_to_message_id(message_id);
 594                            editor.focus_handle(cx).focus(cx);
 595                        })
 596                    }),
 597                )
 598                .when(can_delete_message, move |menu| {
 599                    menu.entry(
 600                        "Delete message",
 601                        None,
 602                        cx.handler_for(&this, move |this, cx| this.remove_message(message_id, cx)),
 603                    )
 604                })
 605            })
 606        };
 607        this.update(cx, |this, cx| {
 608            let subscription = cx.subscribe(&menu, |this: &mut Self, _, _: &DismissEvent, _| {
 609                this.open_context_menu = None;
 610            });
 611            this.open_context_menu = Some((message_id, subscription));
 612        });
 613        menu
 614    }
 615
 616    fn render_markdown_with_mentions(
 617        language_registry: &Arc<LanguageRegistry>,
 618        current_user_id: u64,
 619        message: &channel::ChannelMessage,
 620    ) -> RichText {
 621        let mentions = message
 622            .mentions
 623            .iter()
 624            .map(|(range, user_id)| rich_text::Mention {
 625                range: range.clone(),
 626                is_self_mention: *user_id == current_user_id,
 627            })
 628            .collect::<Vec<_>>();
 629
 630        rich_text::render_rich_text(message.body.clone(), &mentions, language_registry, None)
 631    }
 632
 633    fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
 634        if let Some((chat, _)) = self.active_chat.as_ref() {
 635            let message = self
 636                .message_editor
 637                .update(cx, |editor, cx| editor.take_message(cx));
 638
 639            if let Some(task) = chat
 640                .update(cx, |chat, cx| chat.send_message(message, cx))
 641                .log_err()
 642            {
 643                task.detach();
 644            }
 645        }
 646    }
 647
 648    fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
 649        if let Some((chat, _)) = self.active_chat.as_ref() {
 650            chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
 651        }
 652    }
 653
 654    fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
 655        if let Some((chat, _)) = self.active_chat.as_ref() {
 656            chat.update(cx, |channel, cx| {
 657                if let Some(task) = channel.load_more_messages(cx) {
 658                    task.detach();
 659                }
 660            })
 661        }
 662    }
 663
 664    pub fn select_channel(
 665        &mut self,
 666        selected_channel_id: u64,
 667        scroll_to_message_id: Option<u64>,
 668        cx: &mut ViewContext<ChatPanel>,
 669    ) -> Task<Result<()>> {
 670        let open_chat = self
 671            .active_chat
 672            .as_ref()
 673            .and_then(|(chat, _)| {
 674                (chat.read(cx).channel_id == selected_channel_id)
 675                    .then(|| Task::ready(anyhow::Ok(chat.clone())))
 676            })
 677            .unwrap_or_else(|| {
 678                self.channel_store.update(cx, |store, cx| {
 679                    store.open_channel_chat(selected_channel_id, cx)
 680                })
 681            });
 682
 683        cx.spawn(|this, mut cx| async move {
 684            let chat = open_chat.await?;
 685            this.update(&mut cx, |this, cx| {
 686                this.set_active_chat(chat.clone(), cx);
 687            })?;
 688
 689            if let Some(message_id) = scroll_to_message_id {
 690                if let Some(item_ix) =
 691                    ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
 692                        .await
 693                {
 694                    let task = cx.spawn({
 695                        let this = this.clone();
 696
 697                        |mut cx| async move {
 698                            cx.background_executor().timer(Duration::from_secs(2)).await;
 699                            this.update(&mut cx, |this, cx| {
 700                                this.highlighted_message.take();
 701                                cx.notify();
 702                            })
 703                            .ok();
 704                        }
 705                    });
 706
 707                    this.update(&mut cx, |this, cx| {
 708                        this.highlighted_message = Some((message_id, task));
 709                        if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
 710                            this.message_list.scroll_to(ListOffset {
 711                                item_ix,
 712                                offset_in_item: px(0.0),
 713                            });
 714                            cx.notify();
 715                        }
 716                    })?;
 717                }
 718            }
 719
 720            Ok(())
 721        })
 722    }
 723
 724    fn close_reply_preview(&mut self, _: &CloseReplyPreview, cx: &mut ViewContext<Self>) {
 725        self.message_editor
 726            .update(cx, |editor, _| editor.clear_reply_to_message_id());
 727    }
 728}
 729
 730impl Render for ChatPanel {
 731    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 732        let reply_to_message_id = self.message_editor.read(cx).reply_to_message_id();
 733
 734        v_flex()
 735            .key_context("ChatPanel")
 736            .track_focus(&self.focus_handle)
 737            .size_full()
 738            .on_action(cx.listener(Self::send))
 739            .child(
 740                h_flex().z_index(1).child(
 741                    TabBar::new("chat_header").child(
 742                        h_flex()
 743                            .w_full()
 744                            .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
 745                            .px_2()
 746                            .child(Label::new(
 747                                self.active_chat
 748                                    .as_ref()
 749                                    .and_then(|c| {
 750                                        Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
 751                                    })
 752                                    .unwrap_or("Chat".to_string()),
 753                            )),
 754                    ),
 755                ),
 756            )
 757            .child(div().flex_grow().px_2().map(|this| {
 758                if self.active_chat.is_some() {
 759                    this.child(list(self.message_list.clone()).size_full())
 760                } else {
 761                    this.child(
 762                        div()
 763                            .size_full()
 764                            .p_4()
 765                            .child(
 766                                Label::new("Select a channel to chat in.")
 767                                    .size(LabelSize::Small)
 768                                    .color(Color::Muted),
 769                            )
 770                            .child(
 771                                div().pt_1().w_full().items_center().child(
 772                                    Button::new("toggle-collab", "Open")
 773                                        .full_width()
 774                                        .key_binding(KeyBinding::for_action(
 775                                            &collab_panel::ToggleFocus,
 776                                            cx,
 777                                        ))
 778                                        .on_click(|_, cx| {
 779                                            cx.dispatch_action(
 780                                                collab_panel::ToggleFocus.boxed_clone(),
 781                                            )
 782                                        }),
 783                                ),
 784                            ),
 785                    )
 786                }
 787            }))
 788            .when_some(reply_to_message_id, |el, reply_to_message_id| {
 789                let reply_message = self
 790                    .active_chat()
 791                    .map(|active_chat| {
 792                        active_chat.read(cx).messages().iter().find_map(|m| {
 793                            if m.id == ChannelMessageId::Saved(reply_to_message_id) {
 794                                Some(m)
 795                            } else {
 796                                None
 797                            }
 798                        })
 799                    })
 800                    .flatten()
 801                    .cloned();
 802
 803                el.when_some(reply_message, |el, reply_message| {
 804                    el.child(
 805                        div()
 806                            .when(!self.is_scrolled_to_bottom, |el| {
 807                                el.border_t_1().border_color(cx.theme().colors().border)
 808                            })
 809                            .flex()
 810                            .w_full()
 811                            .items_start()
 812                            .overflow_hidden()
 813                            .py_1()
 814                            .px_2()
 815                            .bg(cx.theme().colors().background)
 816                            .child(self.render_replied_to_message(None, &reply_message, cx))
 817                            .child(
 818                                IconButton::new("close-reply-preview", IconName::Close)
 819                                    .shape(ui::IconButtonShape::Square)
 820                                    .tooltip(|cx| {
 821                                        Tooltip::for_action(
 822                                            "Close reply preview",
 823                                            &CloseReplyPreview,
 824                                            cx,
 825                                        )
 826                                    })
 827                                    .on_click(cx.listener(move |_, _, cx| {
 828                                        cx.dispatch_action(CloseReplyPreview.boxed_clone())
 829                                    })),
 830                            ),
 831                    )
 832                })
 833            })
 834            .children(
 835                Some(
 836                    h_flex()
 837                        .key_context("MessageEditor")
 838                        .on_action(cx.listener(ChatPanel::close_reply_preview))
 839                        .when(
 840                            !self.is_scrolled_to_bottom && reply_to_message_id.is_none(),
 841                            |el| el.border_t_1().border_color(cx.theme().colors().border),
 842                        )
 843                        .p_2()
 844                        .map(|el| el.child(self.message_editor.clone())),
 845                )
 846                .filter(|_| self.active_chat.is_some()),
 847            )
 848            .into_any()
 849    }
 850}
 851
 852impl FocusableView for ChatPanel {
 853    fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
 854        if self.active_chat.is_some() {
 855            self.message_editor.read(cx).focus_handle(cx)
 856        } else {
 857            self.focus_handle.clone()
 858        }
 859    }
 860}
 861
 862impl Panel for ChatPanel {
 863    fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
 864        ChatPanelSettings::get_global(cx).dock
 865    }
 866
 867    fn position_is_valid(&self, position: DockPosition) -> bool {
 868        matches!(position, DockPosition::Left | DockPosition::Right)
 869    }
 870
 871    fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
 872        settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
 873            settings.dock = Some(position)
 874        });
 875    }
 876
 877    fn size(&self, cx: &gpui::WindowContext) -> Pixels {
 878        self.width
 879            .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
 880    }
 881
 882    fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
 883        self.width = size;
 884        self.serialize(cx);
 885        cx.notify();
 886    }
 887
 888    fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
 889        self.active = active;
 890        if active {
 891            self.acknowledge_last_message(cx);
 892        }
 893    }
 894
 895    fn persistent_name() -> &'static str {
 896        "ChatPanel"
 897    }
 898
 899    fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
 900        Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
 901    }
 902
 903    fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
 904        Some("Chat Panel")
 905    }
 906
 907    fn toggle_action(&self) -> Box<dyn gpui::Action> {
 908        Box::new(ToggleFocus)
 909    }
 910
 911    fn starts_open(&self, cx: &WindowContext) -> bool {
 912        ActiveCall::global(cx)
 913            .read(cx)
 914            .room()
 915            .is_some_and(|room| room.read(cx).contains_guests())
 916    }
 917}
 918
 919impl EventEmitter<PanelEvent> for ChatPanel {}
 920
 921fn is_12_hour_clock(locale: String) -> bool {
 922    [
 923        "es-MX", "es-CO", "es-SV", "es-NI",
 924        "es-HN", // Mexico, Colombia, El Salvador, Nicaragua, Honduras
 925        "en-US", "en-CA", "en-AU", "en-NZ", // U.S, Canada, Australia, New Zealand
 926        "ar-SA", "ar-EG", "ar-JO", // Saudi Arabia, Egypt, Jordan
 927        "en-IN", "hi-IN", // India, Hindu
 928        "en-PK", "ur-PK", // Pakistan, Urdu
 929        "en-PH", "fil-PH", // Philippines, Filipino
 930        "bn-BD", "ccp-BD", // Bangladesh, Chakma
 931        "en-IE", "ga-IE", // Ireland, Irish
 932        "en-MY", "ms-MY", // Malaysia, Malay
 933    ]
 934    .contains(&locale.as_str())
 935}
 936
 937fn format_timestamp(
 938    reference: OffsetDateTime,
 939    timestamp: OffsetDateTime,
 940    timezone: UtcOffset,
 941    locale: Option<String>,
 942) -> String {
 943    let locale = match locale {
 944        Some(locale) => locale,
 945        None => sys_locale::get_locale().unwrap_or_else(|| String::from("en-US")),
 946    };
 947    let timestamp_local = timestamp.to_offset(timezone);
 948    let timestamp_local_hour = timestamp_local.hour();
 949    let timestamp_local_minute = timestamp_local.minute();
 950
 951    let (hour, meridiem) = if is_12_hour_clock(locale) {
 952        let meridiem = if timestamp_local_hour >= 12 {
 953            "pm"
 954        } else {
 955            "am"
 956        };
 957
 958        let hour_12 = match timestamp_local_hour {
 959            0 => 12,                              // Midnight
 960            13..=23 => timestamp_local_hour - 12, // PM hours
 961            _ => timestamp_local_hour,            // AM hours
 962        };
 963
 964        (hour_12, Some(meridiem))
 965    } else {
 966        (timestamp_local_hour, None)
 967    };
 968
 969    let formatted_time = match meridiem {
 970        Some(meridiem) => format!("{:02}:{:02} {}", hour, timestamp_local_minute, meridiem),
 971        None => format!("{:02}:{:02}", hour, timestamp_local_minute),
 972    };
 973
 974    let reference_local = reference.to_offset(timezone);
 975    let reference_local_date = reference_local.date();
 976    let timestamp_local_date = timestamp_local.date();
 977
 978    if timestamp_local_date == reference_local_date {
 979        return formatted_time;
 980    }
 981
 982    if reference_local_date.previous_day() == Some(timestamp_local_date) {
 983        return format!("yesterday at {}", formatted_time);
 984    }
 985
 986    match meridiem {
 987        Some(_) => format!(
 988            "{:02}/{:02}/{}",
 989            timestamp_local_date.month() as u32,
 990            timestamp_local_date.day(),
 991            timestamp_local_date.year()
 992        ),
 993        None => format!(
 994            "{:02}/{:02}/{}",
 995            timestamp_local_date.day(),
 996            timestamp_local_date.month() as u32,
 997            timestamp_local_date.year()
 998        ),
 999    }
1000}
1001
1002#[cfg(test)]
1003mod tests {
1004    use super::*;
1005    use gpui::HighlightStyle;
1006    use pretty_assertions::assert_eq;
1007    use rich_text::Highlight;
1008    use time::{Date, OffsetDateTime, Time, UtcOffset};
1009    use util::test::marked_text_ranges;
1010
1011    #[gpui::test]
1012    fn test_render_markdown_with_mentions() {
1013        let language_registry = Arc::new(LanguageRegistry::test());
1014        let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
1015        let message = channel::ChannelMessage {
1016            id: ChannelMessageId::Saved(0),
1017            body,
1018            timestamp: OffsetDateTime::now_utc(),
1019            sender: Arc::new(client::User {
1020                github_login: "fgh".into(),
1021                avatar_uri: "avatar_fgh".into(),
1022                id: 103,
1023            }),
1024            nonce: 5,
1025            mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
1026            reply_to_message_id: None,
1027        };
1028
1029        let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
1030
1031        // Note that the "'" was replaced with ’ due to smart punctuation.
1032        let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
1033        assert_eq!(message.text, body);
1034        assert_eq!(
1035            message.highlights,
1036            vec![
1037                (
1038                    ranges[0].clone(),
1039                    HighlightStyle {
1040                        font_style: Some(gpui::FontStyle::Italic),
1041                        ..Default::default()
1042                    }
1043                    .into()
1044                ),
1045                (ranges[1].clone(), Highlight::Mention),
1046                (
1047                    ranges[2].clone(),
1048                    HighlightStyle {
1049                        font_weight: Some(gpui::FontWeight::BOLD),
1050                        ..Default::default()
1051                    }
1052                    .into()
1053                ),
1054                (ranges[3].clone(), Highlight::SelfMention)
1055            ]
1056        );
1057    }
1058
1059    #[test]
1060    fn test_format_locale() {
1061        let reference = create_offset_datetime(1990, 4, 12, 16, 45, 0);
1062        let timestamp = create_offset_datetime(1990, 4, 12, 15, 30, 0);
1063
1064        assert_eq!(
1065            format_timestamp(
1066                reference,
1067                timestamp,
1068                test_timezone(),
1069                Some(String::from("en-GB"))
1070            ),
1071            "15:30"
1072        );
1073    }
1074
1075    #[test]
1076    fn test_format_today() {
1077        let reference = create_offset_datetime(1990, 4, 12, 16, 45, 0);
1078        let timestamp = create_offset_datetime(1990, 4, 12, 15, 30, 0);
1079
1080        assert_eq!(
1081            format_timestamp(
1082                reference,
1083                timestamp,
1084                test_timezone(),
1085                Some(String::from("en-US"))
1086            ),
1087            "03:30 pm"
1088        );
1089    }
1090
1091    #[test]
1092    fn test_format_yesterday() {
1093        let reference = create_offset_datetime(1990, 4, 12, 10, 30, 0);
1094        let timestamp = create_offset_datetime(1990, 4, 11, 9, 0, 0);
1095
1096        assert_eq!(
1097            format_timestamp(
1098                reference,
1099                timestamp,
1100                test_timezone(),
1101                Some(String::from("en-US"))
1102            ),
1103            "yesterday at 09:00 am"
1104        );
1105    }
1106
1107    #[test]
1108    fn test_format_yesterday_less_than_24_hours_ago() {
1109        let reference = create_offset_datetime(1990, 4, 12, 19, 59, 0);
1110        let timestamp = create_offset_datetime(1990, 4, 11, 20, 0, 0);
1111
1112        assert_eq!(
1113            format_timestamp(
1114                reference,
1115                timestamp,
1116                test_timezone(),
1117                Some(String::from("en-US"))
1118            ),
1119            "yesterday at 08:00 pm"
1120        );
1121    }
1122
1123    #[test]
1124    fn test_format_yesterday_more_than_24_hours_ago() {
1125        let reference = create_offset_datetime(1990, 4, 12, 19, 59, 0);
1126        let timestamp = create_offset_datetime(1990, 4, 11, 18, 0, 0);
1127
1128        assert_eq!(
1129            format_timestamp(
1130                reference,
1131                timestamp,
1132                test_timezone(),
1133                Some(String::from("en-US"))
1134            ),
1135            "yesterday at 06:00 pm"
1136        );
1137    }
1138
1139    #[test]
1140    fn test_format_yesterday_over_midnight() {
1141        let reference = create_offset_datetime(1990, 4, 12, 0, 5, 0);
1142        let timestamp = create_offset_datetime(1990, 4, 11, 23, 55, 0);
1143
1144        assert_eq!(
1145            format_timestamp(
1146                reference,
1147                timestamp,
1148                test_timezone(),
1149                Some(String::from("en-US"))
1150            ),
1151            "yesterday at 11:55 pm"
1152        );
1153    }
1154
1155    #[test]
1156    fn test_format_yesterday_over_month() {
1157        let reference = create_offset_datetime(1990, 4, 2, 9, 0, 0);
1158        let timestamp = create_offset_datetime(1990, 4, 1, 20, 0, 0);
1159
1160        assert_eq!(
1161            format_timestamp(
1162                reference,
1163                timestamp,
1164                test_timezone(),
1165                Some(String::from("en-US"))
1166            ),
1167            "yesterday at 08:00 pm"
1168        );
1169    }
1170
1171    #[test]
1172    fn test_format_before_yesterday() {
1173        let reference = create_offset_datetime(1990, 4, 12, 10, 30, 0);
1174        let timestamp = create_offset_datetime(1990, 4, 10, 20, 20, 0);
1175
1176        assert_eq!(
1177            format_timestamp(
1178                reference,
1179                timestamp,
1180                test_timezone(),
1181                Some(String::from("en-US"))
1182            ),
1183            "04/10/1990"
1184        );
1185    }
1186
1187    fn test_timezone() -> UtcOffset {
1188        UtcOffset::from_hms(0, 0, 0).expect("Valid timezone offset")
1189    }
1190
1191    fn create_offset_datetime(
1192        year: i32,
1193        month: u8,
1194        day: u8,
1195        hour: u8,
1196        minute: u8,
1197        second: u8,
1198    ) -> OffsetDateTime {
1199        let date =
1200            Date::from_calendar_date(year, time::Month::try_from(month).unwrap(), day).unwrap();
1201        let time = Time::from_hms(hour, minute, second).unwrap();
1202        date.with_time(time).assume_utc() // Assume UTC for simplicity
1203    }
1204}