src/windows/mod.rs
1694 lines · 51691 bytes
1//! # Windows for the User Interface
2//!
3//! This module contains the logic for rendering windows, and handling UI actions that get
4//! delegated to individual windows/UI elements (e.g., typing text or selecting a list item).
5//!
6//! Additionally, some of the iamb commands delegate behaviour to the current UI element. For
7//! example, [sending messages][crate::base::SendAction] delegate to the [room window][RoomState],
8//! where we have the message bar and room ID easily accesible and resetable.
9use std::cmp::{Ord, Ordering, PartialOrd};
10use std::fmt::{self, Display};
11use std::ops::Deref;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use matrix_sdk::{
16 encryption::verification::{format_emojis, SasVerification},
17 room::{Room as MatrixRoom, RoomMember},
18 ruma::{
19 events::room::member::MembershipState,
20 events::tag::{TagName, Tags},
21 OwnedRoomAliasId,
22 OwnedRoomId,
23 RoomAliasId,
24 RoomId,
25 },
26};
27
28use ratatui::{
29 buffer::Buffer,
30 layout::{Alignment, Rect},
31 style::{Modifier as StyleModifier, Style},
32 text::{Line, Span, Text},
33 widgets::StatefulWidget,
34};
35
36use modalkit::{
37 actions::{
38 Action,
39 Editable,
40 EditorAction,
41 Jumpable,
42 PromptAction,
43 Promptable,
44 Scrollable,
45 WindowAction,
46 },
47 editing::completion::CompletionList,
48 errors::{EditError, EditResult, UIError},
49 prelude::*,
50};
51
52use modalkit_ratatui::{
53 list::{List, ListCursor, ListItem, ListState},
54 TermOffset,
55 TerminalCursor,
56 Window,
57 WindowOps,
58};
59
60use crate::base::{
61 ChatStore,
62 IambBufferId,
63 IambError,
64 IambId,
65 IambInfo,
66 IambResult,
67 MessageAction,
68 Need,
69 ProgramAction,
70 ProgramContext,
71 ProgramStore,
72 RoomAction,
73 SendAction,
74 SortColumn,
75 SortFieldRoom,
76 SortFieldUser,
77 SortOrder,
78 UnreadInfo,
79};
80
81use self::{room::RoomState, welcome::WelcomeState};
82use crate::message::MessageTimeStamp;
83
84pub mod room;
85pub mod welcome;
86
87type MatrixRoomInfo = Arc<(MatrixRoom, Option<Tags>)>;
88
89const MEMBER_FETCH_DEBOUNCE: Duration = Duration::from_secs(5);
90
91#[inline]
92fn bold_style() -> Style {
93 Style::default().add_modifier(StyleModifier::BOLD)
94}
95
96#[inline]
97fn bold_span(s: &str) -> Span {
98 Span::styled(s, bold_style())
99}
100
101#[inline]
102fn bold_spans(s: &str) -> Line {
103 bold_span(s).into()
104}
105
106#[inline]
107fn selected_style(selected: bool) -> Style {
108 if selected {
109 Style::default().add_modifier(StyleModifier::REVERSED)
110 } else {
111 Style::default()
112 }
113}
114
115#[inline]
116fn selected_span(s: &str, selected: bool) -> Span {
117 Span::styled(s, selected_style(selected))
118}
119
120#[inline]
121fn selected_text(s: &str, selected: bool) -> Text {
122 Text::from(selected_span(s, selected))
123}
124
125fn name_and_labels(name: &str, unread: bool, style: Style) -> (Span<'_>, Vec<Vec<Span<'_>>>) {
126 let name_style = if unread {
127 style.add_modifier(StyleModifier::BOLD)
128 } else {
129 style
130 };
131
132 let name = Span::styled(name, name_style);
133 let labels = if unread {
134 vec![vec![Span::styled("Unread", style)]]
135 } else {
136 vec![]
137 };
138
139 (name, labels)
140}
141
142/// Sort `Some` to be less than `None` so that list items with values come before those without.
143#[inline]
144fn some_cmp<T, F>(a: Option<T>, b: Option<T>, f: F) -> Ordering
145where
146 F: Fn(&T, &T) -> Ordering,
147{
148 match (a, b) {
149 (Some(a), Some(b)) => f(&a, &b),
150 (None, None) => Ordering::Equal,
151 (None, Some(_)) => Ordering::Greater,
152 (Some(_), None) => Ordering::Less,
153 }
154}
155
156fn user_cmp(a: &MemberItem, b: &MemberItem, field: &SortFieldUser) -> Ordering {
157 let a_id = a.member.user_id();
158 let b_id = b.member.user_id();
159
160 match field {
161 SortFieldUser::UserId => a_id.cmp(b_id),
162 SortFieldUser::LocalPart => a_id.localpart().cmp(b_id.localpart()),
163 SortFieldUser::Server => a_id.server_name().cmp(b_id.server_name()),
164 SortFieldUser::PowerLevel => {
165 // Sort higher power levels towards the top of the list.
166 b.member.power_level().cmp(&a.member.power_level())
167 },
168 }
169}
170
171fn room_cmp<T: RoomLikeItem>(a: &T, b: &T, field: &SortFieldRoom) -> Ordering {
172 match field {
173 SortFieldRoom::Favorite => {
174 let fava = a.has_tag(TagName::Favorite);
175 let favb = b.has_tag(TagName::Favorite);
176
177 // If a has Favorite and b doesn't, it should sort earlier in room list.
178 favb.cmp(&fava)
179 },
180 SortFieldRoom::LowPriority => {
181 let lowa = a.has_tag(TagName::LowPriority);
182 let lowb = b.has_tag(TagName::LowPriority);
183
184 // If a has LowPriority and b doesn't, it should sort later in room list.
185 lowa.cmp(&lowb)
186 },
187 SortFieldRoom::Name => a.name().cmp(b.name()),
188 SortFieldRoom::Alias => some_cmp(a.alias(), b.alias(), Ord::cmp),
189 SortFieldRoom::RoomId => a.room_id().cmp(b.room_id()),
190 SortFieldRoom::Unread => {
191 // Sort true (unread) before false (read)
192 b.is_unread().cmp(&a.is_unread())
193 },
194 SortFieldRoom::Recent => {
195 // sort larger timestamps towards the top.
196 some_cmp(a.recent_ts(), b.recent_ts(), |a, b| b.cmp(a))
197 },
198 }
199}
200
201/// Compare two rooms according the configured sort criteria.
202fn room_fields_cmp<T: RoomLikeItem>(
203 a: &T,
204 b: &T,
205 fields: &[SortColumn<SortFieldRoom>],
206) -> Ordering {
207 for SortColumn(field, order) in fields {
208 match (room_cmp(a, b, field), order) {
209 (Ordering::Equal, _) => continue,
210 (o, SortOrder::Ascending) => return o,
211 (o, SortOrder::Descending) => return o.reverse(),
212 }
213 }
214
215 // Break ties on ascending room id.
216 room_cmp(a, b, &SortFieldRoom::RoomId)
217}
218
219fn user_fields_cmp(
220 a: &MemberItem,
221 b: &MemberItem,
222 fields: &[SortColumn<SortFieldUser>],
223) -> Ordering {
224 for SortColumn(field, order) in fields {
225 match (user_cmp(a, b, field), order) {
226 (Ordering::Equal, _) => continue,
227 (o, SortOrder::Ascending) => return o,
228 (o, SortOrder::Descending) => return o.reverse(),
229 }
230 }
231
232 // Break ties on ascending user id.
233 user_cmp(a, b, &SortFieldUser::UserId)
234}
235
236fn tag_to_span(tag: &TagName, style: Style) -> Vec<Span<'_>> {
237 match tag {
238 TagName::Favorite => vec![Span::styled("Favorite", style)],
239 TagName::LowPriority => vec![Span::styled("Low Priority", style)],
240 TagName::ServerNotice => vec![Span::styled("Server Notice", style)],
241 TagName::User(tag) => {
242 vec![
243 Span::styled("User Tag: ", style),
244 Span::styled(tag.as_ref(), style),
245 ]
246 },
247 tag => vec![Span::styled(format!("{tag:?}"), style)],
248 }
249}
250
251fn append_tags<'a>(tags: Vec<Vec<Span<'a>>>, spans: &mut Vec<Span<'a>>, style: Style) {
252 if tags.is_empty() {
253 return;
254 }
255
256 spans.push(Span::styled(" (", style));
257
258 for (i, tag) in tags.into_iter().enumerate() {
259 if i > 0 {
260 spans.push(Span::styled(", ", style));
261 }
262
263 spans.extend(tag);
264 }
265
266 spans.push(Span::styled(")", style));
267}
268
269trait RoomLikeItem {
270 fn room_id(&self) -> &RoomId;
271 fn has_tag(&self, tag: TagName) -> bool;
272 fn is_unread(&self) -> bool;
273 fn recent_ts(&self) -> Option<&MessageTimeStamp>;
274 fn alias(&self) -> Option<&RoomAliasId>;
275 fn name(&self) -> &str;
276}
277
278#[inline]
279fn room_prompt(
280 room_id: &RoomId,
281 act: &PromptAction,
282 ctx: &ProgramContext,
283) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
284 match act {
285 PromptAction::Submit => {
286 let room = IambId::Room(room_id.to_owned(), None);
287 let open = WindowAction::Switch(OpenTarget::Application(room));
288 let acts = vec![(open.into(), ctx.clone())];
289
290 Ok(acts)
291 },
292 PromptAction::Abort(_) => {
293 let msg = "Cannot abort entry inside a list";
294 let err = EditError::Failure(msg.into());
295
296 Err(err)
297 },
298 PromptAction::Recall(..) => {
299 let msg = "Cannot recall history inside a list";
300 let err = EditError::Failure(msg.into());
301
302 Err(err)
303 },
304 }
305}
306
307macro_rules! delegate {
308 ($s: expr, $id: ident => $e: expr) => {
309 match $s {
310 IambWindow::Room($id) => $e,
311 IambWindow::DirectList($id) => $e,
312 IambWindow::MemberList($id, _, _) => $e,
313 IambWindow::RoomList($id) => $e,
314 IambWindow::SpaceList($id) => $e,
315 IambWindow::VerifyList($id) => $e,
316 IambWindow::Welcome($id) => $e,
317 IambWindow::ChatList($id) => $e,
318 IambWindow::UnreadList($id) => $e,
319 }
320 };
321}
322
323pub enum IambWindow {
324 DirectList(DirectListState),
325 MemberList(MemberListState, OwnedRoomId, Option<Instant>),
326 Room(RoomState),
327 VerifyList(VerifyListState),
328 RoomList(RoomListState),
329 SpaceList(SpaceListState),
330 Welcome(WelcomeState),
331 ChatList(ChatListState),
332 UnreadList(UnreadListState),
333}
334
335impl IambWindow {
336 pub fn focus_toggle(&mut self) {
337 if let IambWindow::Room(w) = self {
338 w.focus_toggle()
339 } else {
340 return;
341 }
342 }
343
344 pub async fn message_command(
345 &mut self,
346 act: MessageAction,
347 ctx: ProgramContext,
348 store: &mut ProgramStore,
349 ) -> IambResult<EditInfo> {
350 if let IambWindow::Room(w) = self {
351 w.message_command(act, ctx, store).await
352 } else {
353 return Err(IambError::NoSelectedRoom.into());
354 }
355 }
356
357 pub async fn room_command(
358 &mut self,
359 act: RoomAction,
360 ctx: ProgramContext,
361 store: &mut ProgramStore,
362 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
363 if let IambWindow::Room(w) = self {
364 w.room_command(act, ctx, store).await
365 } else {
366 return Err(IambError::NoSelectedRoomOrSpace.into());
367 }
368 }
369
370 pub async fn send_command(
371 &mut self,
372 act: SendAction,
373 ctx: ProgramContext,
374 store: &mut ProgramStore,
375 ) -> IambResult<EditInfo> {
376 if let IambWindow::Room(w) = self {
377 w.send_command(act, ctx, store).await
378 } else {
379 return Err(IambError::NoSelectedRoom.into());
380 }
381 }
382}
383
384pub type DirectListState = ListState<DirectItem, IambInfo>;
385pub type MemberListState = ListState<MemberItem, IambInfo>;
386pub type RoomListState = ListState<RoomItem, IambInfo>;
387pub type ChatListState = ListState<GenericChatItem, IambInfo>;
388pub type UnreadListState = ListState<GenericChatItem, IambInfo>;
389pub type SpaceListState = ListState<SpaceItem, IambInfo>;
390pub type VerifyListState = ListState<VerifyItem, IambInfo>;
391
392impl From<ChatListState> for IambWindow {
393 fn from(list: ChatListState) -> Self {
394 IambWindow::ChatList(list)
395 }
396}
397
398impl From<RoomState> for IambWindow {
399 fn from(room: RoomState) -> Self {
400 IambWindow::Room(room)
401 }
402}
403
404impl From<VerifyListState> for IambWindow {
405 fn from(list: VerifyListState) -> Self {
406 IambWindow::VerifyList(list)
407 }
408}
409
410impl From<DirectListState> for IambWindow {
411 fn from(list: DirectListState) -> Self {
412 IambWindow::DirectList(list)
413 }
414}
415
416impl From<RoomListState> for IambWindow {
417 fn from(list: RoomListState) -> Self {
418 IambWindow::RoomList(list)
419 }
420}
421
422impl From<SpaceListState> for IambWindow {
423 fn from(list: SpaceListState) -> Self {
424 IambWindow::SpaceList(list)
425 }
426}
427
428impl From<WelcomeState> for IambWindow {
429 fn from(win: WelcomeState) -> Self {
430 IambWindow::Welcome(win)
431 }
432}
433
434impl Editable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
435 fn editor_command(
436 &mut self,
437 act: &EditorAction,
438 ctx: &ProgramContext,
439 store: &mut ProgramStore,
440 ) -> EditResult<EditInfo, IambInfo> {
441 delegate!(self, w => w.editor_command(act, ctx, store))
442 }
443}
444
445impl Jumpable<ProgramContext, IambInfo> for IambWindow {
446 fn jump(
447 &mut self,
448 list: PositionList,
449 dir: MoveDir1D,
450 count: usize,
451 ctx: &ProgramContext,
452 ) -> IambResult<usize> {
453 delegate!(self, w => w.jump(list, dir, count, ctx))
454 }
455}
456
457impl Scrollable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
458 fn scroll(
459 &mut self,
460 style: &ScrollStyle,
461 ctx: &ProgramContext,
462 store: &mut ProgramStore,
463 ) -> EditResult<EditInfo, IambInfo> {
464 delegate!(self, w => w.scroll(style, ctx, store))
465 }
466}
467
468impl Promptable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
469 fn prompt(
470 &mut self,
471 act: &PromptAction,
472 ctx: &ProgramContext,
473 store: &mut ProgramStore,
474 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
475 delegate!(self, w => w.prompt(act, ctx, store))
476 }
477}
478
479impl TerminalCursor for IambWindow {
480 fn get_term_cursor(&self) -> Option<TermOffset> {
481 delegate!(self, w => w.get_term_cursor())
482 }
483}
484
485impl WindowOps<IambInfo> for IambWindow {
486 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
487 match self {
488 IambWindow::Room(state) => state.draw(area, buf, focused, store),
489 IambWindow::DirectList(state) => {
490 let mut items = store
491 .application
492 .sync_info
493 .dms
494 .clone()
495 .into_iter()
496 .map(|room_info| DirectItem::new(room_info, store))
497 .collect::<Vec<_>>();
498 let fields = &store.application.settings.tunables.sort.dms;
499 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
500
501 state.set(items);
502
503 List::new(store)
504 .empty_message("No direct messages yet!")
505 .empty_alignment(Alignment::Center)
506 .focus(focused)
507 .render(area, buf, state);
508 },
509 IambWindow::MemberList(state, room_id, last_fetch) => {
510 let need_fetch = match last_fetch {
511 Some(i) => i.elapsed() >= MEMBER_FETCH_DEBOUNCE,
512 None => true,
513 };
514
515 if need_fetch {
516 if let Ok(mems) = store.application.worker.members(room_id.clone()) {
517 let mut items = mems
518 .into_iter()
519 .map(|m| MemberItem::new(m, room_id.clone()))
520 .collect::<Vec<_>>();
521 let fields = &store.application.settings.tunables.sort.members;
522 items.sort_by(|a, b| user_fields_cmp(a, b, fields));
523 state.set(items);
524 *last_fetch = Some(Instant::now());
525 }
526 }
527
528 List::new(store)
529 .empty_message("No users here yet!")
530 .empty_alignment(Alignment::Center)
531 .focus(focused)
532 .render(area, buf, state);
533 },
534 IambWindow::RoomList(state) => {
535 let mut items = store
536 .application
537 .sync_info
538 .rooms
539 .clone()
540 .into_iter()
541 .map(|room_info| RoomItem::new(room_info, store))
542 .collect::<Vec<_>>();
543 let fields = &store.application.settings.tunables.sort.rooms;
544 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
545
546 state.set(items);
547
548 List::new(store)
549 .empty_message("You haven't joined any rooms yet")
550 .empty_alignment(Alignment::Center)
551 .focus(focused)
552 .render(area, buf, state);
553 },
554 IambWindow::ChatList(state) => {
555 let mut items = store
556 .application
557 .sync_info
558 .rooms
559 .clone()
560 .into_iter()
561 .map(|room_info| GenericChatItem::new(room_info, store, false))
562 .collect::<Vec<_>>();
563
564 let dms = store
565 .application
566 .sync_info
567 .dms
568 .clone()
569 .into_iter()
570 .map(|room_info| GenericChatItem::new(room_info, store, true));
571
572 items.extend(dms);
573
574 let fields = &store.application.settings.tunables.sort.chats;
575 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
576
577 state.set(items);
578
579 List::new(store)
580 .empty_message("You do not have rooms or dms yet")
581 .empty_alignment(Alignment::Center)
582 .focus(focused)
583 .render(area, buf, state);
584 },
585 IambWindow::UnreadList(state) => {
586 let mut items = store
587 .application
588 .sync_info
589 .rooms
590 .clone()
591 .into_iter()
592 .map(|room_info| GenericChatItem::new(room_info, store, false))
593 .filter(RoomLikeItem::is_unread)
594 .collect::<Vec<_>>();
595
596 let dms = store
597 .application
598 .sync_info
599 .dms
600 .clone()
601 .into_iter()
602 .map(|room_info| GenericChatItem::new(room_info, store, true))
603 .filter(RoomLikeItem::is_unread);
604
605 items.extend(dms);
606
607 let fields = &store.application.settings.tunables.sort.chats;
608 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
609
610 state.set(items);
611
612 List::new(store)
613 .empty_message("You do not have rooms or dms yet")
614 .empty_alignment(Alignment::Center)
615 .focus(focused)
616 .render(area, buf, state);
617 },
618 IambWindow::SpaceList(state) => {
619 let mut items = store
620 .application
621 .sync_info
622 .spaces
623 .clone()
624 .into_iter()
625 .map(|room| SpaceItem::new(room, store))
626 .collect::<Vec<_>>();
627 let fields = &store.application.settings.tunables.sort.spaces;
628 items.sort_by(|a, b| room_fields_cmp(a, b, fields));
629
630 state.set(items);
631
632 List::new(store)
633 .empty_message("You haven't joined any spaces yet")
634 .empty_alignment(Alignment::Center)
635 .focus(focused)
636 .render(area, buf, state);
637 },
638 IambWindow::VerifyList(state) => {
639 let verifications = &store.application.verifications;
640 let mut items = verifications.iter().map(VerifyItem::from).collect::<Vec<_>>();
641
642 // Sort the active verifications towards the top.
643 items.sort();
644
645 state.set(items);
646
647 List::new(store)
648 .empty_message("No in-progress verifications")
649 .empty_alignment(Alignment::Center)
650 .focus(focused)
651 .render(area, buf, state);
652 },
653 IambWindow::Welcome(state) => state.draw(area, buf, focused, store),
654 }
655 }
656
657 fn dup(&self, store: &mut ProgramStore) -> Self {
658 match self {
659 IambWindow::Room(w) => w.dup(store).into(),
660 IambWindow::DirectList(w) => w.dup(store).into(),
661 IambWindow::MemberList(w, room_id, last_fetch) => {
662 IambWindow::MemberList(w.dup(store), room_id.clone(), *last_fetch)
663 },
664 IambWindow::RoomList(w) => w.dup(store).into(),
665 IambWindow::SpaceList(w) => w.dup(store).into(),
666 IambWindow::VerifyList(w) => w.dup(store).into(),
667 IambWindow::Welcome(w) => w.dup(store).into(),
668 IambWindow::ChatList(w) => w.dup(store).into(),
669 IambWindow::UnreadList(w) => w.dup(store).into(),
670 }
671 }
672
673 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
674 delegate!(self, w => w.close(flags, store))
675 }
676
677 fn write(
678 &mut self,
679 path: Option<&str>,
680 flags: WriteFlags,
681 store: &mut ProgramStore,
682 ) -> IambResult<EditInfo> {
683 delegate!(self, w => w.write(path, flags, store))
684 }
685
686 fn get_completions(&self) -> Option<CompletionList> {
687 delegate!(self, w => w.get_completions())
688 }
689
690 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
691 delegate!(self, w => w.get_cursor_word(style))
692 }
693
694 fn get_selected_word(&self) -> Option<String> {
695 delegate!(self, w => w.get_selected_word())
696 }
697}
698
699impl Window<IambInfo> for IambWindow {
700 fn id(&self) -> IambId {
701 match self {
702 IambWindow::Room(room) => IambId::Room(room.id().to_owned(), room.thread().cloned()),
703 IambWindow::DirectList(_) => IambId::DirectList,
704 IambWindow::MemberList(_, room_id, _) => IambId::MemberList(room_id.clone()),
705 IambWindow::RoomList(_) => IambId::RoomList,
706 IambWindow::SpaceList(_) => IambId::SpaceList,
707 IambWindow::VerifyList(_) => IambId::VerifyList,
708 IambWindow::Welcome(_) => IambId::Welcome,
709 IambWindow::ChatList(_) => IambId::ChatList,
710 IambWindow::UnreadList(_) => IambId::UnreadList,
711 }
712 }
713
714 fn get_tab_title(&self, store: &mut ProgramStore) -> Line {
715 match self {
716 IambWindow::DirectList(_) => bold_spans("Direct Messages"),
717 IambWindow::RoomList(_) => bold_spans("Rooms"),
718 IambWindow::SpaceList(_) => bold_spans("Spaces"),
719 IambWindow::VerifyList(_) => bold_spans("Verifications"),
720 IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
721 IambWindow::ChatList(_) => bold_spans("DMs & Rooms"),
722 IambWindow::UnreadList(_) => bold_spans("Unread Messages"),
723
724 IambWindow::Room(w) => {
725 let title = store.application.get_room_title(w.id());
726
727 Line::from(title)
728 },
729 IambWindow::MemberList(state, room_id, _) => {
730 let title = store.application.get_room_title(room_id.as_ref());
731 let n = state.len();
732 let v = vec![
733 bold_span("Room Members "),
734 Span::styled(format!("({n}): "), bold_style()),
735 title.into(),
736 ];
737 Line::from(v)
738 },
739 }
740 }
741
742 fn get_win_title(&self, store: &mut ProgramStore) -> Line {
743 match self {
744 IambWindow::DirectList(_) => bold_spans("Direct Messages"),
745 IambWindow::RoomList(_) => bold_spans("Rooms"),
746 IambWindow::SpaceList(_) => bold_spans("Spaces"),
747 IambWindow::VerifyList(_) => bold_spans("Verifications"),
748 IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
749 IambWindow::ChatList(_) => bold_spans("DMs & Rooms"),
750 IambWindow::UnreadList(_) => bold_spans("Unread Messages"),
751
752 IambWindow::Room(w) => w.get_title(store),
753 IambWindow::MemberList(state, room_id, _) => {
754 let title = store.application.get_room_title(room_id.as_ref());
755 let n = state.len();
756 let v = vec![
757 bold_span("Room Members "),
758 Span::styled(format!("({n}): "), bold_style()),
759 title.into(),
760 ];
761 Line::from(v)
762 },
763 }
764 }
765
766 fn open(id: IambId, store: &mut ProgramStore) -> IambResult<Self> {
767 match id {
768 IambId::Room(room_id, thread) => {
769 let (room, name, tags) = store.application.worker.get_room(room_id)?;
770 let room = RoomState::new(room, thread, name, tags, store);
771
772 store.application.need_load.insert(room.id().to_owned(), Need::MEMBERS);
773 return Ok(room.into());
774 },
775 IambId::DirectList => {
776 let list = DirectListState::new(IambBufferId::DirectList, vec![]);
777
778 return Ok(list.into());
779 },
780 IambId::MemberList(room_id) => {
781 let id = IambBufferId::MemberList(room_id.clone());
782 let list = MemberListState::new(id, vec![]);
783 let win = IambWindow::MemberList(list, room_id, None);
784
785 return Ok(win);
786 },
787 IambId::RoomList => {
788 let list = RoomListState::new(IambBufferId::RoomList, vec![]);
789
790 return Ok(list.into());
791 },
792 IambId::SpaceList => {
793 let list = SpaceListState::new(IambBufferId::SpaceList, vec![]);
794
795 return Ok(list.into());
796 },
797 IambId::VerifyList => {
798 let list = VerifyListState::new(IambBufferId::VerifyList, vec![]);
799
800 return Ok(list.into());
801 },
802 IambId::Welcome => {
803 let win = WelcomeState::new(store);
804
805 return Ok(win.into());
806 },
807 IambId::ChatList => {
808 let list = ChatListState::new(IambBufferId::ChatList, vec![]);
809
810 Ok(list.into())
811 },
812 IambId::UnreadList => {
813 let list = UnreadListState::new(IambBufferId::UnreadList, vec![]);
814
815 Ok(IambWindow::UnreadList(list))
816 },
817 }
818 }
819
820 fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
821 let ChatStore { names, worker, .. } = &mut store.application;
822
823 if let Some(room) = names.get_mut(&name) {
824 let id = IambId::Room(room.clone(), None);
825
826 IambWindow::open(id, store)
827 } else {
828 let room_id = worker.join_room(name.clone())?;
829 names.insert(name, room_id.clone());
830
831 let (room, name, tags) = store.application.worker.get_room(room_id)?;
832 let room = RoomState::new(room, None, name, tags, store);
833
834 store.application.need_load.insert(room.id().to_owned(), Need::MEMBERS);
835 Ok(room.into())
836 }
837 }
838
839 fn posn(index: usize, _: &mut ProgramStore) -> IambResult<Self> {
840 let msg = format!("Cannot find indexed buffer (index = {index})");
841 let err = UIError::Unimplemented(msg);
842
843 Err(err)
844 }
845
846 fn unnamed(store: &mut ProgramStore) -> IambResult<Self> {
847 Self::open(IambId::RoomList, store)
848 }
849}
850
851#[derive(Clone)]
852pub struct GenericChatItem {
853 room_info: MatrixRoomInfo,
854 name: String,
855 alias: Option<OwnedRoomAliasId>,
856 unread: UnreadInfo,
857 is_dm: bool,
858}
859
860impl GenericChatItem {
861 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore, is_dm: bool) -> Self {
862 let room = &room_info.deref().0;
863 let room_id = room.room_id();
864
865 let info = store.application.rooms.get_or_default(room_id.to_owned());
866 let name = info.name.clone().unwrap_or_default();
867 let alias = room.canonical_alias();
868 let unread = info.unreads(&store.application.settings);
869 info.tags.clone_from(&room_info.deref().1);
870
871 if let Some(alias) = &alias {
872 store.application.names.insert(alias.to_string(), room_id.to_owned());
873 }
874
875 GenericChatItem { room_info, name, alias, is_dm, unread }
876 }
877
878 #[inline]
879 fn room(&self) -> &MatrixRoom {
880 &self.room_info.deref().0
881 }
882
883 #[inline]
884 fn tags(&self) -> &Option<Tags> {
885 &self.room_info.deref().1
886 }
887}
888
889impl RoomLikeItem for GenericChatItem {
890 fn name(&self) -> &str {
891 self.name.as_str()
892 }
893
894 fn alias(&self) -> Option<&RoomAliasId> {
895 self.alias.as_deref()
896 }
897
898 fn room_id(&self) -> &RoomId {
899 self.room().room_id()
900 }
901
902 fn has_tag(&self, tag: TagName) -> bool {
903 if let Some(tags) = &self.room_info.deref().1 {
904 tags.contains_key(&tag)
905 } else {
906 false
907 }
908 }
909
910 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
911 self.unread.latest()
912 }
913
914 fn is_unread(&self) -> bool {
915 self.unread.is_unread()
916 }
917}
918
919impl Display for GenericChatItem {
920 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
921 write!(f, "{}", self.name)
922 }
923}
924
925impl ListItem<IambInfo> for GenericChatItem {
926 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
927 let unread = self.unread.is_unread();
928 let style = selected_style(selected);
929 let (name, mut labels) = name_and_labels(&self.name, unread, style);
930 let mut spans = vec![name];
931
932 labels.push(if self.is_dm {
933 vec![Span::styled("DM", style)]
934 } else {
935 vec![Span::styled("Room", style)]
936 });
937
938 if let Some(tags) = &self.tags() {
939 labels.extend(tags.keys().map(|t| tag_to_span(t, style)));
940 }
941
942 append_tags(labels, &mut spans, style);
943 Text::from(Line::from(spans))
944 }
945
946 fn get_word(&self) -> Option<String> {
947 self.room_id().to_string().into()
948 }
949}
950
951impl Promptable<ProgramContext, ProgramStore, IambInfo> for GenericChatItem {
952 fn prompt(
953 &mut self,
954 act: &PromptAction,
955 ctx: &ProgramContext,
956 _: &mut ProgramStore,
957 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
958 room_prompt(self.room_id(), act, ctx)
959 }
960}
961
962#[derive(Clone)]
963pub struct RoomItem {
964 room_info: MatrixRoomInfo,
965 name: String,
966 alias: Option<OwnedRoomAliasId>,
967 unread: UnreadInfo,
968}
969
970impl RoomItem {
971 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
972 let room = &room_info.deref().0;
973 let room_id = room.room_id();
974
975 let info = store.application.rooms.get_or_default(room_id.to_owned());
976 let name = info.name.clone().unwrap_or_default();
977 let alias = room.canonical_alias();
978 let unread = info.unreads(&store.application.settings);
979 info.tags.clone_from(&room_info.deref().1);
980
981 if let Some(alias) = &alias {
982 store.application.names.insert(alias.to_string(), room_id.to_owned());
983 }
984
985 RoomItem { room_info, name, alias, unread }
986 }
987
988 #[inline]
989 fn room(&self) -> &MatrixRoom {
990 &self.room_info.deref().0
991 }
992
993 #[inline]
994 fn tags(&self) -> &Option<Tags> {
995 &self.room_info.deref().1
996 }
997}
998
999impl RoomLikeItem for RoomItem {
1000 fn name(&self) -> &str {
1001 self.name.as_str()
1002 }
1003
1004 fn alias(&self) -> Option<&RoomAliasId> {
1005 self.alias.as_deref()
1006 }
1007
1008 fn room_id(&self) -> &RoomId {
1009 self.room().room_id()
1010 }
1011
1012 fn has_tag(&self, tag: TagName) -> bool {
1013 if let Some(tags) = &self.room_info.deref().1 {
1014 tags.contains_key(&tag)
1015 } else {
1016 false
1017 }
1018 }
1019
1020 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1021 self.unread.latest()
1022 }
1023
1024 fn is_unread(&self) -> bool {
1025 self.unread.is_unread()
1026 }
1027}
1028
1029impl Display for RoomItem {
1030 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1031 write!(f, ":verify request {}", self.name)
1032 }
1033}
1034
1035impl ListItem<IambInfo> for RoomItem {
1036 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1037 let unread = self.unread.is_unread();
1038 let style = selected_style(selected);
1039 let (name, mut labels) = name_and_labels(&self.name, unread, style);
1040 let mut spans = vec![name];
1041
1042 if let Some(tags) = &self.tags() {
1043 labels.extend(tags.keys().map(|t| tag_to_span(t, style)));
1044 }
1045
1046 append_tags(labels, &mut spans, style);
1047
1048 Text::from(Line::from(spans))
1049 }
1050
1051 fn get_word(&self) -> Option<String> {
1052 self.room_id().to_string().into()
1053 }
1054}
1055
1056impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomItem {
1057 fn prompt(
1058 &mut self,
1059 act: &PromptAction,
1060 ctx: &ProgramContext,
1061 _: &mut ProgramStore,
1062 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1063 room_prompt(self.room_id(), act, ctx)
1064 }
1065}
1066
1067#[derive(Clone)]
1068pub struct DirectItem {
1069 room_info: MatrixRoomInfo,
1070 name: String,
1071 alias: Option<OwnedRoomAliasId>,
1072 unread: UnreadInfo,
1073}
1074
1075impl DirectItem {
1076 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
1077 let room_id = room_info.0.room_id().to_owned();
1078 let alias = room_info.0.canonical_alias();
1079
1080 let info = store.application.rooms.get_or_default(room_id);
1081 let name = info.name.clone().unwrap_or_default();
1082 let unread = info.unreads(&store.application.settings);
1083 info.tags.clone_from(&room_info.deref().1);
1084
1085 DirectItem { room_info, name, alias, unread }
1086 }
1087
1088 #[inline]
1089 fn room(&self) -> &MatrixRoom {
1090 &self.room_info.deref().0
1091 }
1092
1093 #[inline]
1094 fn tags(&self) -> &Option<Tags> {
1095 &self.room_info.deref().1
1096 }
1097}
1098
1099impl RoomLikeItem for DirectItem {
1100 fn name(&self) -> &str {
1101 self.name.as_str()
1102 }
1103
1104 fn alias(&self) -> Option<&RoomAliasId> {
1105 self.alias.as_deref()
1106 }
1107
1108 fn has_tag(&self, tag: TagName) -> bool {
1109 if let Some(tags) = &self.room_info.deref().1 {
1110 tags.contains_key(&tag)
1111 } else {
1112 false
1113 }
1114 }
1115
1116 fn room_id(&self) -> &RoomId {
1117 self.room().room_id()
1118 }
1119
1120 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1121 self.unread.latest()
1122 }
1123
1124 fn is_unread(&self) -> bool {
1125 self.unread.is_unread()
1126 }
1127}
1128
1129impl Display for DirectItem {
1130 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1131 write!(f, ":verify request {}", self.name)
1132 }
1133}
1134
1135impl ListItem<IambInfo> for DirectItem {
1136 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1137 let unread = self.unread.is_unread();
1138 let style = selected_style(selected);
1139 let (name, mut labels) = name_and_labels(&self.name, unread, style);
1140 let mut spans = vec![name];
1141
1142 if let Some(tags) = &self.tags() {
1143 labels.extend(tags.keys().map(|t| tag_to_span(t, style)));
1144 }
1145
1146 append_tags(labels, &mut spans, style);
1147
1148 Text::from(Line::from(spans))
1149 }
1150
1151 fn get_word(&self) -> Option<String> {
1152 self.room_id().to_string().into()
1153 }
1154}
1155
1156impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
1157 fn prompt(
1158 &mut self,
1159 act: &PromptAction,
1160 ctx: &ProgramContext,
1161 _: &mut ProgramStore,
1162 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1163 room_prompt(self.room_id(), act, ctx)
1164 }
1165}
1166
1167#[derive(Clone)]
1168pub struct SpaceItem {
1169 room_info: MatrixRoomInfo,
1170 name: String,
1171 alias: Option<OwnedRoomAliasId>,
1172}
1173
1174impl SpaceItem {
1175 fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
1176 let room_id = room_info.0.room_id();
1177 let name = store
1178 .application
1179 .get_room_info(room_id.to_owned())
1180 .name
1181 .clone()
1182 .unwrap_or_default();
1183 let alias = room_info.0.canonical_alias();
1184
1185 if let Some(alias) = &alias {
1186 store.application.names.insert(alias.to_string(), room_id.to_owned());
1187 }
1188
1189 SpaceItem { room_info, name, alias }
1190 }
1191
1192 #[inline]
1193 fn room(&self) -> &MatrixRoom {
1194 &self.room_info.deref().0
1195 }
1196}
1197
1198impl RoomLikeItem for SpaceItem {
1199 fn name(&self) -> &str {
1200 self.name.as_str()
1201 }
1202
1203 fn room_id(&self) -> &RoomId {
1204 self.room().room_id()
1205 }
1206
1207 fn alias(&self) -> Option<&RoomAliasId> {
1208 self.alias.as_deref()
1209 }
1210
1211 fn has_tag(&self, _: TagName) -> bool {
1212 // I think that spaces can technically have tags, but afaik no client
1213 // exposes them, so we'll just always return false here for now.
1214 false
1215 }
1216
1217 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1218 // XXX: this needs to determine the room with most recent message and return its timestamp.
1219 None
1220 }
1221
1222 fn is_unread(&self) -> bool {
1223 // XXX: this needs to check whether the space contains rooms with unread messages
1224 false
1225 }
1226}
1227
1228impl Display for SpaceItem {
1229 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1230 write!(f, ":verify request {}", self.room_id())
1231 }
1232}
1233
1234impl ListItem<IambInfo> for SpaceItem {
1235 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1236 selected_text(self.name.as_str(), selected)
1237 }
1238
1239 fn get_word(&self) -> Option<String> {
1240 self.room_id().to_string().into()
1241 }
1242}
1243
1244impl Promptable<ProgramContext, ProgramStore, IambInfo> for SpaceItem {
1245 fn prompt(
1246 &mut self,
1247 act: &PromptAction,
1248 ctx: &ProgramContext,
1249 _: &mut ProgramStore,
1250 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1251 room_prompt(self.room_id(), act, ctx)
1252 }
1253}
1254
1255#[derive(Clone)]
1256pub struct VerifyItem {
1257 user_dev: String,
1258 sasv1: SasVerification,
1259}
1260
1261impl VerifyItem {
1262 fn new(user_dev: String, sasv1: SasVerification) -> Self {
1263 VerifyItem { user_dev, sasv1 }
1264 }
1265
1266 fn show_item(&self) -> String {
1267 let state = if self.sasv1.is_done() {
1268 "done"
1269 } else if self.sasv1.is_cancelled() {
1270 "cancelled"
1271 } else if self.sasv1.emoji().is_some() {
1272 "accepted"
1273 } else {
1274 "not accepted"
1275 };
1276
1277 if self.sasv1.is_self_verification() {
1278 let device = self.sasv1.other_device();
1279
1280 if let Some(display_name) = device.display_name() {
1281 format!("Device verification with {display_name} ({state})")
1282 } else {
1283 format!("Device verification with device {} ({})", device.device_id(), state)
1284 }
1285 } else {
1286 format!("User Verification with {} ({})", self.sasv1.other_user_id(), state)
1287 }
1288 }
1289}
1290
1291impl PartialEq for VerifyItem {
1292 fn eq(&self, other: &Self) -> bool {
1293 self.user_dev == other.user_dev
1294 }
1295}
1296
1297impl Eq for VerifyItem {}
1298
1299impl Ord for VerifyItem {
1300 fn cmp(&self, other: &Self) -> Ordering {
1301 fn state_val(sas: &SasVerification) -> usize {
1302 if sas.is_done() {
1303 return 3;
1304 } else if sas.is_cancelled() {
1305 return 2;
1306 } else {
1307 return 1;
1308 }
1309 }
1310
1311 fn device_val(sas: &SasVerification) -> usize {
1312 if sas.is_self_verification() {
1313 return 1;
1314 } else {
1315 return 2;
1316 }
1317 }
1318
1319 let state1 = state_val(&self.sasv1);
1320 let state2 = state_val(&other.sasv1);
1321
1322 let dev1 = device_val(&self.sasv1);
1323 let dev2 = device_val(&other.sasv1);
1324
1325 let scmp = state1.cmp(&state2);
1326 let dcmp = dev1.cmp(&dev2);
1327
1328 scmp.then(dcmp).then_with(|| {
1329 let did1 = self.sasv1.other_device().device_id();
1330 let did2 = other.sasv1.other_device().device_id();
1331
1332 did1.cmp(did2)
1333 })
1334 }
1335}
1336
1337impl PartialOrd for VerifyItem {
1338 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1339 Some(self.cmp(other))
1340 }
1341}
1342
1343impl From<(&String, &SasVerification)> for VerifyItem {
1344 fn from((user_dev, sasv1): (&String, &SasVerification)) -> Self {
1345 VerifyItem::new(user_dev.clone(), sasv1.clone())
1346 }
1347}
1348
1349impl Display for VerifyItem {
1350 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1351 if self.sasv1.is_done() {
1352 return Ok(());
1353 }
1354
1355 if self.sasv1.is_cancelled() {
1356 write!(f, ":verify request {}", self.sasv1.other_user_id())
1357 } else if self.sasv1.emoji().is_some() {
1358 write!(f, ":verify confirm {}", self.user_dev)
1359 } else {
1360 write!(f, ":verify accept {}", self.user_dev)
1361 }
1362 }
1363}
1364
1365impl ListItem<IambInfo> for VerifyItem {
1366 fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
1367 let mut lines = vec![];
1368
1369 let bold = Style::default().add_modifier(StyleModifier::BOLD);
1370 let item = Span::styled(self.show_item(), selected_style(selected));
1371 lines.push(Line::from(item));
1372
1373 if self.sasv1.is_done() {
1374 // Print nothing.
1375 } else if self.sasv1.is_cancelled() {
1376 if let Some(info) = self.sasv1.cancel_info() {
1377 lines.push(Line::from(format!(" Cancelled: {}", info.reason())));
1378 lines.push(Line::from(""));
1379 }
1380
1381 lines.push(Line::from(" You can start a new verification request with:"));
1382 } else if let Some(emoji) = self.sasv1.emoji() {
1383 lines.push(Line::from(
1384 " Both devices should see the following Emoji sequence:".to_string(),
1385 ));
1386 lines.push(Line::from(""));
1387
1388 for line in format_emojis(emoji).lines() {
1389 lines.push(Line::from(format!(" {line}")));
1390 }
1391
1392 lines.push(Line::from(""));
1393 lines.push(Line::from(" If they don't match, run:"));
1394 lines.push(Line::from(""));
1395 lines.push(Line::from(Span::styled(
1396 format!(":verify mismatch {}", self.user_dev),
1397 bold,
1398 )));
1399 lines.push(Line::from(""));
1400 lines.push(Line::from(" If everything looks right, you can confirm with:"));
1401 } else {
1402 lines.push(Line::from(" To accept this request, run:"));
1403 }
1404
1405 let cmd = self.to_string();
1406
1407 if !cmd.is_empty() {
1408 lines.push(Line::from(""));
1409 lines.push(Line::from(vec![Span::from(" "), Span::styled(cmd, bold)]));
1410 lines.push(Line::from(""));
1411 lines.push(Line::from(vec![
1412 Span::from("You can copy the above command with "),
1413 Span::styled("yy", bold),
1414 Span::from(" and then execute it with "),
1415 Span::styled("@\"", bold),
1416 ]));
1417 }
1418
1419 Text::from(lines)
1420 }
1421
1422 fn get_word(&self) -> Option<String> {
1423 None
1424 }
1425}
1426
1427impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
1428 fn prompt(
1429 &mut self,
1430 act: &PromptAction,
1431 _: &ProgramContext,
1432 _: &mut ProgramStore,
1433 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1434 match act {
1435 PromptAction::Submit => Ok(vec![]),
1436 PromptAction::Abort(_) => {
1437 let msg = "Cannot abort entry inside a list";
1438 let err = EditError::Failure(msg.into());
1439
1440 Err(err)
1441 },
1442 PromptAction::Recall(..) => {
1443 let msg = "Cannot recall history inside a list";
1444 let err = EditError::Failure(msg.into());
1445
1446 Err(err)
1447 },
1448 }
1449 }
1450}
1451
1452#[derive(Clone)]
1453pub struct MemberItem {
1454 member: RoomMember,
1455 room_id: OwnedRoomId,
1456}
1457
1458impl MemberItem {
1459 fn new(member: RoomMember, room_id: OwnedRoomId) -> Self {
1460 Self { member, room_id }
1461 }
1462}
1463
1464impl Display for MemberItem {
1465 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1466 write!(f, "{}", self.member.user_id())
1467 }
1468}
1469
1470impl ListItem<IambInfo> for MemberItem {
1471 fn show(
1472 &self,
1473 selected: bool,
1474 _: &ViewportContext<ListCursor>,
1475 store: &mut ProgramStore,
1476 ) -> Text {
1477 let info = store.application.rooms.get_or_default(self.room_id.clone());
1478 let user_id = self.member.user_id();
1479
1480 let (color, name) = store.application.settings.get_user_overrides(self.member.user_id());
1481 let color = color.unwrap_or_else(|| super::config::user_color(user_id.as_str()));
1482 let mut style = super::config::user_style_from_color(color);
1483
1484 if selected {
1485 style = style.add_modifier(StyleModifier::REVERSED);
1486 }
1487
1488 let mut spans = vec![];
1489 let mut parens = false;
1490
1491 if let Some(name) = name {
1492 spans.push(Span::styled(name, style));
1493 parens = true;
1494 } else if let Some(display) = info.display_names.get(user_id) {
1495 spans.push(Span::styled(display.clone(), style));
1496 parens = true;
1497 }
1498
1499 spans.extend(parens.then_some(Span::styled(" (", style)));
1500 spans.push(Span::styled(user_id.as_str(), style));
1501 spans.extend(parens.then_some(Span::styled(")", style)));
1502
1503 let state = match self.member.membership() {
1504 MembershipState::Ban => Span::raw(" (banned)").into(),
1505 MembershipState::Invite => Span::raw(" (invited)").into(),
1506 MembershipState::Knock => Span::raw(" (wants to join)").into(),
1507 MembershipState::Leave => Span::raw(" (left)").into(),
1508 MembershipState::Join => None,
1509 _ => None,
1510 };
1511
1512 spans.extend(state);
1513
1514 return Line::from(spans).into();
1515 }
1516
1517 fn get_word(&self) -> Option<String> {
1518 self.member.user_id().to_string().into()
1519 }
1520}
1521
1522impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
1523 fn prompt(
1524 &mut self,
1525 act: &PromptAction,
1526 _: &ProgramContext,
1527 _: &mut ProgramStore,
1528 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1529 match act {
1530 PromptAction::Submit => Ok(vec![]),
1531 PromptAction::Abort(_) => {
1532 let msg = "Cannot abort entry inside a list";
1533 let err = EditError::Failure(msg.into());
1534
1535 Err(err)
1536 },
1537 PromptAction::Recall(..) => {
1538 let msg = "Cannot recall history inside a list";
1539 let err = EditError::Failure(msg.into());
1540
1541 Err(err)
1542 },
1543 }
1544 }
1545}
1546
1547#[cfg(test)]
1548mod tests {
1549 use super::*;
1550 use matrix_sdk::ruma::{room_alias_id, server_name};
1551
1552 #[derive(Debug, Eq, PartialEq)]
1553 struct TestRoomItem {
1554 room_id: OwnedRoomId,
1555 tags: Vec<TagName>,
1556 alias: Option<OwnedRoomAliasId>,
1557 name: &'static str,
1558 unread: UnreadInfo,
1559 }
1560
1561 impl RoomLikeItem for &TestRoomItem {
1562 fn room_id(&self) -> &RoomId {
1563 self.room_id.as_ref()
1564 }
1565
1566 fn has_tag(&self, tag: TagName) -> bool {
1567 self.tags.contains(&tag)
1568 }
1569
1570 fn alias(&self) -> Option<&RoomAliasId> {
1571 self.alias.as_deref()
1572 }
1573
1574 fn name(&self) -> &str {
1575 self.name
1576 }
1577
1578 fn recent_ts(&self) -> Option<&MessageTimeStamp> {
1579 self.unread.latest()
1580 }
1581
1582 fn is_unread(&self) -> bool {
1583 self.unread.is_unread()
1584 }
1585 }
1586
1587 #[test]
1588 fn test_sort_rooms() {
1589 let server = server_name!("example.com");
1590
1591 let room1 = TestRoomItem {
1592 room_id: RoomId::new(server).to_owned(),
1593 tags: vec![TagName::Favorite],
1594 alias: Some(room_alias_id!("#room1:example.com").to_owned()),
1595 name: "Z",
1596 unread: UnreadInfo::default(),
1597 };
1598
1599 let room2 = TestRoomItem {
1600 room_id: RoomId::new(server).to_owned(),
1601 tags: vec![],
1602 alias: Some(room_alias_id!("#a:example.com").to_owned()),
1603 name: "Unnamed Room",
1604 unread: UnreadInfo::default(),
1605 };
1606
1607 let room3 = TestRoomItem {
1608 room_id: RoomId::new(server).to_owned(),
1609 tags: vec![],
1610 alias: None,
1611 name: "Cool Room",
1612 unread: UnreadInfo::default(),
1613 };
1614
1615 // Sort by Name ascending.
1616 let mut rooms = vec![&room1, &room2, &room3];
1617 let fields = &[SortColumn(SortFieldRoom::Name, SortOrder::Ascending)];
1618 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1619 assert_eq!(rooms, vec![&room3, &room2, &room1]);
1620
1621 // Sort by Name descending.
1622 let mut rooms = vec![&room1, &room2, &room3];
1623 let fields = &[SortColumn(SortFieldRoom::Name, SortOrder::Descending)];
1624 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1625 assert_eq!(rooms, vec![&room1, &room2, &room3]);
1626
1627 // Sort by Favorite and Alias before Name to show order matters.
1628 let mut rooms = vec![&room1, &room2, &room3];
1629 let fields = &[
1630 SortColumn(SortFieldRoom::Favorite, SortOrder::Ascending),
1631 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1632 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1633 ];
1634 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1635 assert_eq!(rooms, vec![&room1, &room2, &room3]);
1636
1637 // Now flip order of Favorite with Descending
1638 let mut rooms = vec![&room1, &room2, &room3];
1639 let fields = &[
1640 SortColumn(SortFieldRoom::Favorite, SortOrder::Descending),
1641 SortColumn(SortFieldRoom::Alias, SortOrder::Ascending),
1642 SortColumn(SortFieldRoom::Name, SortOrder::Ascending),
1643 ];
1644 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1645 assert_eq!(rooms, vec![&room2, &room3, &room1]);
1646 }
1647
1648 #[test]
1649 fn test_sort_room_recents() {
1650 let server = server_name!("example.com");
1651
1652 let room1 = TestRoomItem {
1653 room_id: RoomId::new(server).to_owned(),
1654 tags: vec![],
1655 alias: None,
1656 name: "Room 1",
1657 unread: UnreadInfo { unread: false, latest: None },
1658 };
1659
1660 let room2 = TestRoomItem {
1661 room_id: RoomId::new(server).to_owned(),
1662 tags: vec![],
1663 alias: None,
1664 name: "Room 2",
1665 unread: UnreadInfo {
1666 unread: false,
1667 latest: Some(MessageTimeStamp::OriginServer(40u32.into())),
1668 },
1669 };
1670
1671 let room3 = TestRoomItem {
1672 room_id: RoomId::new(server).to_owned(),
1673 tags: vec![],
1674 alias: None,
1675 name: "Room 3",
1676 unread: UnreadInfo {
1677 unread: false,
1678 latest: Some(MessageTimeStamp::OriginServer(20u32.into())),
1679 },
1680 };
1681
1682 // Sort by Recent ascending.
1683 let mut rooms = vec![&room1, &room2, &room3];
1684 let fields = &[SortColumn(SortFieldRoom::Recent, SortOrder::Ascending)];
1685 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1686 assert_eq!(rooms, vec![&room2, &room3, &room1]);
1687
1688 // Sort by Recent descending.
1689 let mut rooms = vec![&room1, &room2, &room3];
1690 let fields = &[SortColumn(SortFieldRoom::Recent, SortOrder::Descending)];
1691 rooms.sort_by(|a, b| room_fields_cmp(a, b, fields));
1692 assert_eq!(rooms, vec![&room1, &room3, &room2]);
1693 }
1694}