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