leetcode_tui_core/content/
topic.rs1use crate::emit;
2use crate::utils::Paginate;
3use leetcode_tui_db::DbTopic;
4use leetcode_tui_shared::layout::Window;
5
6pub struct Topic {
7 paginate: Paginate<DbTopic>,
8 topics: Vec<DbTopic>,
9}
10
11impl<'a> Topic {
12 pub(crate) async fn new() -> Self {
13 let mut topics = vec![DbTopic::new("all")];
14 topics.extend(DbTopic::fetch_all().unwrap());
15 let s = Self {
16 paginate: Paginate::new(topics.clone()),
17 topics,
18 };
19 s.notify_change();
20 s
21 }
22
23 pub fn next_topic(&mut self) -> bool {
24 let has_topic_changed = self.paginate.next_elem(self.widget_height());
25 if has_topic_changed {
26 self.notify_change();
27 }
28 has_topic_changed
29 }
30
31 pub fn notify_change(&self) {
32 if let Some(hovered) = self.hovered() {
33 emit!(Topic(hovered.clone()));
34 }
35 }
36
37 pub fn prev_topic(&mut self) -> bool {
38 let has_topic_changed = self.paginate.prev_elem(self.widget_height());
39 if has_topic_changed {
40 self.notify_change()
41 };
42 has_topic_changed
43 }
44
45 pub fn set_topic(&mut self, topic: &DbTopic) -> bool {
46 if let Some(id) = self.topics.iter().position(|x| x.slug == topic.slug) {
47 self.paginate.set_element_by_index(id, self.widget_height());
48 }
49 return true;
50 }
51
52 pub fn window(&self) -> &[DbTopic] {
53 self.paginate.window(self.widget_height())
54 }
55
56 fn widget_height(&self) -> usize {
57 let window = Window::default();
58 let height = window.root.center_layout.topic.inner.height;
59 height as usize
60 }
61}
62
63impl Topic {
64 pub fn hovered(&self) -> Option<&DbTopic> {
65 self.paginate.hovered()
66 }
67}