thread_history.rs

  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 {
264            query: query.clone(),
265            _task: task,
266        };
267        cx.notify();
268    }
269
270    fn matched_count(&self) -> usize {
271        match &self.search_state {
272            SearchState::Empty => self.all_entries.len(),
273            SearchState::Searching { .. } => 0,
274            SearchState::Searched { matches, .. } => matches.len(),
275        }
276    }
277
278    fn list_item_count(&self) -> usize {
279        match &self.search_state {
280            SearchState::Empty => self.separated_items.len(),
281            SearchState::Searching { .. } => 0,
282            SearchState::Searched { matches, .. } => matches.len(),
283        }
284    }
285
286    fn search_produced_no_matches(&self) -> bool {
287        match &self.search_state {
288            SearchState::Empty => false,
289            SearchState::Searching { .. } => false,
290            SearchState::Searched { matches, .. } => matches.is_empty(),
291        }
292    }
293
294    fn get_match(&self, ix: usize) -> Option<&HistoryEntry> {
295        match &self.search_state {
296            SearchState::Empty => self.all_entries.get(ix),
297            SearchState::Searching { .. } => None,
298            SearchState::Searched { matches, .. } => matches
299                .get(ix)
300                .and_then(|m| self.all_entries.get(m.candidate_id)),
301        }
302    }
303
304    pub fn select_previous(
305        &mut self,
306        _: &menu::SelectPrevious,
307        _window: &mut Window,
308        cx: &mut Context<Self>,
309    ) {
310        let count = self.matched_count();
311        if count > 0 {
312            if self.selected_index == 0 {
313                self.set_selected_entry_index(count - 1, cx);
314            } else {
315                self.set_selected_entry_index(self.selected_index - 1, cx);
316            }
317        }
318    }
319
320    pub fn select_next(
321        &mut self,
322        _: &menu::SelectNext,
323        _window: &mut Window,
324        cx: &mut Context<Self>,
325    ) {
326        let count = self.matched_count();
327        if count > 0 {
328            if self.selected_index == count - 1 {
329                self.set_selected_entry_index(0, cx);
330            } else {
331                self.set_selected_entry_index(self.selected_index + 1, cx);
332            }
333        }
334    }
335
336    fn select_first(
337        &mut self,
338        _: &menu::SelectFirst,
339        _window: &mut Window,
340        cx: &mut Context<Self>,
341    ) {
342        let count = self.matched_count();
343        if count > 0 {
344            self.set_selected_entry_index(0, cx);
345        }
346    }
347
348    fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
349        let count = self.matched_count();
350        if count > 0 {
351            self.set_selected_entry_index(count - 1, cx);
352        }
353    }
354
355    fn set_selected_entry_index(&mut self, entry_index: usize, cx: &mut Context<Self>) {
356        self.selected_index = entry_index;
357
358        let scroll_ix = match self.search_state {
359            SearchState::Empty | SearchState::Searching { .. } => self
360                .separated_item_indexes
361                .get(entry_index)
362                .map(|ix| *ix as usize)
363                .unwrap_or(entry_index + 1),
364            SearchState::Searched { .. } => entry_index,
365        };
366
367        self.scroll_handle
368            .scroll_to_item(scroll_ix, ScrollStrategy::Top);
369
370        cx.notify();
371    }
372
373    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
374        if !(self.scrollbar_visibility || self.scrollbar_state.is_dragging()) {
375            return None;
376        }
377
378        Some(
379            div()
380                .occlude()
381                .id("thread-history-scroll")
382                .h_full()
383                .bg(cx.theme().colors().panel_background.opacity(0.8))
384                .border_l_1()
385                .border_color(cx.theme().colors().border_variant)
386                .absolute()
387                .right_1()
388                .top_0()
389                .bottom_0()
390                .w_4()
391                .pl_1()
392                .cursor_default()
393                .on_mouse_move(cx.listener(|_, _, _window, cx| {
394                    cx.notify();
395                    cx.stop_propagation()
396                }))
397                .on_hover(|_, _window, cx| {
398                    cx.stop_propagation();
399                })
400                .on_any_mouse_down(|_, _window, cx| {
401                    cx.stop_propagation();
402                })
403                .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
404                    cx.notify();
405                }))
406                .children(Scrollbar::vertical(self.scrollbar_state.clone())),
407        )
408    }
409
410    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
411        if let Some(entry) = self.get_match(self.selected_index) {
412            let task_result = match entry {
413                HistoryEntry::Thread(thread) => self.agent_panel.update(cx, move |this, cx| {
414                    this.open_thread_by_id(&thread.id, window, cx)
415                }),
416                HistoryEntry::Context(context) => self.agent_panel.update(cx, move |this, cx| {
417                    this.open_saved_prompt_editor(context.path.clone(), window, cx)
418                }),
419            };
420
421            if let Some(task) = task_result.log_err() {
422                task.detach_and_log_err(cx);
423            };
424
425            cx.notify();
426        }
427    }
428
429    fn remove_selected_thread(
430        &mut self,
431        _: &RemoveSelectedThread,
432        _window: &mut Window,
433        cx: &mut Context<Self>,
434    ) {
435        if let Some(entry) = self.get_match(self.selected_index) {
436            let task_result = match entry {
437                HistoryEntry::Thread(thread) => self
438                    .agent_panel
439                    .update(cx, |this, cx| this.delete_thread(&thread.id, cx)),
440                HistoryEntry::Context(context) => self
441                    .agent_panel
442                    .update(cx, |this, cx| this.delete_context(context.path.clone(), cx)),
443            };
444
445            if let Some(task) = task_result.log_err() {
446                task.detach_and_log_err(cx);
447            };
448
449            cx.notify();
450        }
451    }
452
453    fn list_items(
454        &mut self,
455        range: Range<usize>,
456        _window: &mut Window,
457        cx: &mut Context<Self>,
458    ) -> Vec<AnyElement> {
459        let range_start = range.start;
460
461        match &self.search_state {
462            SearchState::Empty => self
463                .separated_items
464                .get(range)
465                .iter()
466                .flat_map(|items| {
467                    items
468                        .iter()
469                        .map(|item| self.render_list_item(item.entry_index(), item, vec![], cx))
470                })
471                .collect(),
472            SearchState::Searched { matches, .. } => matches[range]
473                .iter()
474                .enumerate()
475                .map(|(ix, m)| {
476                    self.render_list_item(
477                        Some(range_start + ix),
478                        &ListItemType::Entry {
479                            index: m.candidate_id,
480                            format: EntryTimeFormat::DateAndTime,
481                        },
482                        m.positions.clone(),
483                        cx,
484                    )
485                })
486                .collect(),
487            SearchState::Searching { .. } => {
488                vec![]
489            }
490        }
491    }
492
493    fn render_list_item(
494        &self,
495        list_entry_ix: Option<usize>,
496        item: &ListItemType,
497        highlight_positions: Vec<usize>,
498        cx: &Context<Self>,
499    ) -> AnyElement {
500        match item {
501            ListItemType::Entry { index, format } => match self.all_entries.get(*index) {
502                Some(entry) => h_flex()
503                    .w_full()
504                    .pb_1()
505                    .child(
506                        HistoryEntryElement::new(entry.clone(), self.agent_panel.clone())
507                            .highlight_positions(highlight_positions)
508                            .timestamp_format(*format)
509                            .selected(list_entry_ix == Some(self.selected_index))
510                            .hovered(list_entry_ix == self.hovered_index)
511                            .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
512                                if *is_hovered {
513                                    this.hovered_index = list_entry_ix;
514                                } else if this.hovered_index == list_entry_ix {
515                                    this.hovered_index = None;
516                                }
517
518                                cx.notify();
519                            }))
520                            .into_any_element(),
521                    )
522                    .into_any(),
523                None => Empty.into_any_element(),
524            },
525            ListItemType::BucketSeparator(bucket) => div()
526                .px(DynamicSpacing::Base06.rems(cx))
527                .pt_2()
528                .pb_1()
529                .child(
530                    Label::new(bucket.to_string())
531                        .size(LabelSize::XSmall)
532                        .color(Color::Muted),
533                )
534                .into_any_element(),
535        }
536    }
537}
538
539impl Focusable for ThreadHistory {
540    fn focus_handle(&self, cx: &App) -> FocusHandle {
541        self.search_editor.focus_handle(cx)
542    }
543}
544
545impl Render for ThreadHistory {
546    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
547        v_flex()
548            .key_context("ThreadHistory")
549            .size_full()
550            .on_action(cx.listener(Self::select_previous))
551            .on_action(cx.listener(Self::select_next))
552            .on_action(cx.listener(Self::select_first))
553            .on_action(cx.listener(Self::select_last))
554            .on_action(cx.listener(Self::confirm))
555            .on_action(cx.listener(Self::remove_selected_thread))
556            .when(!self.all_entries.is_empty(), |parent| {
557                parent.child(
558                    h_flex()
559                        .h(px(41.)) // Match the toolbar perfectly
560                        .w_full()
561                        .py_1()
562                        .px_2()
563                        .gap_2()
564                        .justify_between()
565                        .border_b_1()
566                        .border_color(cx.theme().colors().border)
567                        .child(
568                            Icon::new(IconName::MagnifyingGlass)
569                                .color(Color::Muted)
570                                .size(IconSize::Small),
571                        )
572                        .child(self.search_editor.clone()),
573                )
574            })
575            .child({
576                let view = v_flex()
577                    .id("list-container")
578                    .relative()
579                    .overflow_hidden()
580                    .flex_grow();
581
582                if self.all_entries.is_empty() {
583                    view.justify_center()
584                        .child(
585                            h_flex().w_full().justify_center().child(
586                                Label::new("You don't have any past threads yet.")
587                                    .size(LabelSize::Small),
588                            ),
589                        )
590                } else if self.search_produced_no_matches() {
591                    view.justify_center().child(
592                        h_flex().w_full().justify_center().child(
593                            Label::new("No threads match your search.").size(LabelSize::Small),
594                        ),
595                    )
596                } else {
597                    view.pr_5()
598                        .child(
599                            uniform_list(
600                                cx.entity().clone(),
601                                "thread-history",
602                                self.list_item_count(),
603                                Self::list_items,
604                            )
605                            .p_1()
606                            .track_scroll(self.scroll_handle.clone())
607                            .flex_grow(),
608                        )
609                        .when_some(self.render_scrollbar(cx), |div, scrollbar| {
610                            div.child(scrollbar)
611                        })
612                }
613            })
614    }
615}
616
617#[derive(IntoElement)]
618pub struct HistoryEntryElement {
619    entry: HistoryEntry,
620    agent_panel: WeakEntity<AgentPanel>,
621    selected: bool,
622    hovered: bool,
623    highlight_positions: Vec<usize>,
624    timestamp_format: EntryTimeFormat,
625    on_hover: Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>,
626}
627
628impl HistoryEntryElement {
629    pub fn new(entry: HistoryEntry, agent_panel: WeakEntity<AgentPanel>) -> Self {
630        Self {
631            entry,
632            agent_panel,
633            selected: false,
634            hovered: false,
635            highlight_positions: vec![],
636            timestamp_format: EntryTimeFormat::DateAndTime,
637            on_hover: Box::new(|_, _, _| {}),
638        }
639    }
640
641    pub fn selected(mut self, selected: bool) -> Self {
642        self.selected = selected;
643        self
644    }
645
646    pub fn hovered(mut self, hovered: bool) -> Self {
647        self.hovered = hovered;
648        self
649    }
650
651    pub fn highlight_positions(mut self, positions: Vec<usize>) -> Self {
652        self.highlight_positions = positions;
653        self
654    }
655
656    pub fn on_hover(mut self, on_hover: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
657        self.on_hover = Box::new(on_hover);
658        self
659    }
660
661    pub fn timestamp_format(mut self, format: EntryTimeFormat) -> Self {
662        self.timestamp_format = format;
663        self
664    }
665}
666
667impl RenderOnce for HistoryEntryElement {
668    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
669        let (id, summary, timestamp) = match &self.entry {
670            HistoryEntry::Thread(thread) => (
671                thread.id.to_string(),
672                thread.summary.clone(),
673                thread.updated_at.timestamp(),
674            ),
675            HistoryEntry::Context(context) => (
676                context.path.to_string_lossy().to_string(),
677                context.title.clone().into(),
678                context.mtime.timestamp(),
679            ),
680        };
681
682        let thread_timestamp =
683            self.timestamp_format
684                .format_timestamp(&self.agent_panel, timestamp, cx);
685
686        ListItem::new(SharedString::from(id))
687            .rounded()
688            .toggle_state(self.selected)
689            .spacing(ListItemSpacing::Sparse)
690            .start_slot(
691                h_flex()
692                    .w_full()
693                    .gap_2()
694                    .justify_between()
695                    .child(
696                        HighlightedLabel::new(summary, self.highlight_positions)
697                            .size(LabelSize::Small)
698                            .truncate(),
699                    )
700                    .child(
701                        Label::new(thread_timestamp)
702                            .color(Color::Muted)
703                            .size(LabelSize::XSmall),
704                    ),
705            )
706            .on_hover(self.on_hover)
707            .end_slot::<IconButton>(if self.hovered || self.selected {
708                Some(
709                    IconButton::new("delete", IconName::TrashAlt)
710                        .shape(IconButtonShape::Square)
711                        .icon_size(IconSize::XSmall)
712                        .icon_color(Color::Muted)
713                        .tooltip(move |window, cx| {
714                            Tooltip::for_action("Delete", &RemoveSelectedThread, window, cx)
715                        })
716                        .on_click({
717                            let agent_panel = self.agent_panel.clone();
718
719                            let f: Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static> =
720                                match &self.entry {
721                                    HistoryEntry::Thread(thread) => {
722                                        let id = thread.id.clone();
723
724                                        Box::new(move |_event, _window, cx| {
725                                            agent_panel
726                                                .update(cx, |this, cx| {
727                                                    this.delete_thread(&id, cx)
728                                                        .detach_and_log_err(cx);
729                                                })
730                                                .ok();
731                                        })
732                                    }
733                                    HistoryEntry::Context(context) => {
734                                        let path = context.path.clone();
735
736                                        Box::new(move |_event, _window, cx| {
737                                            agent_panel
738                                                .update(cx, |this, cx| {
739                                                    this.delete_context(path.clone(), cx)
740                                                        .detach_and_log_err(cx);
741                                                })
742                                                .ok();
743                                        })
744                                    }
745                                };
746                            f
747                        }),
748                )
749            } else {
750                None
751            })
752            .on_click({
753                let agent_panel = self.agent_panel.clone();
754
755                let f: Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static> = match &self.entry
756                {
757                    HistoryEntry::Thread(thread) => {
758                        let id = thread.id.clone();
759                        Box::new(move |_event, window, cx| {
760                            agent_panel
761                                .update(cx, |this, cx| {
762                                    this.open_thread_by_id(&id, window, cx)
763                                        .detach_and_log_err(cx);
764                                })
765                                .ok();
766                        })
767                    }
768                    HistoryEntry::Context(context) => {
769                        let path = context.path.clone();
770                        Box::new(move |_event, window, cx| {
771                            agent_panel
772                                .update(cx, |this, cx| {
773                                    this.open_saved_prompt_editor(path.clone(), window, cx)
774                                        .detach_and_log_err(cx);
775                                })
776                                .ok();
777                        })
778                    }
779                };
780                f
781            })
782    }
783}
784
785#[derive(Clone, Copy)]
786pub enum EntryTimeFormat {
787    DateAndTime,
788    TimeOnly,
789}
790
791impl EntryTimeFormat {
792    fn format_timestamp(
793        &self,
794        agent_panel: &WeakEntity<AgentPanel>,
795        timestamp: i64,
796        cx: &App,
797    ) -> String {
798        let timestamp = OffsetDateTime::from_unix_timestamp(timestamp).unwrap();
799        let timezone = agent_panel
800            .read_with(cx, |this, _cx| this.local_timezone())
801            .unwrap_or(UtcOffset::UTC);
802
803        match &self {
804            EntryTimeFormat::DateAndTime => time_format::format_localized_timestamp(
805                timestamp,
806                OffsetDateTime::now_utc(),
807                timezone,
808                time_format::TimestampFormat::EnhancedAbsolute,
809            ),
810            EntryTimeFormat::TimeOnly => time_format::format_time(timestamp),
811        }
812    }
813}
814
815impl From<TimeBucket> for EntryTimeFormat {
816    fn from(bucket: TimeBucket) -> Self {
817        match bucket {
818            TimeBucket::Today => EntryTimeFormat::TimeOnly,
819            TimeBucket::Yesterday => EntryTimeFormat::TimeOnly,
820            TimeBucket::ThisWeek => EntryTimeFormat::DateAndTime,
821            TimeBucket::PastWeek => EntryTimeFormat::DateAndTime,
822            TimeBucket::All => EntryTimeFormat::DateAndTime,
823        }
824    }
825}
826
827#[derive(PartialEq, Eq, Clone, Copy, Debug)]
828enum TimeBucket {
829    Today,
830    Yesterday,
831    ThisWeek,
832    PastWeek,
833    All,
834}
835
836impl TimeBucket {
837    fn from_dates(reference: NaiveDate, date: NaiveDate) -> Self {
838        if date == reference {
839            return TimeBucket::Today;
840        }
841
842        if date == reference - TimeDelta::days(1) {
843            return TimeBucket::Yesterday;
844        }
845
846        let week = date.iso_week();
847
848        if reference.iso_week() == week {
849            return TimeBucket::ThisWeek;
850        }
851
852        let last_week = (reference - TimeDelta::days(7)).iso_week();
853
854        if week == last_week {
855            return TimeBucket::PastWeek;
856        }
857
858        TimeBucket::All
859    }
860}
861
862impl Display for TimeBucket {
863    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
864        match self {
865            TimeBucket::Today => write!(f, "Today"),
866            TimeBucket::Yesterday => write!(f, "Yesterday"),
867            TimeBucket::ThisWeek => write!(f, "This Week"),
868            TimeBucket::PastWeek => write!(f, "Past Week"),
869            TimeBucket::All => write!(f, "All"),
870        }
871    }
872}
873
874#[cfg(test)]
875mod tests {
876    use super::*;
877    use chrono::NaiveDate;
878
879    #[test]
880    fn test_time_bucket_from_dates() {
881        let today = NaiveDate::from_ymd_opt(2023, 1, 15).unwrap();
882
883        let date = today;
884        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::Today);
885
886        let date = NaiveDate::from_ymd_opt(2023, 1, 14).unwrap();
887        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::Yesterday);
888
889        let date = NaiveDate::from_ymd_opt(2023, 1, 13).unwrap();
890        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::ThisWeek);
891
892        let date = NaiveDate::from_ymd_opt(2023, 1, 11).unwrap();
893        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::ThisWeek);
894
895        let date = NaiveDate::from_ymd_opt(2023, 1, 8).unwrap();
896        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::PastWeek);
897
898        let date = NaiveDate::from_ymd_opt(2023, 1, 5).unwrap();
899        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::PastWeek);
900
901        // All: not in this week or last week
902        let date = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap();
903        assert_eq!(TimeBucket::from_dates(today, date), TimeBucket::All);
904
905        // Test year boundary cases
906        let new_year = NaiveDate::from_ymd_opt(2023, 1, 1).unwrap();
907
908        let date = NaiveDate::from_ymd_opt(2022, 12, 31).unwrap();
909        assert_eq!(
910            TimeBucket::from_dates(new_year, date),
911            TimeBucket::Yesterday
912        );
913
914        let date = NaiveDate::from_ymd_opt(2022, 12, 28).unwrap();
915        assert_eq!(TimeBucket::from_dates(new_year, date), TimeBucket::ThisWeek);
916    }
917}