Skip to main content

wiki_tui/components/
mod.rs

1use std::sync::Arc;
2
3use anyhow::Result;
4use crossterm::event::KeyEvent;
5use ratatui::prelude::Rect;
6use tokio::sync::mpsc;
7
8use crate::{
9    action::{Action, ActionResult},
10    config::{Config, Theme},
11    event::Event,
12    terminal::Frame,
13};
14
15pub mod help_popup;
16pub mod logger;
17pub mod message_popup;
18pub mod page;
19pub mod page_language_popup;
20pub mod page_viewer;
21pub mod search;
22pub mod search_bar;
23pub mod search_language_popup;
24
25#[macro_export]
26macro_rules! key_event {
27    (Key::$key: ident, Modifier::$modifier: ident) => {
28        crossterm::event::KeyEvent::new(
29            crossterm::event::KeyCode::$key,
30            crossterm::event::KeyModifiers::$modifier,
31        )
32    };
33    (Key::$key: ident) => {
34        key_event!(Key::$key, Modifier::NONE)
35    };
36    ($char: expr, Modifier::$modifier: ident) => {
37        crossterm::event::KeyEvent::new(
38            crossterm::event::KeyCode::Char($char),
39            crossterm::event::KeyModifiers::$modifier,
40        )
41    };
42    ($char: expr) => {
43        key_event!($char, Modifier::NONE)
44    };
45}
46
47pub trait Component {
48    // TODO: use custom error type
49    #[allow(unused_variables)]
50    fn init(
51        &mut self,
52        action_tx: mpsc::UnboundedSender<Action>,
53        config: Arc<Config>,
54        theme: Arc<Theme>,
55    ) -> Result<()> {
56        Ok(())
57    }
58
59    #[allow(unused_variables)]
60    fn handle_events(&mut self, event: Option<Event>) -> ActionResult {
61        match event {
62            Some(Event::Quit) => Action::Quit.into(),
63            Some(Event::RenderTick) => Action::RenderTick.into(),
64            Some(Event::Key(key_event)) => self.handle_key_events(key_event),
65            Some(Event::Resize(x, y)) => Action::Resize(x, y).into(),
66            None => ActionResult::Ignored,
67        }
68    }
69
70    #[allow(unused_variables)]
71    fn handle_key_events(&mut self, key: KeyEvent) -> ActionResult {
72        ActionResult::Ignored
73    }
74
75    #[allow(unused_variables)]
76    fn update(&mut self, action: Action) -> ActionResult {
77        ActionResult::Ignored
78    }
79
80    fn render(&mut self, f: &mut Frame<'_>, area: Rect);
81}