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