Skip to main content

chatty_rs/models/
event.rs

1use std::sync::Arc;
2
3use tokio::sync::mpsc;
4use tui_textarea::Input;
5
6use super::Conversation;
7
8#[derive(Debug)]
9pub enum Event {
10    Notice(crate::models::NoticeMessage),
11
12    BackendAbort,
13    BackendMessage(crate::models::Message),
14    ChatCompletionResponse(crate::models::BackendResponse),
15
16    SetConversation(Option<Conversation>),
17    ConversationDeleted(String),
18    ConversationUpdated(Conversation),
19
20    KeyboardCharInput(Input),
21    KeyboardEsc,
22    KeyboardEnter,
23    KeyboardAltEnter,
24    KeyboardCtrlC,
25    KeyboardCtrlR,
26    KeyboardCtrlN,
27    KeyboardCtrlE,
28    KeyboardCtrlL,
29    KeyboardCtrlH,
30    KeyboardF1,
31    KeyboardPaste(String),
32
33    Quit,
34
35    UiTick,
36    UiScrollUp,
37    UiScrollDown,
38    UiScrollPageUp,
39    UiScrollPageDown,
40}
41
42#[macro_export]
43macro_rules! info_event {
44    ($($arg:tt)*) => {
45        Event::Notice($crate::info_notice!($($arg)*))
46    }
47}
48
49#[macro_export]
50macro_rules! warn_event {
51    ($($arg:tt)*) => {
52        Event::Notice($crate::warn_notice!($($arg)*))
53    }
54}
55
56#[macro_export]
57macro_rules! error_event {
58    ($($arg:tt)*) => {
59        Event::Notice($crate::error_notice!($($arg)*))
60    }
61}
62
63#[async_trait::async_trait]
64pub trait EventTx {
65    async fn send(&self, event: Event) -> Result<(), mpsc::error::SendError<Event>>;
66}
67
68impl Event {
69    pub fn is_keyboard_event(&self) -> bool {
70        matches!(
71            self,
72            Event::KeyboardCharInput(_)
73                | Event::KeyboardEsc
74                | Event::KeyboardEnter
75                | Event::KeyboardAltEnter
76                | Event::KeyboardCtrlC
77                | Event::KeyboardCtrlR
78                | Event::KeyboardCtrlN
79                | Event::KeyboardCtrlE
80                | Event::KeyboardCtrlL
81                | Event::KeyboardCtrlH
82                | Event::KeyboardF1
83                | Event::Quit
84                | Event::UiScrollUp
85                | Event::UiScrollDown
86                | Event::UiScrollPageUp
87                | Event::UiScrollPageDown
88                | Event::KeyboardPaste(_)
89        )
90    }
91}
92
93#[async_trait::async_trait]
94impl EventTx for mpsc::Sender<Event> {
95    async fn send(&self, event: Event) -> Result<(), mpsc::error::SendError<Event>> {
96        self.send(event).await
97    }
98}
99
100#[async_trait::async_trait]
101impl EventTx for mpsc::UnboundedSender<Event> {
102    async fn send(&self, event: Event) -> Result<(), mpsc::error::SendError<Event>> {
103        self.send(event)
104    }
105}
106
107pub type ArcEventTx = Arc<dyn EventTx + Send + Sync>;