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(
347 div().absolute().child(
348 Avatar::new(message.sender.avatar_uri.clone()).size(rems(1.)),
349 ),
350 )
351 .child(
352 div()
353 .pl(cx.rem_size() + px(6.0))
354 .pr(px(8.0))
355 .font_weight(FontWeight::BOLD)
356 .child(Label::new(message.sender.github_login.clone())),
357 )
358 .child(
359 Label::new(format_timestamp(
360 OffsetDateTime::now_utc(),
361 message.timestamp,
362 self.local_timezone,
363 ))
364 .size(LabelSize::Small)
365 .color(Color::Muted),
366 ),
367 )
368 })
369 .when(is_continuation_from_previous, |this| this.pt_1())
370 .child(
371 v_flex()
372 .w_full()
373 .text_ui_sm()
374 .id(element_id)
375 .group("")
376 .child(text.element("body".into(), cx))
377 .child(
378 div()
379 .absolute()
380 .z_index(1)
381 .right_0()
382 .w_6()
383 .bg(cx.theme().colors().panel_background)
384 .when(!self.has_open_menu(message_id_to_remove), |el| {
385 el.visible_on_hover("")
386 })
387 .children(message_id_to_remove.map(|message_id| {
388 popover_menu(("menu", message_id))
389 .trigger(IconButton::new(
390 ("trigger", message_id),
391 IconName::Ellipsis,
392 ))
393 .menu(move |cx| {
394 Some(Self::render_message_menu(&this, message_id, cx))
395 })
396 })),
397 ),
398 )
399 }
400
401 fn has_open_menu(&self, message_id: Option<u64>) -> bool {
402 match self.open_context_menu.as_ref() {
403 Some((id, _)) => Some(*id) == message_id,
404 None => false,
405 }
406 }
407
408 fn render_message_menu(
409 this: &View<Self>,
410 message_id: u64,
411 cx: &mut WindowContext,
412 ) -> View<ContextMenu> {
413 let menu = {
414 let this = this.clone();
415 ContextMenu::build(cx, move |menu, _| {
416 menu.entry("Delete message", None, move |cx| {
417 this.update(cx, |this, cx| this.remove_message(message_id, cx))
418 })
419 })
420 };
421 this.update(cx, |this, cx| {
422 let subscription = cx.subscribe(&menu, |this: &mut Self, _, _: &DismissEvent, _| {
423 this.open_context_menu = None;
424 });
425 this.open_context_menu = Some((message_id, subscription));
426 });
427 menu
428 }
429
430 fn render_markdown_with_mentions(
431 language_registry: &Arc<LanguageRegistry>,
432 current_user_id: u64,
433 message: &channel::ChannelMessage,
434 ) -> RichText {
435 let mentions = message
436 .mentions
437 .iter()
438 .map(|(range, user_id)| rich_text::Mention {
439 range: range.clone(),
440 is_self_mention: *user_id == current_user_id,
441 })
442 .collect::<Vec<_>>();
443
444 rich_text::render_markdown(message.body.clone(), &mentions, language_registry, None)
445 }
446
447 fn send(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
448 if let Some((chat, _)) = self.active_chat.as_ref() {
449 let message = self
450 .message_editor
451 .update(cx, |editor, cx| editor.take_message(cx));
452
453 if let Some(task) = chat
454 .update(cx, |chat, cx| chat.send_message(message, cx))
455 .log_err()
456 {
457 task.detach();
458 }
459 }
460 }
461
462 fn remove_message(&mut self, id: u64, cx: &mut ViewContext<Self>) {
463 if let Some((chat, _)) = self.active_chat.as_ref() {
464 chat.update(cx, |chat, cx| chat.remove_message(id, cx).detach())
465 }
466 }
467
468 fn load_more_messages(&mut self, cx: &mut ViewContext<Self>) {
469 if let Some((chat, _)) = self.active_chat.as_ref() {
470 chat.update(cx, |channel, cx| {
471 if let Some(task) = channel.load_more_messages(cx) {
472 task.detach();
473 }
474 })
475 }
476 }
477
478 pub fn select_channel(
479 &mut self,
480 selected_channel_id: u64,
481 scroll_to_message_id: Option<u64>,
482 cx: &mut ViewContext<ChatPanel>,
483 ) -> Task<Result<()>> {
484 let open_chat = self
485 .active_chat
486 .as_ref()
487 .and_then(|(chat, _)| {
488 (chat.read(cx).channel_id == selected_channel_id)
489 .then(|| Task::ready(anyhow::Ok(chat.clone())))
490 })
491 .unwrap_or_else(|| {
492 self.channel_store.update(cx, |store, cx| {
493 store.open_channel_chat(selected_channel_id, cx)
494 })
495 });
496
497 cx.spawn(|this, mut cx| async move {
498 let chat = open_chat.await?;
499 this.update(&mut cx, |this, cx| {
500 this.set_active_chat(chat.clone(), cx);
501 })?;
502
503 if let Some(message_id) = scroll_to_message_id {
504 if let Some(item_ix) =
505 ChannelChat::load_history_since_message(chat.clone(), message_id, (*cx).clone())
506 .await
507 {
508 this.update(&mut cx, |this, cx| {
509 if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
510 this.message_list.scroll_to(ListOffset {
511 item_ix,
512 offset_in_item: px(0.0),
513 });
514 cx.notify();
515 }
516 })?;
517 }
518 }
519
520 Ok(())
521 })
522 }
523}
524
525impl Render for ChatPanel {
526 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
527 v_flex()
528 .track_focus(&self.focus_handle)
529 .full()
530 .on_action(cx.listener(Self::send))
531 .child(
532 h_flex().z_index(1).child(
533 TabBar::new("chat_header").child(
534 h_flex()
535 .w_full()
536 .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
537 .px_2()
538 .child(Label::new(
539 self.active_chat
540 .as_ref()
541 .and_then(|c| {
542 Some(format!("#{}", c.0.read(cx).channel(cx)?.name))
543 })
544 .unwrap_or("Chat".to_string()),
545 )),
546 ),
547 ),
548 )
549 .child(div().flex_grow().px_2().pt_1().map(|this| {
550 if self.active_chat.is_some() {
551 this.child(list(self.message_list.clone()).full())
552 } else {
553 this.child(
554 div()
555 .full()
556 .p_4()
557 .child(
558 Label::new("Select a channel to chat in.")
559 .size(LabelSize::Small)
560 .color(Color::Muted),
561 )
562 .child(
563 div().pt_1().w_full().items_center().child(
564 Button::new("toggle-collab", "Open")
565 .full_width()
566 .key_binding(KeyBinding::for_action(
567 &collab_panel::ToggleFocus,
568 cx,
569 ))
570 .on_click(|_, cx| {
571 cx.dispatch_action(
572 collab_panel::ToggleFocus.boxed_clone(),
573 )
574 }),
575 ),
576 ),
577 )
578 }
579 }))
580 .child(
581 h_flex()
582 .when(!self.is_scrolled_to_bottom, |el| {
583 el.border_t_1().border_color(cx.theme().colors().border)
584 })
585 .p_2()
586 .map(|el| {
587 if self.active_chat.is_some() {
588 el.child(self.message_editor.clone())
589 } else {
590 el.child(
591 div()
592 .rounded_md()
593 .h_6()
594 .w_full()
595 .bg(cx.theme().colors().editor_background),
596 )
597 }
598 }),
599 )
600 .into_any()
601 }
602}
603
604impl FocusableView for ChatPanel {
605 fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
606 if self.active_chat.is_some() {
607 self.message_editor.read(cx).focus_handle(cx)
608 } else {
609 self.focus_handle.clone()
610 }
611 }
612}
613
614impl Panel for ChatPanel {
615 fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
616 ChatPanelSettings::get_global(cx).dock
617 }
618
619 fn position_is_valid(&self, position: DockPosition) -> bool {
620 matches!(position, DockPosition::Left | DockPosition::Right)
621 }
622
623 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
624 settings::update_settings_file::<ChatPanelSettings>(self.fs.clone(), cx, move |settings| {
625 settings.dock = Some(position)
626 });
627 }
628
629 fn size(&self, cx: &gpui::WindowContext) -> Pixels {
630 self.width
631 .unwrap_or_else(|| ChatPanelSettings::get_global(cx).default_width)
632 }
633
634 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
635 self.width = size;
636 self.serialize(cx);
637 cx.notify();
638 }
639
640 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
641 self.active = active;
642 if active {
643 self.acknowledge_last_message(cx);
644 }
645 }
646
647 fn persistent_name() -> &'static str {
648 "ChatPanel"
649 }
650
651 fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
652 Some(ui::IconName::MessageBubbles).filter(|_| ChatPanelSettings::get_global(cx).button)
653 }
654
655 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
656 Some("Chat Panel")
657 }
658
659 fn toggle_action(&self) -> Box<dyn gpui::Action> {
660 Box::new(ToggleFocus)
661 }
662
663 fn starts_open(&self, cx: &WindowContext) -> bool {
664 ActiveCall::global(cx)
665 .read(cx)
666 .room()
667 .is_some_and(|room| room.read(cx).contains_guests())
668 }
669}
670
671impl EventEmitter<PanelEvent> for ChatPanel {}
672
673fn format_timestamp(
674 reference: OffsetDateTime,
675 timestamp: OffsetDateTime,
676 timezone: UtcOffset,
677) -> String {
678 let timestamp_local = timestamp.to_offset(timezone);
679 let timestamp_local_hour = timestamp_local.hour();
680
681 let hour_12 = match timestamp_local_hour {
682 0 => 12, // Midnight
683 13..=23 => timestamp_local_hour - 12, // PM hours
684 _ => timestamp_local_hour, // AM hours
685 };
686 let meridiem = if timestamp_local_hour >= 12 {
687 "pm"
688 } else {
689 "am"
690 };
691 let timestamp_local_minute = timestamp_local.minute();
692 let formatted_time = format!("{:02}:{:02} {}", hour_12, timestamp_local_minute, meridiem);
693
694 let reference_local = reference.to_offset(timezone);
695 let reference_local_date = reference_local.date();
696 let timestamp_local_date = timestamp_local.date();
697
698 if timestamp_local_date == reference_local_date {
699 return formatted_time;
700 }
701
702 if reference_local_date.previous_day() == Some(timestamp_local_date) {
703 return format!("yesterday at {}", formatted_time);
704 }
705
706 format!(
707 "{:02}/{:02}/{}",
708 timestamp_local_date.month() as u32,
709 timestamp_local_date.day(),
710 timestamp_local_date.year()
711 )
712}
713
714#[cfg(test)]
715mod tests {
716 use super::*;
717 use gpui::HighlightStyle;
718 use pretty_assertions::assert_eq;
719 use rich_text::Highlight;
720 use time::{Date, OffsetDateTime, Time, UtcOffset};
721 use util::test::marked_text_ranges;
722
723 #[gpui::test]
724 fn test_render_markdown_with_mentions() {
725 let language_registry = Arc::new(LanguageRegistry::test());
726 let (body, ranges) = marked_text_ranges("*hi*, «@abc», let's **call** «@fgh»", false);
727 let message = channel::ChannelMessage {
728 id: ChannelMessageId::Saved(0),
729 body,
730 timestamp: OffsetDateTime::now_utc(),
731 sender: Arc::new(client::User {
732 github_login: "fgh".into(),
733 avatar_uri: "avatar_fgh".into(),
734 id: 103,
735 }),
736 nonce: 5,
737 mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],
738 };
739
740 let message = ChatPanel::render_markdown_with_mentions(&language_registry, 102, &message);
741
742 // Note that the "'" was replaced with ’ due to smart punctuation.
743 let (body, ranges) = marked_text_ranges("«hi», «@abc», let’s «call» «@fgh»", false);
744 assert_eq!(message.text, body);
745 assert_eq!(
746 message.highlights,
747 vec![
748 (
749 ranges[0].clone(),
750 HighlightStyle {
751 font_style: Some(gpui::FontStyle::Italic),
752 ..Default::default()
753 }
754 .into()
755 ),
756 (ranges[1].clone(), Highlight::Mention),
757 (
758 ranges[2].clone(),
759 HighlightStyle {
760 font_weight: Some(gpui::FontWeight::BOLD),
761 ..Default::default()
762 }
763 .into()
764 ),
765 (ranges[3].clone(), Highlight::SelfMention)
766 ]
767 );
768 }
769
770 #[test]
771 fn test_format_today() {
772 let reference = create_offset_datetime(1990, 4, 12, 16, 45, 0);
773 let timestamp = create_offset_datetime(1990, 4, 12, 15, 30, 0);
774
775 assert_eq!(
776 format_timestamp(reference, timestamp, test_timezone()),
777 "03:30 pm"
778 );
779 }
780
781 #[test]
782 fn test_format_yesterday() {
783 let reference = create_offset_datetime(1990, 4, 12, 10, 30, 0);
784 let timestamp = create_offset_datetime(1990, 4, 11, 9, 0, 0);
785
786 assert_eq!(
787 format_timestamp(reference, timestamp, test_timezone()),
788 "yesterday at 09:00 am"
789 );
790 }
791
792 #[test]
793 fn test_format_yesterday_less_than_24_hours_ago() {
794 let reference = create_offset_datetime(1990, 4, 12, 19, 59, 0);
795 let timestamp = create_offset_datetime(1990, 4, 11, 20, 0, 0);
796
797 assert_eq!(
798 format_timestamp(reference, timestamp, test_timezone()),
799 "yesterday at 08:00 pm"
800 );
801 }
802
803 #[test]
804 fn test_format_yesterday_more_than_24_hours_ago() {
805 let reference = create_offset_datetime(1990, 4, 12, 19, 59, 0);
806 let timestamp = create_offset_datetime(1990, 4, 11, 18, 0, 0);
807
808 assert_eq!(
809 format_timestamp(reference, timestamp, test_timezone()),
810 "yesterday at 06:00 pm"
811 );
812 }
813
814 #[test]
815 fn test_format_yesterday_over_midnight() {
816 let reference = create_offset_datetime(1990, 4, 12, 0, 5, 0);
817 let timestamp = create_offset_datetime(1990, 4, 11, 23, 55, 0);
818
819 assert_eq!(
820 format_timestamp(reference, timestamp, test_timezone()),
821 "yesterday at 11:55 pm"
822 );
823 }
824
825 #[test]
826 fn test_format_yesterday_over_month() {
827 let reference = create_offset_datetime(1990, 4, 2, 9, 0, 0);
828 let timestamp = create_offset_datetime(1990, 4, 1, 20, 0, 0);
829
830 assert_eq!(
831 format_timestamp(reference, timestamp, test_timezone()),
832 "yesterday at 08:00 pm"
833 );
834 }
835
836 #[test]
837 fn test_format_before_yesterday() {
838 let reference = create_offset_datetime(1990, 4, 12, 10, 30, 0);
839 let timestamp = create_offset_datetime(1990, 4, 10, 20, 20, 0);
840
841 assert_eq!(
842 format_timestamp(reference, timestamp, test_timezone()),
843 "04/10/1990"
844 );
845 }
846
847 fn test_timezone() -> UtcOffset {
848 UtcOffset::from_hms(0, 0, 0).expect("Valid timezone offset")
849 }
850
851 fn create_offset_datetime(
852 year: i32,
853 month: u8,
854 day: u8,
855 hour: u8,
856 minute: u8,
857 second: u8,
858 ) -> OffsetDateTime {
859 let date =
860 Date::from_calendar_date(year, time::Month::try_from(month).unwrap(), day).unwrap();
861 let time = Time::from_hms(hour, minute, second).unwrap();
862 date.with_time(time).assume_utc() // Assume UTC for simplicity
863 }
864}