leetcode_tui_core/content/
topic.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use crate::emit;
use crate::utils::Paginate;
use leetcode_tui_db::DbTopic;
use leetcode_tui_shared::layout::Window;

pub struct Topic {
    paginate: Paginate<DbTopic>,
}

impl<'a> Topic {
    pub(crate) async fn new() -> Self {
        let mut topics = vec![DbTopic::new("all")];
        topics.extend(DbTopic::fetch_all().unwrap());
        let s = Self {
            paginate: Paginate::new(topics),
        };
        s.notify_change();
        s
    }

    pub fn next_topic(&mut self) -> bool {
        let has_topic_changed = self.paginate.next_elem(self.widget_height());
        if has_topic_changed {
            self.notify_change();
        }
        has_topic_changed
    }

    pub fn notify_change(&self) {
        if let Some(hovered) = self.hovered() {
            emit!(Topic(hovered.clone()));
        }
    }

    pub fn prev_topic(&mut self) -> bool {
        let has_topic_changed = self.paginate.prev_elem(self.widget_height());
        if has_topic_changed {
            self.notify_change()
        };
        has_topic_changed
    }

    pub fn window(&self) -> &[DbTopic] {
        self.paginate.window(self.widget_height())
    }

    fn widget_height(&self) -> usize {
        let window = Window::default();
        let height = window.root.center_layout.topic.inner.height;
        height as usize
    }
}

impl Topic {
    pub fn hovered(&self) -> Option<&DbTopic> {
        self.paginate.hovered()
    }
}