use std::collections::{HashMap, HashSet}; use app_ui_kit::widgets::Unread; use chrono::{DateTime, FixedOffset, Utc}; use store::{ ChannelNotificationLevel, ChannelRecord, ChatRecord, MessageImportance, Sidebar, SidebarTeam, is_bot_id, }; use teams_core::{ChatSection, is_event_preview}; use crate::app_state::chat_title; use crate::data::{ Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others, unread_count, unread_importance_of, }; use crate::format; use crate::typing::{TypingState, preview_label}; pub const FAVORITES_FALLBACK_NAME: &str = "Favorites"; pub const OTHERS_NAME: &str = "Other chats"; pub const OTHERS_ID: &str = "others"; pub const MUTED_NAME: &str = "Muted"; pub const MUTED_ID: &str = "muted_chats"; pub const SECTION_PAGE_SIZE: usize = 5; pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here."; pub const DELETED_PREVIEW: &str = "Message deleted"; pub const DELETED_CHAT_PREVIEW: &str = "This message was deleted"; const OWN_PREFIX: &str = "You"; const GROUP_KIND: &str = "group"; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Preview { Empty, Deleted, Event(String), Typing(String), Text { prefix: Option, text: String, }, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Face { pub user_id: Option, pub name: String, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum AvatarSpec { Single(Face), Pair(Face, Face), Bot(Face), Meeting, Muted, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ChatItem { pub id: String, pub title: String, pub time_label: String, pub preview: Preview, pub unread: Unread, pub importance: MessageImportance, pub muted: bool, pub is_group: bool, pub member_count: usize, pub avatar: AvatarSpec, pub presence_user: Option, pub folder_id: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SectionKind { Favorites, Folder, Others, Muted, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Section { pub id: String, pub name: String, pub kind: SectionKind, pub collapsed: bool, pub count: usize, pub unread_chats: u32, pub items: Vec, pub hidden_count: usize, pub list_expanded: bool, pub show_empty_hint: bool, } pub struct SectionInput<'a> { pub chats: &'a [ChatRecord], pub directory: &'a Directory, pub collapsed: &'a HashSet, pub expanded_lists: &'a HashSet, pub typing: &'a TypingState, pub now: DateTime, pub offset: FixedOffset, } pub fn preview_for(chat: &ChatRecord, me: Option<&Person>) -> Preview { if chat.last_message_deleted { return Preview::Deleted; } let Some(text) = chat .last_message_preview .as_deref() .map(str::trim) .filter(|text| !text.is_empty()) else { return Preview::Empty; }; let sender_id = chat .last_message_sender_id .as_deref() .filter(|sender_id| !sender_id.is_empty()); if sender_id.is_none() && is_event_preview(text) { return Preview::Event(text.to_owned()); } let from_me = match (sender_id, me) { (Some(sender), Some(me)) => sender == me.user_id, _ => false, }; let prefix = if from_me { Some(OWN_PREFIX.to_owned()) } else if is_one_on_one(chat) { None } else { chat.last_message_sender_name .as_deref() .map(|name| format::first_name(name).to_owned()) .filter(|name| !name.is_empty()) }; Preview::Text { prefix, text: text.to_owned(), } } pub fn avatar_for(chat: &ChatRecord, me: Option<&Person>) -> AvatarSpec { if chat.kind.eq_ignore_ascii_case("meeting") { return AvatarSpec::Meeting; } let faces = face_members(chat, me); let face = |(user_id, name): (Option, String)| Face { user_id, name }; if let Some(bot) = one_on_one_bot(chat, me) { return AvatarSpec::Bot(face(bot)); } if is_one_on_one(chat) || faces.len() < 2 { return AvatarSpec::Single(match faces.into_iter().next() { Some(first) => face(first), None => Face { user_id: None, name: chat_title(chat), }, }); } let mut iterator = faces.into_iter(); let (first, second) = (iterator.next(), iterator.next()); match (first, second) { (Some(first), Some(second)) => AvatarSpec::Pair(face(first), face(second)), _ => AvatarSpec::Single(Face { user_id: None, name: chat_title(chat), }), } } pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<&str>) -> ChatItem { let me = input.directory.me.as_ref(); let unread = if chat.unread { unread_count(input.directory, chat) .filter(|count| *count > 0) .map_or(Unread::Dot, Unread::Count) } else { Unread::None }; let presence_user = (is_one_on_one(chat) && !chat.muted) .then(|| { others(chat, me) .into_iter() .find_map(|(user_id, _)| user_id) }) .flatten() .filter(|user_id| !is_bot_id(user_id)); let typing_names = input.typing.names(&chat.id); let preview = if typing_names.is_empty() { preview_for(chat, me) } else { Preview::Typing(preview_label(&typing_names, is_one_on_one(chat))) }; ChatItem { id: chat.id.clone(), title: chat_title(chat), time_label: chat .preview_at .or(chat.last_message_at) .map(|time| { format::list_time_label( time, input.now.with_timezone(&input.offset).date_naive(), input.offset, ) }) .unwrap_or_default(), preview, unread, importance: if chat.unread { unread_importance_of(input.directory, chat) } else { MessageImportance::Normal }, muted: chat.muted, is_group: chat.kind == GROUP_KIND, member_count: chat.members.len(), avatar: if chat.muted { AvatarSpec::Muted } else { avatar_for(chat, me) }, presence_user, folder_id: folder_id.map(str::to_owned), } } pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 { chats .iter() .filter(|chat| chat.unread && !chat.muted) .count() as u32 } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NameWeight { Regular, Semibold, Bold, } /// Teams channel list: `highlighted` is colorNeutralForeground1, otherwise colorNeutralForeground3. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct NameStyle { pub weight: NameWeight, pub highlighted: bool, } impl NameStyle { const PLAIN: NameStyle = NameStyle { weight: NameWeight::Regular, highlighted: false, }; } pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyle { if !unread || !shown { return NameStyle::PLAIN; } NameStyle { weight: if selected { NameWeight::Regular } else { NameWeight::Bold }, highlighted: true, } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MentionBadge { Count(u32), Channel, Team, } /// Teams pulls a hidden channel into the list while it holds personal @mentions. pub fn channel_shown(team: &SidebarTeam, channel_id: &str) -> bool { !team.hidden_channel_ids.iter().any(|id| id == channel_id) || team.channel_mentions(channel_id).personal > 0 } pub fn channel_hoisted(team: &SidebarTeam, channel_id: &str) -> bool { team.hidden_channel_ids.iter().any(|id| id == channel_id) && team.channel_mentions(channel_id).personal > 0 } pub fn team_hoisted(team: &SidebarTeam) -> bool { team.hidden && team .channels .iter() .any(|channel| channel_hoisted(team, &channel.id)) } pub fn channel_badge(team: &SidebarTeam, channel_id: &str) -> Option { let mentions = team.channel_mentions(channel_id); if mentions.personal > 0 { Some(MentionBadge::Count(mentions.personal)) } else if mentions.channel > 0 { Some(MentionBadge::Channel) } else if mentions.team > 0 { Some(MentionBadge::Team) } else { None } } /// The collapsed team row sums personal mentions of every channel, the icons only of shown channels. pub fn team_badge(team: &SidebarTeam, expanded: bool) -> Option { if expanded || !team_has_unread(team) { return None; } let personal: u32 = team .mentions .iter() .filter(|(channel_id, _)| { team.channels .iter() .any(|channel| &channel.id == *channel_id) }) .map(|(_, mentions)| mentions.personal) .sum(); if personal > 0 { return Some(MentionBadge::Count(personal)); } let shown = || { team.channels .iter() .filter(|channel| channel_shown(team, &channel.id)) .map(|channel| team.channel_mentions(&channel.id)) }; if shown().any(|mentions| mentions.channel > 0) { Some(MentionBadge::Channel) } else if shown().any(|mentions| mentions.team > 0) { Some(MentionBadge::Team) } else { None } } pub fn channel_shows_unread(team: &SidebarTeam, channel: &ChannelRecord) -> bool { channel.unread && (team.channel_notifications(&channel.id).level != ChannelNotificationLevel::Off || team.channel_mentions(&channel.id).personal > 0) } pub fn team_has_unread(team: &SidebarTeam) -> bool { team.channels .iter() .any(|channel| channel_shows_unread(team, channel) && channel_shown(team, &channel.id)) } pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle { if expanded || !team_has_unread(team) { return NameStyle::PLAIN; } NameStyle { weight: NameWeight::Semibold, highlighted: true, } } pub fn channel_unread(sidebar: &Sidebar, channel_id: &str) -> bool { sidebar .teams .iter() .flat_map(|team| team.channels.iter()) .any(|channel| channel.id == channel_id && channel.unread) } pub fn any_unread_channel(sidebar: &Sidebar) -> bool { sidebar .teams .iter() .filter(|team| !team.hidden) .any(team_has_unread) } pub fn build_sections(input: &SectionInput<'_>) -> Vec
{ let by_id: HashMap<&str, &ChatRecord> = input .chats .iter() .map(|chat| (chat.id.as_str(), chat)) .collect(); let mut placed: HashSet<&str> = HashSet::new(); let mut built: Vec> = input .directory .folders .iter() .map(|folder| { let (kind, name) = match folder.kind { FolderKind::Favorites => ( SectionKind::Favorites, if folder.name.trim().is_empty() { FAVORITES_FALLBACK_NAME.to_owned() } else { folder.name.clone() }, ), FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()), FolderKind::Recent | FolderKind::Meeting | FolderKind::Muted => return None, }; let items: Vec = folder .conversation_ids .iter() .filter_map(|id| by_id.get(id.as_str()).copied()) .filter(|chat| placed.insert(chat.id.as_str())) .map(|chat| chat_item(chat, input, Some(&folder.id))) .collect(); Some(section(folder.id.clone(), name, kind, items, input)) }) .collect(); let settings = &input.directory.section_settings; let mut muted = Vec::new(); let mut rest = Vec::new(); for chat in input .chats .iter() .filter(|chat| !placed.contains(chat.id.as_str())) { let item = chat_item(chat, input, None); if chat.muted && settings.enabled(ChatSection::Muted) { muted.push(item); } else { rest.push(item); } } let folder_id = |kind: FolderKind, fallback: &str| { input .directory .folders .iter() .find(|folder| folder.kind == kind) .map_or_else(|| fallback.to_owned(), |folder| folder.id.clone()) }; let mut others = Some(section( folder_id(FolderKind::Recent, OTHERS_ID), OTHERS_NAME.to_owned(), SectionKind::Others, rest, input, )); let mut muted = (!muted.is_empty()).then(|| { section( folder_id(FolderKind::Muted, MUTED_ID), MUTED_NAME.to_owned(), SectionKind::Muted, muted, input, ) }); let mut sections = Vec::new(); for (folder, section) in input.directory.folders.iter().zip(&mut built) { match folder.kind { FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()), FolderKind::Recent => sections.extend(others.take()), FolderKind::Meeting => {} FolderKind::Muted => sections.extend(muted.take()), } } sections.extend(others); sections.extend(muted); sections } pub fn wants_older_chats( others_end: Option, viewport_bottom: f32, scroll_top: f32, last_trigger_top: Option, loading: bool, ) -> bool { !loading && others_end.is_some_and(|end| end <= viewport_bottom) && last_trigger_top != Some(scroll_top) } pub fn older_chats_trigger_resets(previous: (bool, bool), current: (bool, bool)) -> bool { let ((had_more, was_loading), (has_more, is_loading)) = (previous, current); (was_loading && !is_loading) || (!had_more && has_more) } pub fn visible_chat_ids(sections: &[Section]) -> Vec<&str> { sections .iter() .filter(|section| !section.collapsed) .flat_map(|section| section.items.iter().map(|item| item.id.as_str())) .collect() } pub fn next_chat_id(sections: &[Section], removed_id: &str) -> Option { let visible = visible_chat_ids(sections); let position = visible.iter().position(|id| *id == removed_id)?; visible .get(position + 1) .or_else(|| { position .checked_sub(1) .and_then(|previous| visible.get(previous)) }) .map(|id| (*id).to_owned()) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Step { Previous, Next, } pub fn step_id(ids: &[&str], current: Option<&str>, step: Step) -> Option { let position = current.and_then(|current| ids.iter().position(|id| *id == current)); let target = match (position, step) { (Some(position), Step::Next) => position + 1, (Some(position), Step::Previous) => position.checked_sub(1)?, (None, Step::Next) => 0, (None, Step::Previous) => ids.len().checked_sub(1)?, }; ids.get(target).map(|id| (*id).to_owned()) } pub fn step_unread_id( sections: &[Section], current: Option<&str>, step: Step, ) -> Option { let items: Vec<&ChatItem> = sections .iter() .filter(|section| !section.collapsed) .flat_map(|section| section.items.iter()) .collect(); let position = current.and_then(|current| items.iter().position(|item| item.id == current)); let unread = |item: &&&ChatItem| item.unread.is_unread(); let found = match (position, step) { (Some(position), Step::Next) => items[position + 1..].iter().find(unread), (Some(position), Step::Previous) => items[..position].iter().rev().find(unread), (None, Step::Next) => items.iter().find(unread), (None, Step::Previous) => items.iter().rev().find(unread), }; found.map(|item| item.id.clone()) } pub struct ChannelOrderInput<'a> { pub teams: &'a [SidebarTeam], pub pinned_ids: &'a [String], pub collapsed_teams: &'a HashSet, pub revealed_channel_teams: &'a HashSet, pub hidden_teams_open: bool, pub selected_channel: Option<&'a str>, } pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> { let mut ids: Vec<&str> = Vec::new(); let mut push = |id: &'a str| { if !ids.contains(&id) { ids.push(id); } }; for pinned_id in input.pinned_ids { let known = input .teams .iter() .flat_map(|entry| entry.channels.iter()) .find(|channel| &channel.id == pinned_id); if let Some(channel) = known { push(&channel.id); } } let holds_selection = |entry: &SidebarTeam| { entry .channels .iter() .any(|channel| Some(channel.id.as_str()) == input.selected_channel) }; let hidden_teams_shown = input.hidden_teams_open || input .teams .iter() .any(|entry| entry.hidden && holds_selection(entry)); let main_teams = input .teams .iter() .filter(|entry| !entry.hidden || team_hoisted(entry)) .map(|entry| (entry, entry.hidden)); let hidden_teams = input .teams .iter() .filter(|entry| entry.hidden && hidden_teams_shown) .map(|entry| (entry, false)); for (entry, hoisted_only) in main_teams.chain(hidden_teams) { if input.collapsed_teams.contains(&entry.team.id) { continue; } for channel_id in team_channel_ids(entry, hoisted_only, input) { push(channel_id); } } ids } fn team_channel_ids<'a>( entry: &'a SidebarTeam, hoisted_only: bool, input: &ChannelOrderInput<'_>, ) -> Vec<&'a str> { let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel; let rows = team_channel_rows( entry, hoisted_only, input.revealed_channel_teams.contains(&entry.team.id), is_selected, ); rows.shown .into_iter() .chain(rows.revealed) .map(|channel| channel.id.as_str()) .collect() } pub struct TeamChannelRows<'a> { pub shown: Vec<&'a ChannelRecord>, pub hidden_count: usize, pub revealed: Vec<&'a ChannelRecord>, } /// `hoisted_only` is a hidden team pulled into the main list: it shows only its hoisted channels. pub fn team_channel_rows<'a>( entry: &'a SidebarTeam, hoisted_only: bool, revealed: bool, is_selected: impl Fn(&ChannelRecord) -> bool, ) -> TeamChannelRows<'a> { let shown: Vec<&ChannelRecord> = entry .channels .iter() .filter(|channel| { if hoisted_only { channel_hoisted(entry, &channel.id) } else { is_selected(channel) || channel_shown(entry, &channel.id) } }) .collect(); if hoisted_only { return TeamChannelRows { shown, hidden_count: 0, revealed: Vec::new(), }; } let hidden: Vec<&ChannelRecord> = entry .channels .iter() .filter(|channel| !shown.iter().any(|row| row.id == channel.id)) .collect(); TeamChannelRows { shown, hidden_count: hidden.len(), revealed: if revealed { hidden } else { Vec::new() }, } } fn section( id: String, name: String, kind: SectionKind, mut items: Vec, input: &SectionInput<'_>, ) -> Section { let collapsed = input.collapsed.contains(&id); let count = items.len(); let unread_chats = items .iter() .filter(|item| item.unread.is_unread() && !item.muted) .count() as u32; let paged = kind == SectionKind::Muted; let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id); let hidden_count = if paged && !list_expanded { count.saturating_sub(SECTION_PAGE_SIZE) } else { 0 }; items.truncate(count - hidden_count); for item in items.iter_mut().filter(|item| item.muted) { if item.unread.is_unread() { item.unread = Unread::Silent; } } Section { collapsed, count, unread_chats, hidden_count, list_expanded, show_empty_hint: items.is_empty() && !collapsed && matches!(kind, SectionKind::Favorites | SectionKind::Folder), id, name, kind, items, } } #[cfg(test)] mod tests { use chrono::TimeZone; use store::MemberRecord; use super::*; use crate::data::FolderInfo; fn me() -> Person { Person { user_id: "me".into(), display_name: "Me Myself".into(), } } fn chat(id: &str, kind: &str, unread: bool) -> ChatRecord { ChatRecord { id: id.into(), kind: kind.into(), title: id.to_uppercase(), unread, last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 7, 9, 30, 0).unwrap()), members: vec![ MemberRecord { user_id: Some("me".into()), display_name: "Me Myself".into(), }, MemberRecord { user_id: Some("ada".into()), display_name: "Ada Example".into(), }, MemberRecord { user_id: Some("bob".into()), display_name: "Bob Sample".into(), }, ], ..Default::default() } } fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo { FolderInfo { id: id.into(), name: format!("name-{id}"), kind, expanded: None, conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(), } } fn muted_chat(id: &str) -> ChatRecord { ChatRecord { muted: true, ..chat(id, "group", false) } } fn meeting_chat(id: &str) -> ChatRecord { chat(id, "meeting", false) } fn sectioned_directory(muted: bool, folders: Vec) -> Directory { let mut directory = Directory { folders, ..Default::default() }; directory.section_settings.set(ChatSection::Muted, muted); directory } fn section_ids(sections: &[Section]) -> Vec<&str> { sections.iter().map(|section| section.id.as_str()).collect() } fn item_ids(section: &Section) -> Vec<&str> { section.items.iter().map(|item| item.id.as_str()).collect() } fn input<'a>( chats: &'a [ChatRecord], directory: &'a Directory, collapsed: &'a HashSet, ) -> SectionInput<'a> { typing_input(chats, directory, collapsed, &NO_TYPING) } static NO_EXPANDED: std::sync::LazyLock> = std::sync::LazyLock::new(HashSet::new); static NO_TYPING: std::sync::LazyLock = std::sync::LazyLock::new(TypingState::default); fn typing_input<'a>( chats: &'a [ChatRecord], directory: &'a Directory, collapsed: &'a HashSet, typing: &'a TypingState, ) -> SectionInput<'a> { SectionInput { chats, directory, collapsed, expanded_lists: &NO_EXPANDED, typing, now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(), offset: FixedOffset::east_opt(0).unwrap(), } } #[test] fn next_chat_is_the_following_row_then_the_previous_one() { let chats = [ chat("a", "group", false), chat("b", "group", false), chat("c", "group", false), ]; let directory = Directory::default(); let collapsed = HashSet::new(); let sections = build_sections(&input(&chats, &directory, &collapsed)); assert_eq!(next_chat_id(§ions, "a"), Some("b".to_owned())); assert_eq!(next_chat_id(§ions, "c"), Some("b".to_owned())); assert_eq!(next_chat_id(§ions, "zzz"), None); let single = [chat("a", "group", false)]; let sections = build_sections(&input(&single, &directory, &collapsed)); assert_eq!(next_chat_id(§ions, "a"), None); } #[test] fn stepping_follows_the_visible_order_without_wrapping() { let ids = ["a", "b", "c"]; assert_eq!(step_id(&ids, Some("a"), Step::Next), Some("b".to_owned())); assert_eq!( step_id(&ids, Some("b"), Step::Previous), Some("a".to_owned()) ); assert_eq!(step_id(&ids, Some("c"), Step::Next), None); assert_eq!(step_id(&ids, Some("a"), Step::Previous), None); assert_eq!(step_id(&ids, None, Step::Next), Some("a".to_owned())); assert_eq!( step_id(&ids, Some("gone"), Step::Previous), Some("c".to_owned()) ); assert_eq!(step_id(&[], None, Step::Next), None); } #[test] fn unread_stepping_skips_read_chats_in_both_directions() { let directory = Directory::default(); let collapsed = HashSet::new(); let chats = [ chat("a", "group", true), chat("b", "group", false), chat("c", "group", true), chat("d", "group", false), ]; let sections = build_sections(&input(&chats, &directory, &collapsed)); let unread: Vec<&str> = visible_chat_ids(§ions) .into_iter() .filter(|id| *id == "a" || *id == "c") .collect(); let (first_unread, last_unread) = (unread[0], unread[1]); assert_eq!( step_unread_id(§ions, None, Step::Next).as_deref(), Some(first_unread) ); assert_eq!(step_unread_id(§ions, Some(last_unread), Step::Next), None); assert_eq!( step_unread_id(§ions, Some(last_unread), Step::Previous).as_deref(), Some(first_unread) ); assert_eq!( step_unread_id(§ions, None, Step::Previous).as_deref(), Some(last_unread) ); } #[test] fn visible_chats_skip_collapsed_sections_and_see_more_rows() { let mut chats = vec![chat("fav", "group", false), chat("hid", "group", false)]; chats.extend((0..7).map(|index| muted_chat(&format!("m{index}")))); chats.push(chat("other", "group", false)); let directory = sectioned_directory( true, vec![ folder("fav-folder", FolderKind::Favorites, &["fav"]), folder("work", FolderKind::UserCreated, &["hid"]), folder("recent", FolderKind::Recent, &[]), folder("muted-folder", FolderKind::Muted, &[]), ], ); let mut collapsed = HashSet::new(); let sections = build_sections(&input(&chats, &directory, &collapsed)); assert_eq!( visible_chat_ids(§ions), vec!["fav", "hid", "other", "m0", "m1", "m2", "m3", "m4"] ); collapsed.insert("work".to_owned()); collapsed.insert("muted-folder".to_owned()); let sections = build_sections(&input(&chats, &directory, &collapsed)); assert_eq!(visible_chat_ids(§ions), vec!["fav", "other"]); } fn team( id: &str, hidden: bool, channel_ids: &[&str], hidden_channel_ids: &[&str], ) -> SidebarTeam { SidebarTeam { rights: Default::default(), team: store::TeamRecord { id: id.into(), name: id.into(), }, channels: channel_ids .iter() .map(|channel_id| ChannelRecord { id: (*channel_id).into(), team_id: id.into(), name: (*channel_id).into(), membership_type: None, last_message_at: None, unread: false, }) .collect(), hidden, hidden_channel_ids: hidden_channel_ids .iter() .map(|id| (*id).to_owned()) .collect(), notifications: HashMap::new(), mentions: Default::default(), } } fn with_unread(mut entry: SidebarTeam, unread_ids: &[&str]) -> SidebarTeam { for channel in &mut entry.channels { channel.unread = unread_ids.contains(&channel.id.as_str()); } entry } #[test] fn unread_shown_channel_is_bold_and_highlighted() { let bold = NameStyle { weight: NameWeight::Bold, highlighted: true, }; let plain = NameStyle { weight: NameWeight::Regular, highlighted: false, }; assert_eq!(channel_name_style(true, true, false), bold); assert_eq!(channel_name_style(false, true, false), plain); assert_eq!(channel_name_style(true, false, false), plain); assert_eq!( channel_name_style(true, true, true), NameStyle { weight: NameWeight::Regular, highlighted: true, } ); } #[test] fn collapsed_team_with_an_unread_shown_channel_is_semibold() { let entry = with_unread(team("t1", false, &["a", "b"], &["b"]), &["a"]); let semibold = NameStyle { weight: NameWeight::Semibold, highlighted: true, }; assert_eq!(team_name_style(&entry, false), semibold); assert_eq!(team_name_style(&entry, true), NameStyle::PLAIN); let only_hidden = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]); assert_eq!(team_name_style(&only_hidden, false), NameStyle::PLAIN); } #[test] fn muted_channel_shows_no_unread_unless_personally_mentioned() { let mut entry = with_unread(team("t1", false, &["a"], &[]), &["a"]); entry.notifications.insert( "a".into(), store::ChannelNotifications { level: ChannelNotificationLevel::Off, include_replies: false, }, ); assert!(!channel_shows_unread(&entry, &entry.channels[0])); assert_eq!(team_name_style(&entry, false), NameStyle::PLAIN); entry.mentions.insert( "a".into(), store::ChannelMentions { personal: 1, ..Default::default() }, ); assert!(channel_shows_unread(&entry, &entry.channels[0])); } #[test] fn rail_dot_counts_shown_channels_of_shown_teams_only() { let sidebar = |teams: Vec| Sidebar { teams, ..Sidebar::default() }; let hidden_channel = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]); let hidden_team = with_unread(team("t2", true, &["c"], &[]), &["c"]); assert!(!any_unread_channel(&sidebar(vec![ hidden_channel, hidden_team ]))); let shown = with_unread(team("t1", false, &["a"], &[]), &["a"]); let both = sidebar(vec![shown]); assert!(any_unread_channel(&both)); assert!(channel_unread(&both, "a")); assert!(!channel_unread(&both, "missing")); } #[test] fn visible_channels_list_pinned_first_then_open_teams() { let teams = [ team("t1", false, &["a", "b", "c"], &["b"]), team("t2", false, &["d", "e"], &[]), team("t3", true, &["f"], &[]), ]; let pinned = ["e".to_owned(), "missing".to_owned()]; let order = |selected: Option<&str>, hidden_teams_open: bool, collapsed: &[&str], revealed: &[&str]| { let to_set = |ids: &[&str]| { ids.iter() .map(|id| (*id).to_owned()) .collect::>() }; let (collapsed, revealed) = (to_set(collapsed), to_set(revealed)); let input = ChannelOrderInput { teams: &teams, pinned_ids: &pinned, collapsed_teams: &collapsed, revealed_channel_teams: &revealed, hidden_teams_open, selected_channel: selected, }; visible_channel_ids(&input) .into_iter() .map(str::to_owned) .collect::>() }; assert_eq!(order(None, false, &[], &[]), vec!["e", "a", "c", "d"]); assert_eq!( order(Some("b"), false, &[], &[]), vec!["e", "a", "b", "c", "d"] ); assert_eq!( order(Some("f"), false, &[], &[]), vec!["e", "a", "c", "d", "f"] ); assert_eq!(order(None, true, &[], &[]), vec!["e", "a", "c", "d", "f"]); assert_eq!( order(None, true, &["t2"], &["t1"]), vec!["e", "a", "c", "b", "f"] ); } fn with_mentions(mut entry: SidebarTeam, mentions: &[(&str, u32, u32, u32)]) -> SidebarTeam { for (channel_id, personal, channel, team) in mentions { entry.mentions.insert( (*channel_id).to_owned(), store::ChannelMentions { personal: *personal, channel: *channel, team: *team, }, ); } entry } #[test] fn channel_badges_prefer_the_count_then_channel_then_team() { let entry = with_mentions( team("t", false, &["a", "b", "c", "d"], &[]), &[("a", 2, 1, 1), ("b", 0, 3, 1), ("c", 0, 0, 1)], ); assert_eq!(channel_badge(&entry, "a"), Some(MentionBadge::Count(2))); assert_eq!(channel_badge(&entry, "b"), Some(MentionBadge::Channel)); assert_eq!(channel_badge(&entry, "c"), Some(MentionBadge::Team)); assert_eq!(channel_badge(&entry, "d"), None); } #[test] fn the_collapsed_team_sums_counts_of_all_channels_and_icons_of_shown_ones() { let entry = with_unread( with_mentions( team("t", false, &["a", "b", "c"], &["b", "c"]), &[("a", 1, 0, 0), ("b", 2, 0, 0), ("c", 0, 1, 0)], ), &["a", "b", "c"], ); assert_eq!(team_badge(&entry, false), Some(MentionBadge::Count(3))); assert_eq!(team_badge(&entry, true), None); let icons_only = with_unread( with_mentions( team("t", false, &["a", "c"], &["c"]), &[("a", 0, 0, 1), ("c", 0, 1, 0)], ), &["a", "c"], ); assert_eq!(team_badge(&icons_only, false), Some(MentionBadge::Team)); let read = with_mentions(team("t", false, &["a"], &[]), &[("a", 1, 0, 0)]); assert_eq!(team_badge(&read, false), None); } #[test] fn a_hidden_channel_with_a_personal_mention_is_pulled_into_the_list() { let entry = with_unread( with_mentions( team("t", false, &["a", "b", "c"], &["b", "c"]), &[("b", 1, 0, 0), ("c", 0, 1, 0)], ), &["b", "c"], ); assert!(channel_shown(&entry, "b")); assert!(!channel_shown(&entry, "c")); assert!(team_has_unread(&entry)); let rows = team_channel_rows(&entry, false, false, |_| false); let shown: Vec<&str> = rows .shown .iter() .map(|channel| channel.id.as_str()) .collect(); assert_eq!(shown, ["a", "b"]); assert_eq!(rows.hidden_count, 1); assert!(rows.revealed.is_empty()); } #[test] fn a_hidden_team_with_a_hoisted_channel_shows_only_that_channel_in_the_main_list() { let teams = [ team("t1", false, &["a"], &[]), with_mentions(team("t2", true, &["b", "c"], &["c"]), &[("c", 1, 0, 0)]), ]; assert!(team_hoisted(&teams[1])); assert!(!team_hoisted(&teams[0])); let rows = team_channel_rows(&teams[1], true, true, |_| true); let shown: Vec<&str> = rows .shown .iter() .map(|channel| channel.id.as_str()) .collect(); assert_eq!(shown, ["c"]); assert_eq!(rows.hidden_count, 0); let empty = HashSet::new(); let input = ChannelOrderInput { teams: &teams, pinned_ids: &[], collapsed_teams: &empty, revealed_channel_teams: &empty, hidden_teams_open: false, selected_channel: None, }; assert_eq!(visible_channel_ids(&input), ["a", "c"]); let open = ChannelOrderInput { hidden_teams_open: true, ..input }; assert_eq!(visible_channel_ids(&open), ["a", "c", "b"]); } #[test] fn muted_chats_stay_out_of_unread_counts() { let mut quiet = chat("a", "group", true); quiet.muted = true; let chats = [quiet, chat("b", "group", true)]; assert_eq!(unread_chat_count(&chats), 1); let directory = sectioned_directory(true, Vec::new()); let collapsed = HashSet::new(); let sections = build_sections(&input(&chats, &directory, &collapsed)); assert_eq!(sections[0].unread_chats, 1); assert_eq!(sections[1].kind, SectionKind::Muted); assert!(sections[1].items[0].muted); assert!(sections[1].items[0].unread.is_unread()); } #[test] fn preview_prefix_is_you_for_own_and_first_name_for_groups() { let mut group = chat("g", "group", false); group.last_message_preview = Some("Hello".into()); group.last_message_sender_id = Some("ada".into()); group.last_message_sender_name = Some("Ada Example".into()); assert_eq!( preview_for(&group, Some(&me())), Preview::Text { prefix: Some("Ada".into()), text: "Hello".into() } ); group.last_message_sender_id = Some("me".into()); assert_eq!( preview_for(&group, Some(&me())), Preview::Text { prefix: Some("You".into()), text: "Hello".into() } ); let mut direct = chat("d", "oneOnOne", false); direct.last_message_preview = Some("Hi".into()); direct.last_message_sender_id = Some("ada".into()); direct.last_message_sender_name = Some("Ada Example".into()); assert_eq!( preview_for(&direct, Some(&me())), Preview::Text { prefix: None, text: "Hi".into() } ); } #[test] fn deleted_and_blank_previews() { let mut deleted = chat("d", "group", false); deleted.last_message_deleted = true; deleted.last_message_preview = Some("secret".into()); assert_eq!(preview_for(&deleted, None), Preview::Deleted); assert_eq!( preview_for(&chat("e", "group", false), None), Preview::Empty ); } #[test] fn sections_follow_folder_order_and_leave_the_rest_for_others() { let chats = vec![ chat("a", "group", false), chat("b", "oneOnOne", true), chat("c", "group", false), chat("d", "group", false), ]; let directory = Directory { me: Some(me()), folders: vec![ folder("fav", FolderKind::Favorites, &["c"]), folder("work", FolderKind::UserCreated, &["b", "gone", "a"]), folder("todo", FolderKind::UserCreated, &[]), ], ..Default::default() }; let collapsed = HashSet::new(); let sections = build_sections(&input(&chats, &directory, &collapsed)); let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect(); assert_eq!(ids, vec!["fav", "work", "todo", OTHERS_ID]); let work: Vec<&str> = sections[1] .items .iter() .map(|item| item.id.as_str()) .collect(); assert_eq!(work, vec!["b", "a"]); assert_eq!(sections[1].count, 2); assert_eq!(sections[2].count, 0); assert!(sections[2].show_empty_hint); let others: Vec<&str> = sections[3] .items .iter() .map(|item| item.id.as_str()) .collect(); assert_eq!(others, vec!["d"]); assert!(!sections[3].show_empty_hint); } #[test] fn collapsed_sections_keep_the_aggregated_unread() { let chats = vec![ chat("a", "group", true), chat("b", "group", true), chat("c", "group", false), ]; let directory = Directory { folders: vec![folder("work", FolderKind::UserCreated, &["a", "b", "c"])], ..Default::default() }; let collapsed: HashSet = ["work".to_owned()].into(); let sections = build_sections(&input(&chats, &directory, &collapsed)); assert!(sections[0].collapsed); assert_eq!(sections[0].unread_chats, 2); assert_eq!(sections[0].count, 3); assert!(!sections[0].show_empty_hint); } #[test] fn collapsed_empty_folder_hides_the_hint() { let directory = Directory { folders: vec![folder("todo", FolderKind::UserCreated, &[])], ..Default::default() }; let collapsed: HashSet = ["todo".to_owned()].into(); let sections = build_sections(&input(&[], &directory, &collapsed)); assert!(!sections[0].show_empty_hint); } #[test] fn favorites_without_a_server_name_say_angeheftet() { let mut favorites = folder("fav", FolderKind::Favorites, &[]); favorites.name = String::new(); let directory = Directory { folders: vec![favorites], ..Default::default() }; let sections = build_sections(&input(&[], &directory, &HashSet::new())); assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME); } #[test] fn the_importance_marker_shows_only_while_the_chat_is_unread() { let chats = vec![chat("a", "group", true), chat("b", "group", false)]; let mut directory = Directory::default(); directory .unread_importance .insert("a".into(), MessageImportance::Urgent); directory .unread_importance .insert("b".into(), MessageImportance::High); let collapsed = HashSet::new(); let context = input(&chats, &directory, &collapsed); assert_eq!( chat_item(&chats[0], &context, None).importance, MessageImportance::Urgent ); assert_eq!( chat_item(&chats[1], &context, None).importance, MessageImportance::Normal ); } #[test] fn unread_is_a_count_when_known_else_a_dot() { let chats = vec![ chat("a", "group", true), chat("b", "group", true), chat("c", "group", false), ]; let mut directory = Directory::default(); directory.unread_counts.insert("a".into(), 5); let collapsed = HashSet::new(); let context = input(&chats, &directory, &collapsed); assert_eq!( chat_item(&chats[0], &context, None).unread, Unread::Count(5) ); assert_eq!(chat_item(&chats[1], &context, None).unread, Unread::Dot); assert_eq!(chat_item(&chats[2], &context, None).unread, Unread::None); assert_eq!(unread_chat_count(&chats), 2); } #[test] fn one_on_one_has_presence_and_a_single_face_groups_have_a_pair() { let directory = Directory { me: Some(me()), ..Default::default() }; let collapsed = HashSet::new(); let chats = vec![chat("d", "oneOnOne", false), chat("g", "group", false)]; let context = input(&chats, &directory, &collapsed); let direct = chat_item(&chats[0], &context, None); assert_eq!(direct.presence_user.as_deref(), Some("ada")); assert!( matches!(direct.avatar, AvatarSpec::Single(ref face) if face.name == "Ada Example") ); let group = chat_item(&chats[1], &context, None); assert_eq!(group.presence_user, None); assert!(matches!(group.avatar, AvatarSpec::Pair(..))); assert_eq!( avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting ); } #[test] fn the_notes_chat_shows_my_face_and_my_presence() { let directory = Directory { me: Some(me()), ..Default::default() }; let collapsed = HashSet::new(); let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false); notes.title = "Me Myself (You)".into(); notes .members .retain(|member| member.user_id.as_deref() == Some("me")); let chats = vec![notes]; let context = input(&chats, &directory, &collapsed); let item = chat_item(&chats[0], &context, None); assert_eq!(item.title, "Me Myself (You)"); assert_eq!(item.presence_user.as_deref(), Some("me")); assert!( matches!(item.avatar, AvatarSpec::Single(ref face) if face.user_id.as_deref() == Some("me")) ); } #[test] fn a_one_on_one_with_a_bot_shows_the_bot_tile_and_no_presence() { let directory = Directory { me: Some(me()), ..Default::default() }; let collapsed = HashSet::new(); let mut echo = chat("echo", "oneOnOne", false); echo.title = "Echo".into(); echo.members.truncate(1); echo.members.push(MemberRecord { user_id: Some("28:bot-echo".into()), display_name: "Echo".into(), }); echo.last_message_preview = Some("Recording is ready".into()); let chats = vec![echo]; let context = input(&chats, &directory, &collapsed); let item = chat_item(&chats[0], &context, None); assert_eq!(item.title, "Echo"); assert_eq!(item.presence_user, None); assert!( matches!(item.avatar, AvatarSpec::Bot(ref face) if face.user_id.as_deref() == Some("28:bot-echo")) ); assert_eq!(item.preview, Preview::Event("Recording is ready".into())); } #[test] fn an_event_label_from_a_person_stays_plain_text() { let mut direct = chat("d", "oneOnOne", false); direct.last_message_preview = Some("Recording is ready".into()); direct.last_message_sender_id = Some("ada".into()); assert_eq!( preview_for(&direct, Some(&me())), Preview::Text { prefix: None, text: "Recording is ready".into() } ); } #[test] fn typing_replaces_the_preview_even_in_muted_chats() { let mut direct = chat("d", "oneOnOne", false); direct.last_message_preview = Some("Earlier".into()); direct.muted = true; let group = chat("g", "group", false); let chats = vec![direct, group]; let directory = Directory::default(); let collapsed = HashSet::new(); let now = std::time::Instant::now(); let mut typing = TypingState::default(); typing.start("d", "ada", "Ada Example", now, Utc::now()); typing.start("g", "ada", "Ada Example", now, Utc::now()); let context = typing_input(&chats, &directory, &collapsed, &typing); assert_eq!( chat_item(&chats[0], &context, None).preview, Preview::Typing("typing...".into()) ); assert_eq!( chat_item(&chats[1], &context, None).preview, Preview::Typing("Ada is typing...".into()) ); typing.clear("d", "ada"); let context = typing_input(&chats, &directory, &collapsed, &typing); assert_eq!( chat_item(&chats[0], &context, None).preview, Preview::Text { prefix: None, text: "Earlier".into() } ); } #[test] fn time_label_uses_the_list_rules() { let chats = vec![chat("a", "group", false)]; let directory = Directory::default(); let collapsed = HashSet::new(); let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None); assert_eq!(item.time_label, "09:30"); } #[test] fn muted_chats_leave_others_unless_pinned_or_in_a_custom_section_and_meeting_chats_stay() { let chats = vec![ chat("plain", "group", false), muted_chat("quiet"), muted_chat("pinned-quiet"), meeting_chat("sync"), meeting_chat("custom-sync"), ChatRecord { muted: true, ..meeting_chat("quiet-sync") }, ]; let directory = sectioned_directory( true, vec![ folder("fav", FolderKind::Favorites, &["pinned-quiet"]), folder("work", FolderKind::UserCreated, &["custom-sync"]), ], ); let sections = build_sections(&input(&chats, &directory, &HashSet::new())); assert_eq!( section_ids(§ions), vec!["fav", "work", OTHERS_ID, MUTED_ID] ); assert_eq!(item_ids(§ions[0]), vec!["pinned-quiet"]); assert_eq!(item_ids(§ions[1]), vec!["custom-sync"]); assert_eq!(item_ids(§ions[2]), vec!["plain", "sync"]); assert_eq!(item_ids(§ions[3]), vec!["quiet", "quiet-sync"]); assert_eq!(sections[3].kind, SectionKind::Muted); assert_eq!(sections[3].count, 2); } #[test] fn turning_the_muted_section_off_puts_its_chats_back_in_others() { let chats = vec![muted_chat("quiet"), meeting_chat("sync")]; let directory = sectioned_directory(false, Vec::new()); let sections = build_sections(&input(&chats, &directory, &HashSet::new())); assert_eq!(section_ids(§ions), vec![OTHERS_ID]); assert_eq!(item_ids(§ions[0]), vec!["quiet", "sync"]); } #[test] fn muted_chats_stay_in_others_until_the_user_turns_the_section_on() { let chats = vec![muted_chat("quiet"), meeting_chat("sync")]; let directory = Directory::default(); let sections = build_sections(&input(&chats, &directory, &HashSet::new())); assert_eq!(section_ids(§ions), vec![OTHERS_ID]); assert_eq!(item_ids(§ions[0]), vec!["quiet", "sync"]); assert!(sections[0].items[0].muted); assert_eq!(sections[0].items[0].avatar, AvatarSpec::Muted); assert_eq!(sections[0].items[1].avatar, AvatarSpec::Meeting); } #[test] fn a_muted_chat_in_others_stays_bold_without_a_count() { let mut quiet = muted_chat("quiet"); quiet.unread = true; let chats = vec![quiet]; let mut directory = Directory::default(); directory.unread_counts.insert("quiet".into(), 4); let sections = build_sections(&input(&chats, &directory, &HashSet::new())); assert_eq!(sections[0].kind, SectionKind::Others); assert_eq!(sections[0].items[0].unread, Unread::Silent); assert_eq!(sections[0].unread_chats, 0); } #[test] fn older_chats_load_only_when_the_end_of_other_chats_is_on_screen_once_per_scroll_position() { assert!(wants_older_chats(Some(900.), 1000., 0., None, false)); assert!(!wants_older_chats(Some(1500.), 1000., 0., None, false)); assert!(!wants_older_chats(None, 1000., 0., None, false)); assert!(!wants_older_chats(Some(900.), 1000., 0., Some(0.), false)); assert!(wants_older_chats(Some(900.), 1000., 120., Some(0.), false)); } #[test] fn a_running_load_never_consumes_the_trigger() { assert!(!wants_older_chats(Some(900.), 1000., 0., None, true)); } #[test] fn the_trigger_resets_when_a_load_ends_or_more_chats_appear_but_not_while_idle() { assert!(older_chats_trigger_resets((true, true), (true, false))); assert!(older_chats_trigger_resets((true, true), (false, false))); assert!(older_chats_trigger_resets((false, false), (true, false))); assert!(!older_chats_trigger_resets((true, false), (true, false))); assert!(!older_chats_trigger_resets((true, false), (true, true))); assert!(!older_chats_trigger_resets((false, false), (false, false))); } #[test] fn empty_system_sections_are_hidden() { let chats = vec![chat("a", "group", false)]; let directory = sectioned_directory(true, Vec::new()); let sections = build_sections(&input(&chats, &directory, &HashSet::new())); assert_eq!(section_ids(§ions), vec![OTHERS_ID]); } #[test] fn sections_follow_the_server_folder_order_with_system_folders() { let chats = vec![ chat("a", "group", false), muted_chat("quiet"), meeting_chat("sync"), ]; let directory = sectioned_directory( true, vec![ folder("muted-id", FolderKind::Muted, &[]), folder("fav", FolderKind::Favorites, &[]), folder("recent-id", FolderKind::Recent, &[]), folder("meeting-id", FolderKind::Meeting, &[]), ], ); let collapsed: HashSet = ["muted-id".to_owned()].into(); let sections = build_sections(&input(&chats, &directory, &collapsed)); assert_eq!(section_ids(§ions), vec!["muted-id", "fav", "recent-id"]); assert!(sections[0].collapsed); assert_eq!(sections[0].name, MUTED_NAME); assert_eq!(item_ids(§ions[2]), vec!["a", "sync"]); } #[test] fn newest_five_show_then_see_more_expands_and_see_less_collapses() { let chats: Vec = (0..8) .map(|index| muted_chat(&format!("m{index}"))) .collect(); let directory = sectioned_directory(true, Vec::new()); let collapsed = HashSet::new(); let sections = build_sections(&input(&chats, &directory, &collapsed)); let muted = §ions[1]; assert_eq!(item_ids(muted), vec!["m0", "m1", "m2", "m3", "m4"]); assert_eq!(muted.count, 8); assert_eq!(muted.hidden_count, 3); assert!(!muted.list_expanded); let expanded: HashSet = [MUTED_ID.to_owned()].into(); let mut context = input(&chats, &directory, &collapsed); context.expanded_lists = &expanded; let sections = build_sections(&context); let muted = §ions[1]; assert_eq!(muted.items.len(), 8); assert_eq!(muted.hidden_count, 0); assert!(muted.list_expanded); } #[test] fn five_chats_need_no_see_more_even_when_marked_expanded() { let chats: Vec = (0..5) .map(|index| muted_chat(&format!("m{index}"))) .collect(); let directory = sectioned_directory(true, Vec::new()); let collapsed = HashSet::new(); let expanded: HashSet = [MUTED_ID.to_owned()].into(); let mut context = input(&chats, &directory, &collapsed); context.expanded_lists = &expanded; let muted = &build_sections(&context)[1]; assert_eq!(muted.hidden_count, 0); assert!(!muted.list_expanded); } #[test] fn muted_section_keeps_unread_bold_without_a_badge_or_a_count() { let mut quiet = muted_chat("quiet"); quiet.unread = true; let chats = vec![ quiet, ChatRecord { muted: true, ..meeting_chat("x") }, ]; let mut directory = sectioned_directory(true, Vec::new()); directory.unread_counts.insert("quiet".into(), 4); let sections = build_sections(&input(&chats, &directory, &HashSet::new())); let muted = §ions[1]; assert_eq!(muted.items[0].unread, Unread::Silent); assert!(muted.items[0].unread.is_unread()); assert_eq!(muted.unread_chats, 0); assert_eq!(unread_chat_count(&chats), 0); } #[test] fn meeting_chats_keep_their_unread_count_in_others() { let mut sync = meeting_chat("sync"); sync.unread = true; let chats = vec![sync]; let mut directory = sectioned_directory(true, Vec::new()); directory.unread_counts.insert("sync".into(), 3); let sections = build_sections(&input(&chats, &directory, &HashSet::new())); assert_eq!(sections[0].id, OTHERS_ID); assert_eq!(sections[0].items[0].unread, Unread::Count(3)); assert_eq!(sections[0].unread_chats, 1); } }