1use std::fmt::Display;
2use std::ops::Range;
3use std::sync::Arc;
4
5use chrono::{Datelike as _, Local, NaiveDate, TimeDelta};
6use editor::{Editor, EditorEvent};
7use fuzzy::{StringMatch, StringMatchCandidate};
8use gpui::{
9 App, ClickEvent, Empty, Entity, FocusHandle, Focusable, ScrollStrategy, Stateful, Task,
10 UniformListScrollHandle, WeakEntity, Window, uniform_list,
11};
12use time::{OffsetDateTime, UtcOffset};
13use ui::{
14 HighlightedLabel, IconButtonShape, ListItem, ListItemSpacing, Scrollbar, ScrollbarState,
15 Tooltip, prelude::*,
16};
17use util::ResultExt;
18
19use crate::history_store::{HistoryEntry, HistoryStore};
20use crate::{AgentPanel, RemoveSelectedThread};
21
22pub struct ThreadHistory {
23 agent_panel: WeakEntity<AgentPanel>,
24 history_store: Entity<HistoryStore>,
25 scroll_handle: UniformListScrollHandle,
26 selected_index: usize,
27 hovered_index: Option<usize>,
28 search_editor: Entity<Editor>,
29 all_entries: Arc<Vec<HistoryEntry>>,
30 // When the search is empty, we display date separators between history entries
31 // This vector contains an enum of either a separator or an actual entry
32 separated_items: Vec<ListItemType>,
33 // Maps entry indexes to list item indexes
34 separated_item_indexes: Vec<u32>,
35 _separated_items_task: Option<Task<()>>,
36 search_state: SearchState,
37 scrollbar_visibility: bool,
38 scrollbar_state: ScrollbarState,
39 _subscriptions: Vec<gpui::Subscription>,
40}
41
42enum SearchState {
43 Empty,
44 Searching {
45 query: SharedString,
46 _task: Task<()>,
47 },
48 Searched {
49 query: SharedString,
50 matches: Vec<StringMatch>,
51 },
52}
53
54enum ListItemType {
55 BucketSeparator(TimeBucket),
56 Entry {
57 index: usize,
58 format: EntryTimeFormat,
59 },
60}
61
62impl ListItemType {
63 fn entry_index(&self) -> Option<usize> {
64 match self {
65 ListItemType::BucketSeparator(_) => None,
66 ListItemType::Entry { index, .. } => Some(*index),
67 }
68 }
69}
70
71impl ThreadHistory {
72 pub(crate) fn new(
73 agent_panel: WeakEntity<AgentPanel>,
74 history_store: Entity<HistoryStore>,
75 window: &mut Window,
76 cx: &mut Context<Self>,
77 ) -> Self {
78 let search_editor = cx.new(|cx| {
79 let mut editor = Editor::single_line(window, cx);
80 editor.set_placeholder_text("Search threads...", cx);
81 editor
82 });
83
84 let search_editor_subscription =
85 cx.subscribe(&search_editor, |this, search_editor, event, cx| {
86 if let EditorEvent::BufferEdited = event {
87 let query = search_editor.read(cx).text(cx);
88 this.search(query.into(), cx);
89 }
90 });
91
92 let history_store_subscription = cx.observe(&history_store, |this, _, cx| {
93 this.update_all_entries(cx);
94 });
95
96 let scroll_handle = UniformListScrollHandle::default();
97 let scrollbar_state = ScrollbarState::new(scroll_handle.clone());
98
99 let mut this = Self {
100 agent_panel,
101 history_store,
102 scroll_handle,
103 selected_index: 0,
104 hovered_index: None,
105 search_state: SearchState::Empty,
106 all_entries: Default::default(),
107 separated_items: Default::default(),
108 separated_item_indexes: Default::default(),
109 search_editor,
110 scrollbar_visibility: true,
111 scrollbar_state,
112 _subscriptions: vec![search_editor_subscription, history_store_subscription],
113 _separated_items_task: None,
114 };
115 this.update_all_entries(cx);
116 this
117 }
118
119 fn update_all_entries(&mut self, cx: &mut Context<Self>) {
120 let new_entries: Arc<Vec<HistoryEntry>> = self
121 .history_store
122 .update(cx, |store, cx| store.entries(cx))
123 .into();
124
125 self._separated_items_task.take();
126
127 let mut items = Vec::with_capacity(new_entries.len() + 1);
128 let mut indexes = Vec::with_capacity(new_entries.len() + 1);
129
130 let bg_task = cx.background_spawn(async move {
131 let mut bucket = None;
132 let today = Local::now().naive_local().date();
133
134 for (index, entry) in new_entries.iter().enumerate() {
135 let entry_date = entry
136 .updated_at()
137 .with_timezone(&Local)
138 .naive_local()
139 .date();
140 let entry_bucket = TimeBucket::from_dates(today, entry_date);
141
142 if Some(entry_bucket) != bucket {
143 bucket = Some(entry_bucket);
144 items.push(ListItemType::BucketSeparator(entry_bucket));
145 }
146
147 indexes.push(items.len() as u32);
148 items.push(ListItemType::Entry {
149 index,
150 format: entry_bucket.into(),
151 });
152 }
153 (new_entries, items, indexes)
154 });
155
156 let task = cx.spawn(async move |this, cx| {
157 let (new_entries, items, indexes) = bg_task.await;
158 this.update(cx, |this, cx| {
159 let previously_selected_entry =
160 this.all_entries.get(this.selected_index).map(|e| e.id());
161
162 this.all_entries = new_entries;
163 this.separated_items = items;
164 this.separated_item_indexes = indexes;
165
166 match &this.search_state {
167 SearchState::Empty => {
168 if this.selected_index >= this.all_entries.len() {
169 this.set_selected_entry_index(
170 this.all_entries.len().saturating_sub(1),
171 cx,
172 );
173 } else if let Some(prev_id) = previously_selected_entry {
174 if let Some(new_ix) = this
175 .all_entries
176 .iter()
177 .position(|probe| probe.id() == prev_id)
178 {
179 this.set_selected_entry_index(new_ix, cx);
180 }
181 }
182 }
183 SearchState::Searching { query, .. } | SearchState::Searched { query, .. } => {
184 this.search(query.clone(), cx);
185 }
186 }
187
188 cx.notify();
189 })
190 .log_err();
191 });
192 self._separated_items_task = Some(task);
193 }
194
195 fn search(&mut self, query: SharedString, cx: &mut Context<Self>) {
196 if query.is_empty() {
197 self.search_state = SearchState::Empty;
198 cx.notify();
199 return;
200 }
201
202 let all_entries = self.all_entries.clone();
203
204 let fuzzy_search_task = cx.background_spawn({
205 let query = query.clone();
206 let executor = cx.background_executor().clone();
207 async move {
208 let mut candidates = Vec::with_capacity(all_entries.len());
209
210 for (idx, entry) in all_entries.iter().enumerate() {
211 match entry {
212 HistoryEntry::Thread(thread) => {
213 candidates.push(StringMatchCandidate::new(idx, &thread.summary));
214 }
215 HistoryEntry::Context(context) => {
216 candidates.push(StringMatchCandidate::new(idx, &context.title));
217 }
218 }
219 }
220
221 const MAX_MATCHES: usize = 100;
222
223 fuzzy::match_strings(
224 &candidates,
225 &query,
226 false,
227 MAX_MATCHES,
228 &Default::default(),
229 executor,
230 )
231 .await
232 }
233 });
234
235 let task = cx.spawn({
236 let query = query.clone();
237 async move |this, cx| {
238 let matches = fuzzy_search_task.await;
239
240 this.update(cx, |this, cx| {
241 let SearchState::Searching {
242 query: current_query,
243 _task,
244 } = &this.search_state
245 else {
246 return;
247 };
248
249 if &query == current_query {
250 this.search_state = SearchState::Searched {
251 query: query.clone(),
252 matches,
253 };
254
255 this.set_selected_entry_index(0, cx);
256 cx.notify();
257 };
258 })
259 .log_err();
260 }
261 });
262
263 self.search_state = SearchState::Searching { query, _task: task };
264 cx.notify();
265 }
266
267 fn matched_count(&self) -> usize {
268 match &self.search_state {
269 SearchState::Empty => self.all_entries.len(),
270 SearchState::Searching { .. } => 0,
271 SearchState::Searched { matches, .. } => matches.len(),
272 }
273 }
274
275 fn list_item_count(&self) -> usize {
276 match &self.search_state {
277 SearchState::Empty => self.separated_items.len(),
278 SearchState::Searching { .. } => 0,
279 SearchState::Searched { matches, .. } => matches.len(),
280 }
281 }
282
283 fn search_produced_no_matches(&self) -> bool {
284 match &self.search_state {
285 SearchState::Empty => false,
286 SearchState::Searching { .. } => false,
287 SearchState::Searched { matches, .. } => matches.is_empty(),
288 }
289 }
290
291 fn get_match(&self, ix: usize) -> Option<&HistoryEntry> {
292 match &self.search_state {
293 SearchState::Empty => self.all_entries.get(ix),
294 SearchState::Searching { .. } => None,
295 SearchState::Searched { matches, .. } => matches
296 .get(ix)
297 .and_then(|m| self.all_entries.get(m.candidate_id)),
298 }
299 }
300
301 pub fn select_previous(
302 &mut self,
303 _: &menu::SelectPrevious,
304 _window: &mut Window,
305 cx: &mut Context<Self>,
306 ) {
307 let count = self.matched_count();
308 if count > 0 {
309 if self.selected_index == 0 {
310 self.set_selected_entry_index(count - 1, cx);
311 } else {
312 self.set_selected_entry_index(self.selected_index - 1, cx);
313 }
314 }
315 }
316
317 pub fn select_next(
318 &mut self,
319 _: &menu::SelectNext,
320 _window: &mut Window,
321 cx: &mut Context<Self>,
322 ) {
323 let count = self.matched_count();
324 if count > 0 {
325 if self.selected_index == count - 1 {
326 self.set_selected_entry_index(0, cx);
327 } else {
328 self.set_selected_entry_index(self.selected_index + 1, cx);
329 }
330 }
331 }
332
333 fn select_first(
334 &mut self,
335 _: &menu::SelectFirst,
336 _window: &mut Window,
337 cx: &mut Context<Self>,
338 ) {
339 let count = self.matched_count();
340 if count > 0 {
341 self.set_selected_entry_index(0, cx);
342 }
343 }
344
345 fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
346 let count = self.matched_count();
347 if count > 0 {
348 self.set_selected_entry_index(count - 1, cx);
349 }
350 }
351
352 fn set_selected_entry_index(&mut self, entry_index: usize, cx: &mut Context<Self>) {
353 self.selected_index = entry_index;
354
355 let scroll_ix = match self.search_state {
356 SearchState::Empty | SearchState::Searching { .. } => self
357 .separated_item_indexes
358 .get(entry_index)
359 .map(|ix| *ix as usize)
360 .unwrap_or(entry_index + 1),
361 SearchState::Searched { .. } => entry_index,
362 };
363
364 self.scroll_handle
365 .scroll_to_item(scroll_ix, ScrollStrategy::Top);
366
367 cx.notify();
368 }
369
370 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
371 if !(self.scrollbar_visibility || self.scrollbar_state.is_dragging()) {
372 return None;
373 }
374
375 Some(
376 div()
377 .occlude()
378 .id("thread-history-scroll")
379 .h_full()
380 .bg(cx.theme().colors().panel_background.opacity(0.8))
381 .border_l_1()
382 .border_color(cx.theme().colors().border_variant)
383 .absolute()
384 .right_1()
385 .top_0()
386 .bottom_0()
387 .w_4()
388 .pl_1()
389 .cursor_default()
390 .on_mouse_move(cx.listener(|_, _, _window, cx| {
391 cx.notify();
392 cx.stop_propagation()
393 }))
394 .on_hover(|_, _window, cx| {
395 cx.stop_propagation();
396 })
397 .on_any_mouse_down(|_, _window, cx| {
398 cx.stop_propagation();
399 })
400 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
401 cx.notify();
402 }))
403 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
404 )
405 }
406
407 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
408 if let Some(entry) = self.get_match(self.selected_index) {
409 let task_result = match entry {
410 HistoryEntry::Thread(thread) => self.agent_panel.update(cx, move |this, cx| {
411 this.open_thread_by_id(&thread.id, window, cx)
412 }),
413 HistoryEntry::Context(context) => self.agent_panel.update(cx, move |this, cx| {
414 this.open_saved_prompt_editor(context.path.clone(), window, cx)
415 }),
416 };
417
418 if let Some(task) = task_result.log_err() {
419 task.detach_and_log_err(cx);
420 };
421
422 cx.notify();
423 }
424 }
425
426 fn remove_selected_thread(
427 &mut self,
428 _: &RemoveSelectedThread,
429 _window: &mut Window,
430 cx: &mut Context<Self>,
431 ) {
432 if let Some(entry) = self.get_match(self.selected_index) {
433 let task_result = match entry {
434 HistoryEntry::Thread(thread) => self
435 .agent_panel
436 .update(cx, |this, cx| this.delete_thread(&thread.id, cx)),
437 HistoryEntry::Context(context) => self
438 .agent_panel
439 .update(cx, |this, cx| this.delete_context(context.path.clone(), cx)),
440 };
441
442 if let Some(task) = task_result.log_err() {
443 task.detach_and_log_err(cx);
444 };
445
446 cx.notify();
447 }
448 }
449
450 fn list_items(
451 &mut self,
452 range: Range<usize>,
453 _window: &mut Window,
454 cx: &mut Context<Self>,
455 ) -> Vec<AnyElement> {
456 let range_start = range.start;
457
458 match &self.search_state {
459 SearchState::Empty => self
460 .separated_items
461 .get(range)
462 .iter()
463 .flat_map(|items| {
464 items
465 .iter()
466 .map(|item| self.render_list_item(item.entry_index(), item, vec![], cx))
467 })
468 .collect(),
469 SearchState::Searched { matches, .. } => matches[range]
470 .iter()
471 .enumerate()
472 .map(|(ix, m)| {
473 self.render_list_item(
474 Some(range_start + ix),
475 &ListItemType::Entry {
476 index: m.candidate_id,
477 format: EntryTimeFormat::DateAndTime,
478 },
479 m.positions.clone(),
480 cx,
481 )
482 })
483 .collect(),
484 SearchState::Searching { .. } => {
485 vec![]
486 }
487 }
488 }
489
490 fn render_list_item(
491 &self,
492 list_entry_ix: Option<usize>,
493 item: &ListItemType,
494 highlight_positions: Vec<usize>,
495 cx: &Context<Self>,
496 ) -> AnyElement {
497 match item {
498 ListItemType::Entry { index, format } => match self.all_entries.get(*index) {
499 Some(entry) => h_flex()
500 .w_full()
501 .pb_1()
502 .child(
503 HistoryEntryElement::new(entry.clone(), self.agent_panel.clone())
504 .highlight_positions(highlight_positions)
505 .timestamp_format(*format)
506 .selected(list_entry_ix == Some(self.selected_index))
507 .hovered(list_entry_ix == self.hovered_index)
508 .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
509 if *is_hovered {
510 this.hovered_index = list_entry_ix;
511 } else if this.hovered_index == list_entry_ix {
512 this.hovered_index = None;
513 }
514
515 cx.notify();
516 }))
517 .into_any_element(),
518 )
519 .into_any(),
520 None => Empty.into_any_element(),
521 },
522 ListItemType::BucketSeparator(bucket) => div()
523 .px(DynamicSpacing::Base06.rems(cx))
524 .pt_2()
525 .pb_1()
526 .child(
527 Label::new(bucket.to_string())
528 .size(LabelSize::XSmall)
529 .color(Color::Muted),
530 )
531 .into_any_element(),
532 }
533 }
534}
535
536impl Focusable for ThreadHistory {
537 fn focus_handle(&self, cx: &App) -> FocusHandle {
538 self.search_editor.focus_handle(cx)
539 }
540}
541
542impl Render for ThreadHistory {
543 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
544 v_flex()
545 .key_context("ThreadHistory")
546 .size_full()
547 .on_action(cx.listener(Self::select_previous))
548 .on_action(cx.listener(Self::select_next))
549 .on_action(cx.listener(Self::select_first))
550 .on_action(cx.listener(Self::select_last))
551 .on_action(cx.listener(Self::confirm))
552 .on_action(cx.listener(Self::remove_selected_thread))
553 .when(!self.all_entries.is_empty(), |parent| {
554 parent.child(
555 h_flex()
556 .h(px(41.)) // Match the toolbar perfectly
557 .w_full()
558 .py_1()
559 .px_2()
560 .gap_2()
561 .justify_between()
562 .border_b_1()
563 .border_color(cx.theme().colors().border)
564 .child(
565 Icon::new(IconName::MagnifyingGlass)
566 .color(Color::Muted)
567 .size(IconSize::Small),
568 )
569 .child(self.search_editor.clone()),
570 )
571 })
572 .child({
573 let view = v_flex()
574 .id("list-container")
575 .relative()
576 .overflow_hidden()
577 .flex_grow();
578
579 if self.all_entries.is_empty() {
580 view.justify_center()
581 .child(
582 h_flex().w_full().justify_center().child(
583 Label::new("You don't have any past threads yet.")
584 .size(LabelSize::Small),
585 ),
586 )
587 } else if self.search_produced_no_matches() {
588 view.justify_center().child(
589 h_flex().w_full().justify_center().child(
590 Label::new("No threads match your search.").size(LabelSize::Small),
591 ),
592 )
593 } else {
594 view.pr_5()
595 .child(
596 uniform_list(
597 cx.entity().clone(),
598 "thread-history",
599 self.list_item_count(),
600 Self::list_items,
601 )
602 .p_1()
603 .track_scroll(self.scroll_handle.clone())
604 .flex_grow(),
605 )
606 .when_some(self.render_scrollbar(cx), |div, scrollbar| {
607 div.child(scrollbar)
608 })
609 }
610 })
611 }
612}
613
614#[derive(IntoElement)]
615pub struct HistoryEntryElement {
616 entry: HistoryEntry,
617 agent_panel: WeakEntity<AgentPanel>,
618 selected: bool,
619 hovered: bool,
620 highlight_positions: Vec<usize>,
621 timestamp_format: EntryTimeFormat,
622 on_hover: Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>,
623}
624
625impl HistoryEntryElement {
626 pub fn new(entry: HistoryEntry, agent_panel: WeakEntity<AgentPanel>) -> Self {
627 Self {
628 entry,
629 agent_panel,
630 selected: false,
631 hovered: false,
632 highlight_positions: vec![],
633 timestamp_format: EntryTimeFormat::DateAndTime,
634 on_hover: Box::new(|_, _, _| {}),
635 }
636 }
637
638 pub fn selected(mut self, selected: bool) -> Self {
639 self.selected = selected;
640 self
641 }
642
643 pub fn hovered(mut self, hovered: bool) -> Self {
644 self.hovered = hovered;
645 self
646 }
647
648 pub fn highlight_positions(mut self, positions: Vec<usize>) -> Self {
649 self.highlight_positions = positions;
650 self
651 }
652
653 pub fn on_hover(mut self, on_hover: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
654 self.on_hover = Box::new(on_hover);
655 self
656 }
657
658 pub fn timestamp_format(mut self, format: EntryTimeFormat) -> Self {
659 self.timestamp_format = format;
660 self
661 }
662}
663
664impl RenderOnce for HistoryEntryElement {
665 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
666 let (id, summary, timestamp) = match &self.entry {
667 HistoryEntry::Thread(thread) => (
668 thread.id.to_string(),
669 thread.summary.clone(),
670 thread.updated_at.timestamp(),
671 ),
672 HistoryEntry::Context(context) => (
673 context.path.to_string_lossy().to_string(),
674 context.title.clone().into(),
675 context.mtime.timestamp(),
676 ),
677 };
678
679 let thread_timestamp =
680 self.timestamp_format
681 .format_timestamp(&self.agent_panel, timestamp, cx);
682
683 ListItem::new(SharedString::from(id))
684 .rounded()
685 .toggle_state(self.selected)
686 .spacing(ListItemSpacing::Sparse)
687 .start_slot(
688 h_flex()
689 .w_full()
690 .gap_2()
691 .justify_between()
692 .child(
693 HighlightedLabel::new(summary, self.highlight_positions)
694 .size(LabelSize::Small)
695 .truncate(),
696 )
697 .child(
698 Label::new(thread_timestamp)
699 .color(Color::Muted)
700 .size(LabelSize::XSmall),
701 ),
702 )
703 .on_hover(self.on_hover)
704 .end_slot::<IconButton>(if self.hovered || self.selected {
705 Some(
706 IconButton::new("delete", IconName::TrashAlt)
707 .shape(IconButtonShape::Square)
708 .icon_size(IconSize::XSmall)
709 .icon_color(Color::Muted)
710 .tooltip(move |window, cx| {
711 Tooltip::for_action("Delete", &RemoveSelectedThread, window, cx)
712 })
713 .on_click({
714 let agent_panel = self.agent_panel.clone();
715
716 let f: Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static> =
717 match &self.entry {
718 HistoryEntry::Thread(thread) => {
719 let id = thread.id.clone();
720
721 Box::new(move |_event, _window, cx| {
722 agent_panel
723 .update(cx, |this, cx| {
724 this.delete_thread(&id, cx)
725 .detach_and_log_err(cx);
726 })
727 .ok();
728 })
729 }
730 HistoryEntry::Context(context) => {
731 let path = context.path.clone();
732
733 Box::new(move |_event, _window, cx| {
734 agent_panel
735 .update(cx, |this, cx| {
736 this.delete_context(path.clone(), cx)
737 .detach_and_log_err(cx);
738 })
739 .ok();
740 })
741 }
742 };
743 f
744 }),
745 )
746 } else {
747 None
748 })
749 .on_click({
750 let agent_panel = self.agent_panel.clone();
751
752 let f: Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static> = match &self.entry
753 {
754 HistoryEntry::Thread(thread) => {
755 let id = thread.id.clone();
756 Box::new(move |_event, window, cx| {
757 agent_panel
758 .update(cx, |this, cx| {
759 this.open_thread_by_id(&id, window, cx)
760 .detach_and_log_err(cx);
761 })
762 .ok();
763 })
764 }
765 HistoryEntry::Context(context) => {
766 let path = context.path.clone();
767 Box::new(move |_event, window, cx| {
768 agent_panel
769 .update(cx, |this, cx| {
770 this.open_saved_prompt_editor(path.clone(), window, cx)
771 .detach_and_log_err(cx);
772 })
773 .ok();
774 })
775 }
776 };
777 f
778 })
779 }
780}
781
782#[derive(Clone, Copy)]
783pub enum EntryTimeFormat {
784 DateAndTime,
785 TimeOnly,
786}
787
788impl EntryTimeFormat {
789 fn format_timestamp(
790 &self,
791 agent_panel: &WeakEntity<AgentPanel>,
792 timestamp: i64,
793 cx: &App,
794 ) -> String {
795 let timestamp = OffsetDateTime::from_unix_timestamp(timestamp).unwrap();
796 let timezone = agent_panel
797 .read_with(cx, |this, _cx| this.local_timezone())
798 .unwrap_or(UtcOffset::UTC);
799
800 match &self {
801 EntryTimeFormat::DateAndTime => time_format::format_localized_timestamp(
802 timestamp,
803 OffsetDateTime::now_utc(),
804 timezone,
805 time_format::TimestampFormat::EnhancedAbsolute,
806 ),
807 EntryTimeFormat::TimeOnly => time_format::format_time(timestamp),
808 }
809 }
810}
811
812impl From<TimeBucket> for EntryTimeFormat {
813 fn from(bucket: TimeBucket) -> Self {
814 match bucket {
815 TimeBucket::Today => EntryTimeFormat::TimeOnly,
816 TimeBucket::Yesterday => EntryTimeFormat::TimeOnly,
817 TimeBucket::ThisWeek => EntryTimeFormat::DateAndTime,
818 TimeBucket::PastWeek => EntryTimeFormat::DateAndTime,
819 TimeBucket::All => EntryTimeFormat::DateAndTime,
820 }
821 }
822}
823
824#[derive(PartialEq, Eq, Clone, Copy, Debug)]
825enum TimeBucket {
826 Today,
827 Yesterday,
828 ThisWeek,
829 PastWeek,
830 All,
831}
832
833impl TimeBucket {
834 fn from_dates(reference: NaiveDate, date: NaiveDate) -> Self {
835 if date == reference {
836 return TimeBucket::Today;
837 }
838
839 if date == reference - TimeDelta::days(1) {
840 return TimeBucket::Yesterday;
841 }
842
843 let week = date.iso_week();
844
845 if reference.iso_week() == week {
846 return TimeBucket::ThisWeek;
847 }
848
849 let last_week = (reference - TimeDelta::days(7)).iso_week();
850
851 if week == last_week {
852 return TimeBucket::PastWeek;
853 }
854
855 TimeBucket::All
856 }
857}
858
859impl Display for TimeBucket {
860 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
861 match self {
862 TimeBucket::Today => write!(f, "Today"),
863 TimeBucket::Yesterday => write!(f, "Yesterday"),
864 TimeBucket::ThisWeek => write!(f, "This Week"),
865 TimeBucket::PastWeek => write!(f, "Past Week"),
866 TimeBucket::All => write!(f, "All"),
867 }
868 }
869}
870
871#[cfg(test)]
872mod tests {
873 use super::*;
874 use chrono::NaiveDate;
875
876 #[test]
877 fn test_time_bucket_from_dates() {
878 let today = NaiveDate::from_ymd_opt(2023, 1, 15).unwrap();
879
880 let date = today;
881 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::Today);
882
883 let date = NaiveDate::from_ymd_opt(2023, 1, 14).unwrap();
884 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::Yesterday);
885
886 let date = NaiveDate::from_ymd_opt(2023, 1, 13).unwrap();
887 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::ThisWeek);
888
889 let date = NaiveDate::from_ymd_opt(2023, 1, 11).unwrap();
890 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::ThisWeek);
891
892 let date = NaiveDate::from_ymd_opt(2023, 1, 8).unwrap();
893 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::PastWeek);
894
895 let date = NaiveDate::from_ymd_opt(2023, 1, 5).unwrap();
896 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::PastWeek);
897
898 // All: not in this week or last week
899 let date = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap();
900 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::All);
901
902 // Test year boundary cases
903 let new_year = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap();
904
905 let date = NaiveDate::from_ymd_opt(2022, 12, 31).unwrap();
906 assert_eq!(
907 TimeBucket::from_dates(new_year, date),
908 TimeBucket::Yesterday
909 );
910
911 let date = NaiveDate::from_ymd_opt(2022, 12, 28).unwrap();
912 assert_eq!(TimeBucket::from_dates(new_year, date), TimeBucket::ThisWeek);
913 }
914}