src/windows/mod.rs

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