chat_panel.rs

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