src/base.rs

807 lines · 23546 bytes

  1use std::collections::{HashMap, HashSet};
  2use std::hash::Hash;
  3use std::sync::Arc;
  4use std::time::{Duration, Instant};
  5
  6use tokio::sync::Mutex as AsyncMutex;
  7use tracing::warn;
  8
  9use matrix_sdk::{
 10    encryption::verification::SasVerification,
 11    room::Joined,
 12    ruma::{
 13        events::{
 14            reaction::ReactionEvent,
 15            room::message::{
 16                OriginalRoomMessageEvent,
 17                Relation,
 18                Replacement,
 19                RoomMessageEvent,
 20                RoomMessageEventContent,
 21            },
 22            tag::{TagName, Tags},
 23            AnyMessageLikeEvent,
 24            MessageLikeEvent,
 25        },
 26        EventId,
 27        OwnedEventId,
 28        OwnedRoomId,
 29        OwnedUserId,
 30        RoomId,
 31    },
 32};
 33
 34use modalkit::{
 35    editing::{
 36        action::{Action, UIError, UIResult},
 37        application::{
 38            ApplicationAction,
 39            ApplicationContentId,
 40            ApplicationError,
 41            ApplicationInfo,
 42            ApplicationStore,
 43            ApplicationWindowId,
 44        },
 45        context::EditContext,
 46        store::Store,
 47    },
 48    env::vim::{
 49        command::{CommandContext, VimCommand, VimCommandMachine},
 50        keybindings::VimMachine,
 51        VimContext,
 52    },
 53    input::bindings::SequenceStatus,
 54    input::key::TerminalKey,
 55    tui::{
 56        buffer::Buffer,
 57        layout::{Alignment, Rect},
 58        text::{Span, Spans},
 59        widgets::{Paragraph, Widget},
 60    },
 61};
 62
 63use crate::{
 64    message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
 65    worker::Requester,
 66    ApplicationSettings,
 67};
 68
 69const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
 70
 71#[derive(Clone, Debug, Eq, PartialEq)]
 72pub enum IambInfo {}
 73
 74#[derive(Clone, Debug, Eq, PartialEq)]
 75pub enum VerifyAction {
 76    Accept,
 77    Cancel,
 78    Confirm,
 79    Mismatch,
 80}
 81
 82#[derive(Clone, Debug, Eq, PartialEq)]
 83pub enum MessageAction {
 84    /// Cance the current reply or edit.
 85    Cancel,
 86
 87    /// Download an attachment to the given path.
 88    ///
 89    /// The second argument controls whether to overwrite any already existing file at the
 90    /// destination path, or to open the attachment after downloading.
 91    Download(Option<String>, DownloadFlags),
 92
 93    /// Edit a sent message.
 94    Edit,
 95
 96    /// React to a message with an Emoji.
 97    React(String),
 98
 99    /// Redact a message, with an optional reason.
100    Redact(Option<String>),
101
102    /// Reply to a message.
103    Reply,
104
105    /// Unreact to a message.
106    ///
107    /// If no specific Emoji to remove to is specified, then all reactions from the user on the
108    /// message are removed.
109    Unreact(Option<String>),
110}
111
112bitflags::bitflags! {
113    pub struct DownloadFlags: u32 {
114        const NONE = 0b00000000;
115
116        /// Overwrite file if it already exists.
117        const FORCE = 0b00000001;
118
119        /// Open file after downloading.
120        const OPEN = 0b00000010;
121    }
122}
123
124#[derive(Clone, Debug, Eq, PartialEq)]
125pub enum RoomField {
126    Name,
127    Tag(TagName),
128    Topic,
129}
130
131#[derive(Clone, Debug, Eq, PartialEq)]
132pub enum RoomAction {
133    InviteAccept,
134    InviteReject,
135    InviteSend(OwnedUserId),
136    Members(Box<CommandContext<ProgramContext>>),
137    Set(RoomField, String),
138    Unset(RoomField),
139}
140
141#[derive(Clone, Debug, Eq, PartialEq)]
142pub enum SendAction {
143    Submit,
144    Upload(String),
145}
146
147#[derive(Clone, Debug, Eq, PartialEq)]
148pub enum IambAction {
149    Message(MessageAction),
150    Room(RoomAction),
151    Send(SendAction),
152    Verify(VerifyAction, String),
153    VerifyRequest(String),
154    ToggleScrollbackFocus,
155}
156
157impl From<MessageAction> for IambAction {
158    fn from(act: MessageAction) -> Self {
159        IambAction::Message(act)
160    }
161}
162
163impl From<RoomAction> for IambAction {
164    fn from(act: RoomAction) -> Self {
165        IambAction::Room(act)
166    }
167}
168
169impl From<SendAction> for IambAction {
170    fn from(act: SendAction) -> Self {
171        IambAction::Send(act)
172    }
173}
174
175impl ApplicationAction for IambAction {
176    fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
177        match self {
178            IambAction::Message(..) => SequenceStatus::Break,
179            IambAction::Room(..) => SequenceStatus::Break,
180            IambAction::Send(..) => SequenceStatus::Break,
181            IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
182            IambAction::Verify(..) => SequenceStatus::Break,
183            IambAction::VerifyRequest(..) => SequenceStatus::Break,
184        }
185    }
186
187    fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
188        match self {
189            IambAction::Message(..) => SequenceStatus::Atom,
190            IambAction::Room(..) => SequenceStatus::Atom,
191            IambAction::Send(..) => SequenceStatus::Atom,
192            IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
193            IambAction::Verify(..) => SequenceStatus::Atom,
194            IambAction::VerifyRequest(..) => SequenceStatus::Atom,
195        }
196    }
197
198    fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
199        match self {
200            IambAction::Message(..) => SequenceStatus::Ignore,
201            IambAction::Room(..) => SequenceStatus::Ignore,
202            IambAction::Send(..) => SequenceStatus::Ignore,
203            IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
204            IambAction::Verify(..) => SequenceStatus::Ignore,
205            IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
206        }
207    }
208
209    fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
210        match self {
211            IambAction::Message(..) => false,
212            IambAction::Room(..) => false,
213            IambAction::Send(..) => false,
214            IambAction::ToggleScrollbackFocus => false,
215            IambAction::Verify(..) => false,
216            IambAction::VerifyRequest(..) => false,
217        }
218    }
219}
220
221impl From<RoomAction> for ProgramAction {
222    fn from(act: RoomAction) -> Self {
223        IambAction::from(act).into()
224    }
225}
226
227impl From<IambAction> for ProgramAction {
228    fn from(act: IambAction) -> Self {
229        Action::Application(act)
230    }
231}
232
233pub type ProgramAction = Action<IambInfo>;
234pub type ProgramContext = VimContext<IambInfo>;
235pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
236pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
237pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
238pub type ProgramStore = Store<IambInfo>;
239pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
240
241pub type IambResult<T> = UIResult<T, IambInfo>;
242
243/// Reaction events for some message.
244///
245/// The event identifier used as a key here is the ID for the reaction, and not for the message
246/// it's reacting to.
247pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
248
249pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
250
251#[derive(thiserror::Error, Debug)]
252pub enum IambError {
253    #[error("Invalid user identifier: {0}")]
254    InvalidUserId(String),
255
256    #[error("Invalid verification user/device pair: {0}")]
257    InvalidVerificationId(String),
258
259    #[error("Cryptographic storage error: {0}")]
260    CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
261
262    #[error("HTTP client error: {0}")]
263    Http(#[from] matrix_sdk::HttpError),
264
265    #[error("Matrix client error: {0}")]
266    Matrix(#[from] matrix_sdk::Error),
267
268    #[error("Matrix client storage error: {0}")]
269    Store(#[from] matrix_sdk::StoreError),
270
271    #[error("Serialization/deserialization error: {0}")]
272    Serde(#[from] serde_json::Error),
273
274    #[error("Selected message does not have any attachments")]
275    NoAttachment,
276
277    #[error("No message currently selected")]
278    NoSelectedMessage,
279
280    #[error("Current window is not a room or space")]
281    NoSelectedRoomOrSpace,
282
283    #[error("Current window is not a room")]
284    NoSelectedRoom,
285
286    #[error("You do not have a current invitation to this room")]
287    NotInvited,
288
289    #[error("You need to join the room before you can do that")]
290    NotJoined,
291
292    #[error("Unknown room identifier: {0}")]
293    UnknownRoom(OwnedRoomId),
294
295    #[error("Verification request error: {0}")]
296    VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
297}
298
299impl From<IambError> for UIError<IambInfo> {
300    fn from(err: IambError) -> Self {
301        UIError::Application(err)
302    }
303}
304
305impl ApplicationError for IambError {}
306
307#[derive(Default)]
308pub enum RoomFetchStatus {
309    Done,
310    HaveMore(String),
311    #[default]
312    NotStarted,
313}
314
315pub enum EventLocation {
316    Message(MessageKey),
317    Reaction(OwnedEventId),
318}
319
320impl EventLocation {
321    fn to_message_key(&self) -> Option<&MessageKey> {
322        if let EventLocation::Message(key) = self {
323            Some(key)
324        } else {
325            None
326        }
327    }
328}
329
330#[derive(Default)]
331pub struct RoomInfo {
332    /// The display name for this room.
333    pub name: Option<String>,
334
335    /// The tags placed on this room.
336    pub tags: Option<Tags>,
337
338    /// A map of event IDs to where they are stored in this struct.
339    pub keys: HashMap<OwnedEventId, EventLocation>,
340
341    /// The messages loaded for this room.
342    pub messages: Messages,
343
344    /// A map of read markers to display on different events.
345    pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>,
346
347    /// An event ID for where we should indicate we've read up to.
348    pub read_till: Option<OwnedEventId>,
349
350    /// A map of message identifiers to a map of reaction events.
351    pub reactions: HashMap<OwnedEventId, MessageReactions>,
352
353    /// Where to continue fetching from when we continue loading scrollback history.
354    pub fetch_id: RoomFetchStatus,
355
356    /// The time that we last fetched scrollback for this room.
357    pub fetch_last: Option<Instant>,
358
359    /// Users currently typing in this room, and when we received notification of them doing so.
360    pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
361}
362
363impl RoomInfo {
364    pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
365        if let Some(reacts) = self.reactions.get(event_id) {
366            let mut counts = HashMap::new();
367
368            for (key, _) in reacts.values() {
369                let count = counts.entry(key.as_str()).or_default();
370                *count += 1;
371            }
372
373            let mut reactions = counts.into_iter().collect::<Vec<_>>();
374            reactions.sort();
375
376            reactions
377        } else {
378            vec![]
379        }
380    }
381
382    pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
383        self.messages.get(self.keys.get(event_id)?.to_message_key()?)
384    }
385
386    pub fn insert_reaction(&mut self, react: ReactionEvent) {
387        match react {
388            MessageLikeEvent::Original(react) => {
389                let rel_id = react.content.relates_to.event_id;
390                let key = react.content.relates_to.key;
391
392                let message = self.reactions.entry(rel_id.clone()).or_default();
393                let event_id = react.event_id;
394                let user_id = react.sender;
395
396                message.insert(event_id.clone(), (key, user_id));
397
398                let loc = EventLocation::Reaction(rel_id);
399                self.keys.insert(event_id, loc);
400            },
401            MessageLikeEvent::Redacted(_) => {
402                return;
403            },
404        }
405    }
406
407    pub fn insert_edit(&mut self, msg: Replacement) {
408        let event_id = msg.event_id;
409        let new_content = msg.new_content;
410
411        let key = if let Some(EventLocation::Message(k)) = self.keys.get(&event_id) {
412            k
413        } else {
414            return;
415        };
416
417        let msg = if let Some(msg) = self.messages.get_mut(key) {
418            msg
419        } else {
420            return;
421        };
422
423        match &mut msg.event {
424            MessageEvent::Original(orig) => {
425                orig.content = *new_content;
426            },
427            MessageEvent::Local(_, content) => {
428                *content = new_content;
429            },
430            MessageEvent::Redacted(_) => {
431                return;
432            },
433        }
434    }
435
436    pub fn insert_message(&mut self, msg: RoomMessageEvent) {
437        let event_id = msg.event_id().to_owned();
438        let key = (msg.origin_server_ts().into(), event_id.clone());
439
440        self.keys.insert(event_id.clone(), EventLocation::Message(key.clone()));
441        self.messages.insert(key, msg.into());
442
443        // Remove any echo.
444        let key = (MessageTimeStamp::LocalEcho, event_id);
445        let _ = self.messages.remove(&key);
446    }
447
448    pub fn insert(&mut self, msg: RoomMessageEvent) {
449        match msg {
450            RoomMessageEvent::Original(OriginalRoomMessageEvent {
451                content:
452                    RoomMessageEventContent { relates_to: Some(Relation::Replacement(repl)), .. },
453                ..
454            }) => self.insert_edit(repl),
455            _ => self.insert_message(msg),
456        }
457    }
458
459    fn recently_fetched(&self) -> bool {
460        self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
461    }
462
463    fn get_typers(&self) -> &[OwnedUserId] {
464        if let Some((t, users)) = &self.users_typing {
465            if t.elapsed() < Duration::from_secs(4) {
466                return users.as_ref();
467            } else {
468                return &[];
469            }
470        } else {
471            return &[];
472        }
473    }
474
475    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Spans<'a> {
476        let typers = self.get_typers();
477        let n = typers.len();
478
479        match n {
480            0 => Spans(vec![]),
481            1 => {
482                let user = settings.get_user_span(typers[0].as_ref());
483
484                Spans(vec![user, Span::from(" is typing...")])
485            },
486            2 => {
487                let user1 = settings.get_user_span(typers[0].as_ref());
488                let user2 = settings.get_user_span(typers[1].as_ref());
489
490                Spans(vec![
491                    user1,
492                    Span::raw(" and "),
493                    user2,
494                    Span::from(" are typing..."),
495                ])
496            },
497            n if n < 5 => Spans::from("Several people are typing..."),
498            _ => Spans::from("Many people are typing..."),
499        }
500    }
501
502    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
503        self.users_typing = (Instant::now(), user_ids).into();
504    }
505
506    pub fn render_typing(
507        &mut self,
508        area: Rect,
509        buf: &mut Buffer,
510        settings: &ApplicationSettings,
511    ) -> Rect {
512        if area.height <= 2 || area.width <= 20 {
513            return area;
514        }
515
516        if !settings.tunables.typing_notice_display {
517            return area;
518        }
519
520        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
521        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
522
523        Paragraph::new(self.get_typing_spans(settings))
524            .alignment(Alignment::Center)
525            .render(bar, buf);
526
527        return top;
528    }
529}
530
531pub struct ChatStore {
532    pub worker: Requester,
533    pub rooms: HashMap<OwnedRoomId, RoomInfo>,
534    pub names: HashMap<String, OwnedRoomId>,
535    pub verifications: HashMap<String, SasVerification>,
536    pub settings: ApplicationSettings,
537    pub need_load: HashSet<OwnedRoomId>,
538}
539
540impl ChatStore {
541    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
542        ChatStore {
543            worker,
544            settings,
545
546            names: Default::default(),
547            rooms: Default::default(),
548            verifications: Default::default(),
549            need_load: Default::default(),
550        }
551    }
552
553    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
554        self.worker.client.get_joined_room(room_id)
555    }
556
557    pub fn get_room_title(&self, room_id: &RoomId) -> String {
558        self.rooms
559            .get(room_id)
560            .and_then(|i| i.name.as_ref())
561            .map(String::from)
562            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
563    }
564
565    pub async fn set_receipts(&mut self, receipts: Vec<(OwnedRoomId, Receipts)>) {
566        let mut updates = vec![];
567
568        for (room_id, receipts) in receipts.into_iter() {
569            if let Some(info) = self.rooms.get_mut(&room_id) {
570                info.receipts = receipts;
571
572                if let Some(read_till) = info.read_till.take() {
573                    updates.push((room_id, read_till));
574                }
575            }
576        }
577
578        for (room_id, read_till) in updates.into_iter() {
579            if let Some(room) = self.worker.client.get_joined_room(&room_id) {
580                let _ = room.read_receipt(read_till.as_ref()).await;
581            }
582        }
583    }
584
585    pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
586        self.need_load.insert(room_id);
587    }
588
589    pub fn load_older(&mut self, limit: u32) {
590        let ChatStore { need_load, rooms, worker, .. } = self;
591
592        for room_id in std::mem::take(need_load).into_iter() {
593            let info = rooms.entry(room_id.clone()).or_default();
594
595            if info.recently_fetched() {
596                need_load.insert(room_id);
597                continue;
598            } else {
599                info.fetch_last = Instant::now().into();
600            }
601
602            let fetch_id = match &info.fetch_id {
603                RoomFetchStatus::Done => continue,
604                RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
605                RoomFetchStatus::NotStarted => None,
606            };
607
608            let res = worker.load_older(room_id.clone(), fetch_id, limit);
609
610            match res {
611                Ok((fetch_id, msgs)) => {
612                    for msg in msgs.into_iter() {
613                        match msg {
614                            AnyMessageLikeEvent::RoomMessage(msg) => {
615                                info.insert(msg);
616                            },
617                            AnyMessageLikeEvent::Reaction(ev) => {
618                                info.insert_reaction(ev);
619                            },
620                            _ => continue,
621                        }
622                    }
623
624                    info.fetch_id =
625                        fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore);
626                },
627                Err(e) => {
628                    warn!(
629                        room_id = room_id.as_str(),
630                        err = e.to_string(),
631                        "Failed to load older messages"
632                    );
633
634                    // Wait and try again.
635                    need_load.insert(room_id);
636                },
637            }
638        }
639    }
640
641    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
642        self.rooms.entry(room_id).or_default()
643    }
644
645    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
646        self.rooms.entry(room_id.to_owned()).or_default().name = name.to_string().into();
647    }
648
649    pub fn insert_sas(&mut self, sas: SasVerification) {
650        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
651
652        self.verifications.insert(key, sas);
653    }
654}
655
656impl ApplicationStore for ChatStore {}
657
658#[derive(Clone, Debug, Eq, Hash, PartialEq)]
659pub enum IambId {
660    Room(OwnedRoomId),
661    DirectList,
662    MemberList(OwnedRoomId),
663    RoomList,
664    SpaceList,
665    VerifyList,
666    Welcome,
667}
668
669impl ApplicationWindowId for IambId {}
670
671#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
672pub enum RoomFocus {
673    Scrollback,
674    MessageBar,
675}
676
677impl RoomFocus {
678    pub fn is_scrollback(&self) -> bool {
679        matches!(self, RoomFocus::Scrollback)
680    }
681
682    pub fn is_msgbar(&self) -> bool {
683        matches!(self, RoomFocus::MessageBar)
684    }
685}
686
687#[derive(Clone, Debug, Eq, Hash, PartialEq)]
688pub enum IambBufferId {
689    Command,
690    Room(OwnedRoomId, RoomFocus),
691    DirectList,
692    MemberList(OwnedRoomId),
693    RoomList,
694    SpaceList,
695    VerifyList,
696    Welcome,
697}
698
699impl IambBufferId {
700    pub fn to_window(&self) -> Option<IambId> {
701        match self {
702            IambBufferId::Command => None,
703            IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
704            IambBufferId::DirectList => Some(IambId::DirectList),
705            IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
706            IambBufferId::RoomList => Some(IambId::RoomList),
707            IambBufferId::SpaceList => Some(IambId::SpaceList),
708            IambBufferId::VerifyList => Some(IambId::VerifyList),
709            IambBufferId::Welcome => Some(IambId::Welcome),
710        }
711    }
712}
713
714impl ApplicationContentId for IambBufferId {}
715
716impl ApplicationInfo for IambInfo {
717    type Error = IambError;
718    type Store = ChatStore;
719    type Action = IambAction;
720    type WindowId = IambId;
721    type ContentId = IambBufferId;
722}
723
724#[cfg(test)]
725pub mod tests {
726    use super::*;
727    use crate::config::user_style_from_color;
728    use crate::tests::*;
729    use modalkit::tui::style::Color;
730
731    #[test]
732    fn test_typing_spans() {
733        let mut info = RoomInfo::default();
734        let settings = mock_settings();
735
736        let users0 = vec![];
737        let users1 = vec![TEST_USER1.clone()];
738        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
739        let users4 = vec![
740            TEST_USER1.clone(),
741            TEST_USER2.clone(),
742            TEST_USER3.clone(),
743            TEST_USER4.clone(),
744        ];
745        let users5 = vec![
746            TEST_USER1.clone(),
747            TEST_USER2.clone(),
748            TEST_USER3.clone(),
749            TEST_USER4.clone(),
750            TEST_USER5.clone(),
751        ];
752
753        // Nothing set.
754        assert_eq!(info.users_typing, None);
755        assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
756
757        // Empty typing list.
758        info.set_typing(users0);
759        assert!(info.users_typing.is_some());
760        assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
761
762        // Single user typing.
763        info.set_typing(users1);
764        assert!(info.users_typing.is_some());
765        assert_eq!(
766            info.get_typing_spans(&settings),
767            Spans(vec![
768                Span::styled("@user1:example.com", user_style("@user1:example.com")),
769                Span::from(" is typing...")
770            ])
771        );
772
773        // Two users typing.
774        info.set_typing(users2);
775        assert!(info.users_typing.is_some());
776        assert_eq!(
777            info.get_typing_spans(&settings),
778            Spans(vec![
779                Span::styled("@user1:example.com", user_style("@user1:example.com")),
780                Span::raw(" and "),
781                Span::styled("@user2:example.com", user_style("@user2:example.com")),
782                Span::raw(" are typing...")
783            ])
784        );
785
786        // Four users typing.
787        info.set_typing(users4);
788        assert!(info.users_typing.is_some());
789        assert_eq!(info.get_typing_spans(&settings), Spans::from("Several people are typing..."));
790
791        // Five users typing.
792        info.set_typing(users5);
793        assert!(info.users_typing.is_some());
794        assert_eq!(info.get_typing_spans(&settings), Spans::from("Many people are typing..."));
795
796        // Test that USER5 gets rendered using the configured color and name.
797        info.set_typing(vec![TEST_USER5.clone()]);
798        assert!(info.users_typing.is_some());
799        assert_eq!(
800            info.get_typing_spans(&settings),
801            Spans(vec![
802                Span::styled("USER 5", user_style_from_color(Color::Black)),
803                Span::from(" is typing...")
804            ])
805        );
806    }
807}