-
Notifications
You must be signed in to change notification settings - Fork 17
/
chat_window.rs
328 lines (306 loc) · 11.5 KB
/
chat_window.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
use crate::{
action::Action,
app_context::AppContext,
components::component_traits::{Component, HandleFocus},
event::Event,
tg::message_entry::MessageEntry,
};
use arboard::Clipboard;
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
symbols::{
border::{self, Set},
line,
},
text::{Line, Span},
widgets::{Block, Borders, List, ListDirection, ListItem, ListState, Paragraph},
};
use std::sync::Arc;
use tokio::sync::mpsc::UnboundedSender;
/// `ChatWindow` is a struct that represents a window for displaying a chat.
/// It is responsible for managing the layout and rendering of the chat window.
pub struct ChatWindow {
/// The application context.
app_context: Arc<AppContext>,
/// The name of the `ChatWindow`.
name: String,
/// An unbounded sender that send action for processing.
action_tx: Option<UnboundedSender<Action>>,
/// A list of message items to be displayed in the `ChatWindow`.
message_list: Vec<MessageEntry>,
/// The state of the list.
message_list_state: ListState,
/// Indicates whether the `ChatWindow` is focused or not.
focused: bool,
}
/// Implementation of the `ChatWindow` struct.
impl ChatWindow {
/// Create a new instance of the `ChatWindow` struct.
///
/// # Arguments
/// * `app_context` - An Arc wrapped AppContext struct.
///
/// # Returns
/// * `Self` - The new instance of the `ChatWindow` struct.
pub fn new(app_context: Arc<AppContext>) -> Self {
let name = "".to_string();
let action_tx = None;
let message_list = vec![];
let message_list_state = ListState::default();
let focused = false;
ChatWindow {
app_context,
name,
action_tx,
message_list,
message_list_state,
focused,
}
}
/// Set the name of the `ChatWindow`.
///
/// # Arguments
/// * `name` - The name of the `ChatWindow`.
///
/// # Returns
/// * `Self` - The modified instance of the `ChatWindow`.
pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
self.name = name.as_ref().to_string();
self
}
/// Select the next message item in the list.
fn next(&mut self) {
let i = match self.message_list_state.selected() {
Some(i) => {
if i == self.message_list.len() / 2 {
if let Some(event_tx) = self.app_context.tg_context().event_tx().as_ref() {
event_tx.send(Event::GetChatHistory).unwrap();
}
}
if i == 0 {
0
} else {
i - 1
}
}
None => 0,
};
self.message_list_state.select(Some(i));
}
/// Select the previous message item in the list.
fn previous(&mut self) {
let i = match self.message_list_state.selected() {
Some(i) => {
if i == self.message_list.len() / 2 {
if let Some(event_tx) = self.app_context.tg_context().event_tx().as_ref() {
event_tx.send(Event::GetChatHistory).unwrap();
}
}
if i >= self.message_list.len() - 1 {
i
} else {
i + 1
}
}
None => 0,
};
self.message_list_state.select(Some(i));
}
/// Unselect the message item in the list.
fn unselect(&mut self) {
self.message_list_state.select(None);
}
/// Delete the selected message item in the list.
///
/// # Arguments
/// * `revoke` - A boolean flag indicating whether the message should be revoked or not.
fn delete_selected(&mut self, revoke: bool) {
if let Some(selected) = self.message_list_state.selected() {
if let Some(event_tx) = self.app_context.tg_context().event_tx().as_ref() {
let sender_id = self.message_list[selected].sender_id();
if sender_id != self.app_context.tg_context().me() {
return;
}
let message_id = self.message_list[selected].id();
event_tx
.send(Event::DeleteMessages(vec![message_id], revoke))
.unwrap();
self.app_context.tg_context().delete_message(message_id);
}
}
}
/// Copy the selected message item in the list.
fn copy_selected(&self) {
if let Some(selected) = self.message_list_state.selected() {
let message = self.message_list[selected].message_content_to_string();
if let Ok(mut clipboard) = Clipboard::new() {
clipboard.set_text(message).unwrap();
}
}
}
/// Edit the selected message item in the list.
fn edit_selected(&self) {
if let Some(selected) = self.message_list_state.selected() {
let sender_id = self.message_list[selected].sender_id();
if sender_id != self.app_context.tg_context().me() {
return;
}
let message = self.message_list[selected].message_content_to_string();
let message_id = self.message_list[selected].id();
if let Some(event_tx) = self.app_context.tg_context().event_tx().as_ref() {
event_tx
.send(Event::EditMessage(message_id, message))
.unwrap();
}
}
}
/// Reply to the selected message item in the list.
fn reply_selected(&self) {
if let Some(selected) = self.message_list_state.selected() {
let message_id = self.message_list[selected].id();
let text = self.message_list[selected].message_content_to_string();
if let Some(event_tx) = self.app_context.tg_context().event_tx().as_ref() {
event_tx
.send(Event::ReplyMessage(message_id, text))
.unwrap();
}
}
}
}
/// Implement the `HandleFocus` trait for the `ChatWindow` struct.
/// This trait allows the `ChatListWindow` to be focused or unfocused.
impl HandleFocus for ChatWindow {
/// Set the `focused` flag for the `ChatWindow`.
fn focus(&mut self) {
self.focused = true;
}
/// Set the `focused` flag for the `ChatWindow`.
fn unfocus(&mut self) {
self.focused = false;
}
}
/// Implement the `Component` trait for the `ChatListWindow` struct.
impl Component for ChatWindow {
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> std::io::Result<()> {
self.action_tx = Some(tx);
Ok(())
}
fn update(&mut self, action: Action) {
match action {
Action::ChatWindowNext => self.next(),
Action::ChatWindowPrevious => self.previous(),
Action::ChatWindowUnselect => self.unselect(),
Action::ChatWindowDeleteForEveryone => self.delete_selected(true),
Action::ChatWindowDeleteForMe => self.delete_selected(false),
Action::ChatWindowCopy => self.copy_selected(),
Action::ChatWindowEdit => self.edit_selected(),
Action::ShowChatWindowReply => self.reply_selected(),
_ => {}
}
}
fn draw(&mut self, frame: &mut ratatui::Frame<'_>, area: Rect) -> std::io::Result<()> {
if !self.focused {
self.message_list_state.select(None);
}
self.message_list
.clone_from(&self.app_context.tg_context().open_chat_messages());
let chat_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(2), Constraint::Percentage(100)])
.split(area);
let border = Set {
top_left: line::NORMAL.vertical_right,
top_right: line::NORMAL.vertical_left,
bottom_left: line::NORMAL.horizontal_up,
..border::PLAIN
};
let style_border_focused = if self.focused {
self.app_context.style_border_component_focused()
} else {
self.app_context.style_chat()
};
let mut is_unread_outbox = true;
let mut is_unread_inbox = true;
let wrap_width = (area.width / 2) as i32;
let items = self.message_list.iter().map(|message_entry| {
let (myself, name_style, content_style, alignment) = if message_entry.sender_id()
== self.app_context.tg_context().me()
{
if message_entry.id() == self.app_context.tg_context().last_read_outbox_message_id()
{
is_unread_outbox = false;
}
(
true,
self.app_context.style_chat_message_myself_name(),
self.app_context.style_chat_message_myself_content(),
Alignment::Right,
)
} else {
if message_entry.id() == self.app_context.tg_context().last_read_inbox_message_id()
{
is_unread_inbox = false;
}
(
false,
self.app_context.style_chat_message_other_name(),
self.app_context.style_chat_message_other_content(),
Alignment::Left,
)
};
ListItem::new(
message_entry
.get_text_styled(
myself,
&self.app_context,
is_unread_outbox,
name_style,
content_style,
wrap_width,
)
.alignment(alignment),
)
});
let block = Block::new()
.border_set(border)
.border_style(style_border_focused)
.borders(Borders::TOP | Borders::LEFT | Borders::RIGHT)
.style(self.app_context.style_chat());
let list = List::new(items)
.block(block)
.style(self.app_context.style_chat())
.highlight_style(self.app_context.style_item_selected())
.repeat_highlight_symbol(true)
.direction(ListDirection::BottomToTop);
let border_header = Set {
top_left: line::NORMAL.horizontal_down,
bottom_left: line::NORMAL.horizontal_up,
..border::PLAIN
};
let block_header = Block::new()
.border_set(border_header)
.border_style(style_border_focused)
.borders(Borders::TOP | Borders::LEFT | Borders::RIGHT)
.style(self.app_context.style_chat())
.title(self.name.as_str());
let header = Paragraph::new(Line::from(vec![
Span::styled(
self.app_context
.tg_context()
.name_of_open_chat_id()
.unwrap_or_default(),
self.app_context.style_chat_chat_name(),
),
Span::raw(" "),
Span::styled(
self.app_context.tg_context().open_chat_user_status(),
self.app_context.style_timestamp(),
),
]))
.block(block_header)
.alignment(Alignment::Center);
frame.render_widget(header, chat_layout[0]);
frame.render_stateful_widget(list, chat_layout[1], &mut self.message_list_state);
Ok(())
}
}