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 "thread-history",
598 self.list_item_count(),
599 cx.processor(|this, range: Range<usize>, window, cx| {
600 this.list_items(range, window, cx)
601 }),
602 )
603 .p_1()
604 .track_scroll(self.scroll_handle.clone())
605 .flex_grow(),
606 )
607 .when_some(self.render_scrollbar(cx), |div, scrollbar| {
608 div.child(scrollbar)
609 })
610 }
611 })
612 }
613}
614
615#[derive(IntoElement)]
616pub struct HistoryEntryElement {
617 entry: HistoryEntry,
618 agent_panel: WeakEntity<AgentPanel>,
619 selected: bool,
620 hovered: bool,
621 highlight_positions: Vec<usize>,
622 timestamp_format: EntryTimeFormat,
623 on_hover: Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>,
624}
625
626impl HistoryEntryElement {
627 pub fn new(entry: HistoryEntry, agent_panel: WeakEntity<AgentPanel>) -> Self {
628 Self {
629 entry,
630 agent_panel,
631 selected: false,
632 hovered: false,
633 highlight_positions: vec![],
634 timestamp_format: EntryTimeFormat::DateAndTime,
635 on_hover: Box::new(|_, _, _| {}),
636 }
637 }
638
639 pub fn selected(mut self, selected: bool) -> Self {
640 self.selected = selected;
641 self
642 }
643
644 pub fn hovered(mut self, hovered: bool) -> Self {
645 self.hovered = hovered;
646 self
647 }
648
649 pub fn highlight_positions(mut self, positions: Vec<usize>) -> Self {
650 self.highlight_positions = positions;
651 self
652 }
653
654 pub fn on_hover(mut self, on_hover: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
655 self.on_hover = Box::new(on_hover);
656 self
657 }
658
659 pub fn timestamp_format(mut self, format: EntryTimeFormat) -> Self {
660 self.timestamp_format = format;
661 self
662 }
663}
664
665impl RenderOnce for HistoryEntryElement {
666 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
667 let (id, summary, timestamp) = match &self.entry {
668 HistoryEntry::Thread(thread) => (
669 thread.id.to_string(),
670 thread.summary.clone(),
671 thread.updated_at.timestamp(),
672 ),
673 HistoryEntry::Context(context) => (
674 context.path.to_string_lossy().to_string(),
675 context.title.clone(),
676 context.mtime.timestamp(),
677 ),
678 };
679
680 let thread_timestamp =
681 self.timestamp_format
682 .format_timestamp(&self.agent_panel, timestamp, cx);
683
684 ListItem::new(SharedString::from(id))
685 .rounded()
686 .toggle_state(self.selected)
687 .spacing(ListItemSpacing::Sparse)
688 .start_slot(
689 h_flex()
690 .w_full()
691 .gap_2()
692 .justify_between()
693 .child(
694 HighlightedLabel::new(summary, self.highlight_positions)
695 .size(LabelSize::Small)
696 .truncate(),
697 )
698 .child(
699 Label::new(thread_timestamp)
700 .color(Color::Muted)
701 .size(LabelSize::XSmall),
702 ),
703 )
704 .on_hover(self.on_hover)
705 .end_slot::<IconButton>(if self.hovered || self.selected {
706 Some(
707 IconButton::new("delete", IconName::TrashAlt)
708 .shape(IconButtonShape::Square)
709 .icon_size(IconSize::XSmall)
710 .icon_color(Color::Muted)
711 .tooltip(move |window, cx| {
712 Tooltip::for_action("Delete", &RemoveSelectedThread, window, cx)
713 })
714 .on_click({
715 let agent_panel = self.agent_panel.clone();
716
717 let f: Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static> =
718 match &self.entry {
719 HistoryEntry::Thread(thread) => {
720 let id = thread.id.clone();
721
722 Box::new(move |_event, _window, cx| {
723 agent_panel
724 .update(cx, |this, cx| {
725 this.delete_thread(&id, cx)
726 .detach_and_log_err(cx);
727 })
728 .ok();
729 })
730 }
731 HistoryEntry::Context(context) => {
732 let path = context.path.clone();
733
734 Box::new(move |_event, _window, cx| {
735 agent_panel
736 .update(cx, |this, cx| {
737 this.delete_context(path.clone(), cx)
738 .detach_and_log_err(cx);
739 })
740 .ok();
741 })
742 }
743 };
744 f
745 }),
746 )
747 } else {
748 None
749 })
750 .on_click({
751 let agent_panel = self.agent_panel.clone();
752
753 let f: Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static> = match &self.entry
754 {
755 HistoryEntry::Thread(thread) => {
756 let id = thread.id.clone();
757 Box::new(move |_event, window, cx| {
758 agent_panel
759 .update(cx, |this, cx| {
760 this.open_thread_by_id(&id, window, cx)
761 .detach_and_log_err(cx);
762 })
763 .ok();
764 })
765 }
766 HistoryEntry::Context(context) => {
767 let path = context.path.clone();
768 Box::new(move |_event, window, cx| {
769 agent_panel
770 .update(cx, |this, cx| {
771 this.open_saved_prompt_editor(path.clone(), window, cx)
772 .detach_and_log_err(cx);
773 })
774 .ok();
775 })
776 }
777 };
778 f
779 })
780 }
781}
782
783#[derive(Clone, Copy)]
784pub enum EntryTimeFormat {
785 DateAndTime,
786 TimeOnly,
787}
788
789impl EntryTimeFormat {
790 fn format_timestamp(
791 &self,
792 agent_panel: &WeakEntity<AgentPanel>,
793 timestamp: i64,
794 cx: &App,
795 ) -> String {
796 let timestamp = OffsetDateTime::from_unix_timestamp(timestamp).unwrap();
797 let timezone = agent_panel
798 .read_with(cx, |this, _cx| this.local_timezone())
799 .unwrap_or(UtcOffset::UTC);
800
801 match &self {
802 EntryTimeFormat::DateAndTime => time_format::format_localized_timestamp(
803 timestamp,
804 OffsetDateTime::now_utc(),
805 timezone,
806 time_format::TimestampFormat::EnhancedAbsolute,
807 ),
808 EntryTimeFormat::TimeOnly => time_format::format_time(timestamp),
809 }
810 }
811}
812
813impl From<TimeBucket> for EntryTimeFormat {
814 fn from(bucket: TimeBucket) -> Self {
815 match bucket {
816 TimeBucket::Today => EntryTimeFormat::TimeOnly,
817 TimeBucket::Yesterday => EntryTimeFormat::TimeOnly,
818 TimeBucket::ThisWeek => EntryTimeFormat::DateAndTime,
819 TimeBucket::PastWeek => EntryTimeFormat::DateAndTime,
820 TimeBucket::All => EntryTimeFormat::DateAndTime,
821 }
822 }
823}
824
825#[derive(PartialEq, Eq, Clone, Copy, Debug)]
826enum TimeBucket {
827 Today,
828 Yesterday,
829 ThisWeek,
830 PastWeek,
831 All,
832}
833
834impl TimeBucket {
835 fn from_dates(reference: NaiveDate, date: NaiveDate) -> Self {
836 if date == reference {
837 return TimeBucket::Today;
838 }
839
840 if date == reference - TimeDelta::days(1) {
841 return TimeBucket::Yesterday;
842 }
843
844 let week = date.iso_week();
845
846 if reference.iso_week() == week {
847 return TimeBucket::ThisWeek;
848 }
849
850 let last_week = (reference - TimeDelta::days(7)).iso_week();
851
852 if week == last_week {
853 return TimeBucket::PastWeek;
854 }
855
856 TimeBucket::All
857 }
858}
859
860impl Display for TimeBucket {
861 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
862 match self {
863 TimeBucket::Today => write!(f, "Today"),
864 TimeBucket::Yesterday => write!(f, "Yesterday"),
865 TimeBucket::ThisWeek => write!(f, "This Week"),
866 TimeBucket::PastWeek => write!(f, "Past Week"),
867 TimeBucket::All => write!(f, "All"),
868 }
869 }
870}
871
872#[cfg(test)]
873mod tests {
874 use super::*;
875 use chrono::NaiveDate;
876
877 #[test]
878 fn test_time_bucket_from_dates() {
879 let today = NaiveDate::from_ymd_opt(2023, 1, 15).unwrap();
880
881 let date = today;
882 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::Today);
883
884 let date = NaiveDate::from_ymd_opt(2023, 1, 14).unwrap();
885 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::Yesterday);
886
887 let date = NaiveDate::from_ymd_opt(2023, 1, 13).unwrap();
888 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::ThisWeek);
889
890 let date = NaiveDate::from_ymd_opt(2023, 1, 11).unwrap();
891 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::ThisWeek);
892
893 let date = NaiveDate::from_ymd_opt(2023, 1, 8).unwrap();
894 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::PastWeek);
895
896 let date = NaiveDate::from_ymd_opt(2023, 1, 5).unwrap();
897 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::PastWeek);
898
899 // All: not in this week or last week
900 let date = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap();
901 assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::All);
902
903 // Test year boundary cases
904 let new_year = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap();
905
906 let date = NaiveDate::from_ymd_opt(2022, 12, 31).unwrap();
907 assert_eq!(
908 TimeBucket::from_dates(new_year, date),
909 TimeBucket::Yesterday
910 );
911
912 let date = NaiveDate::from_ymd_opt(2022, 12, 28).unwrap();
913 assert_eq!(TimeBucket::from_dates(new_year, date), TimeBucket::ThisWeek);
914 }
915}