BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / sidebar_model.rs

sidebar_model.rs

sidebar_model.rs 53.3 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2
3use app_ui_kit::widgets::Unread;
4use chrono::{DateTime, FixedOffset, Utc};
5use store::{ChannelRecord, ChatRecord, MessageImportance, Sidebar, SidebarTeam, is_bot_id};
6use teams_core::{ChatSection, is_event_preview};
7
8use crate::app_state::chat_title;
9use crate::data::{
10 Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others,
11 unread_count, unread_importance_of,
12};
13use crate::format;
14use crate::typing::{TypingState, preview_label};
15
16pub const FAVORITES_FALLBACK_NAME: &str = "Favorites";
17pub const OTHERS_NAME: &str = "Other chats";
18pub const OTHERS_ID: &str = "others";
19pub const MUTED_NAME: &str = "Muted";
20pub const MUTED_ID: &str = "muted_chats";
21pub const SECTION_PAGE_SIZE: usize = 5;
22pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
23pub const DELETED_PREVIEW: &str = "Message deleted";
24pub const DELETED_CHAT_PREVIEW: &str = "This message was deleted";
25const OWN_PREFIX: &str = "You";
26const GROUP_KIND: &str = "group";
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum Preview {
30 Empty,
31 Deleted,
32 Event(String),
33 Typing(String),
34 Text {
35 prefix: Option<String>,
36 text: String,
37 },
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Face {
42 pub user_id: Option<String>,
43 pub name: String,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum AvatarSpec {
48 Single(Face),
49 Pair(Face, Face),
50 Bot(Face),
51 Meeting,
52 Muted,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct ChatItem {
57 pub id: String,
58 pub title: String,
59 pub time_label: String,
60 pub preview: Preview,
61 pub unread: Unread,
62 pub importance: MessageImportance,
63 pub muted: bool,
64 pub is_group: bool,
65 pub member_count: usize,
66 pub avatar: AvatarSpec,
67 pub presence_user: Option<String>,
68 pub folder_id: Option<String>,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum SectionKind {
73 Favorites,
74 Folder,
75 Others,
76 Muted,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct Section {
81 pub id: String,
82 pub name: String,
83 pub kind: SectionKind,
84 pub collapsed: bool,
85 pub count: usize,
86 pub unread_chats: u32,
87 pub items: Vec<ChatItem>,
88 pub hidden_count: usize,
89 pub list_expanded: bool,
90 pub show_empty_hint: bool,
91}
92
93pub struct SectionInput<'a> {
94 pub chats: &'a [ChatRecord],
95 pub directory: &'a Directory,
96 pub collapsed: &'a HashSet<String>,
97 pub expanded_lists: &'a HashSet<String>,
98 pub typing: &'a TypingState,
99 pub now: DateTime<Utc>,
100 pub offset: FixedOffset,
101}
102
103pub fn preview_for(chat: &ChatRecord, me: Option<&Person>) -> Preview {
104 if chat.last_message_deleted {
105 return Preview::Deleted;
106 }
107 let Some(text) = chat
108 .last_message_preview
109 .as_deref()
110 .map(str::trim)
111 .filter(|text| !text.is_empty())
112 else {
113 return Preview::Empty;
114 };
115 let sender_id = chat
116 .last_message_sender_id
117 .as_deref()
118 .filter(|sender_id| !sender_id.is_empty());
119 if sender_id.is_none() && is_event_preview(text) {
120 return Preview::Event(text.to_owned());
121 }
122 let from_me = match (sender_id, me) {
123 (Some(sender), Some(me)) => sender == me.user_id,
124 _ => false,
125 };
126 let prefix = if from_me {
127 Some(OWN_PREFIX.to_owned())
128 } else if is_one_on_one(chat) {
129 None
130 } else {
131 chat.last_message_sender_name
132 .as_deref()
133 .map(|name| format::first_name(name).to_owned())
134 .filter(|name| !name.is_empty())
135 };
136 Preview::Text {
137 prefix,
138 text: text.to_owned(),
139 }
140}
141
142pub fn avatar_for(chat: &ChatRecord, me: Option<&Person>) -> AvatarSpec {
143 if chat.kind.eq_ignore_ascii_case("meeting") {
144 return AvatarSpec::Meeting;
145 }
146 let faces = face_members(chat, me);
147 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
148 if let Some(bot) = one_on_one_bot(chat, me) {
149 return AvatarSpec::Bot(face(bot));
150 }
151 if is_one_on_one(chat) || faces.len() < 2 {
152 return AvatarSpec::Single(match faces.into_iter().next() {
153 Some(first) => face(first),
154 None => Face {
155 user_id: None,
156 name: chat_title(chat),
157 },
158 });
159 }
160 let mut iterator = faces.into_iter();
161 let (first, second) = (iterator.next(), iterator.next());
162 match (first, second) {
163 (Some(first), Some(second)) => AvatarSpec::Pair(face(first), face(second)),
164 _ => AvatarSpec::Single(Face {
165 user_id: None,
166 name: chat_title(chat),
167 }),
168 }
169}
170
171pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<&str>) -> ChatItem {
172 let me = input.directory.me.as_ref();
173 let unread = if chat.unread {
174 unread_count(input.directory, chat)
175 .filter(|count| *count > 0)
176 .map_or(Unread::Dot, Unread::Count)
177 } else {
178 Unread::None
179 };
180 let presence_user = (is_one_on_one(chat) && !chat.muted)
181 .then(|| {
182 others(chat, me)
183 .into_iter()
184 .find_map(|(user_id, _)| user_id)
185 })
186 .flatten()
187 .filter(|user_id| !is_bot_id(user_id));
188 let typing_names = input.typing.names(&chat.id);
189 let preview = if typing_names.is_empty() {
190 preview_for(chat, me)
191 } else {
192 Preview::Typing(preview_label(&typing_names, is_one_on_one(chat)))
193 };
194 ChatItem {
195 id: chat.id.clone(),
196 title: chat_title(chat),
197 time_label: chat
198 .last_message_at
199 .map(|time| {
200 format::list_time_label(
201 time,
202 input.now.with_timezone(&input.offset).date_naive(),
203 input.offset,
204 )
205 })
206 .unwrap_or_default(),
207 preview,
208 unread,
209 importance: if chat.unread {
210 unread_importance_of(input.directory, chat)
211 } else {
212 MessageImportance::Normal
213 },
214 muted: chat.muted,
215 is_group: chat.kind == GROUP_KIND,
216 member_count: chat.members.len(),
217 avatar: if chat.muted {
218 AvatarSpec::Muted
219 } else {
220 avatar_for(chat, me)
221 },
222 presence_user,
223 folder_id: folder_id.map(str::to_owned),
224 }
225}
226
227pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 {
228 chats
229 .iter()
230 .filter(|chat| chat.unread && !chat.muted)
231 .count() as u32
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum NameWeight {
236 Regular,
237 Semibold,
238 Bold,
239}
240
241/// Teams channel list: `highlighted` is colorNeutralForeground1, otherwise colorNeutralForeground3.
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243pub struct NameStyle {
244 pub weight: NameWeight,
245 pub highlighted: bool,
246}
247
248impl NameStyle {
249 const PLAIN: NameStyle = NameStyle {
250 weight: NameWeight::Regular,
251 highlighted: false,
252 };
253}
254
255pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyle {
256 if !unread || !shown {
257 return NameStyle::PLAIN;
258 }
259 NameStyle {
260 weight: if selected {
261 NameWeight::Regular
262 } else {
263 NameWeight::Bold
264 },
265 highlighted: true,
266 }
267}
268
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270pub enum MentionBadge {
271 Count(u32),
272 Channel,
273 Team,
274}
275
276/// Teams pulls a hidden channel into the list while it holds personal @mentions.
277pub fn channel_shown(team: &SidebarTeam, channel_id: &str) -> bool {
278 !team.hidden_channel_ids.iter().any(|id| id == channel_id)
279 || team.channel_mentions(channel_id).personal > 0
280}
281
282pub fn channel_hoisted(team: &SidebarTeam, channel_id: &str) -> bool {
283 team.hidden_channel_ids.iter().any(|id| id == channel_id)
284 && team.channel_mentions(channel_id).personal > 0
285}
286
287pub fn team_hoisted(team: &SidebarTeam) -> bool {
288 team.hidden
289 && team
290 .channels
291 .iter()
292 .any(|channel| channel_hoisted(team, &channel.id))
293}
294
295pub fn channel_badge(team: &SidebarTeam, channel_id: &str) -> Option<MentionBadge> {
296 let mentions = team.channel_mentions(channel_id);
297 if mentions.personal > 0 {
298 Some(MentionBadge::Count(mentions.personal))
299 } else if mentions.channel > 0 {
300 Some(MentionBadge::Channel)
301 } else if mentions.team > 0 {
302 Some(MentionBadge::Team)
303 } else {
304 None
305 }
306}
307
308/// The collapsed team row sums personal mentions of every channel, the icons only of shown channels.
309pub fn team_badge(team: &SidebarTeam, expanded: bool) -> Option<MentionBadge> {
310 if expanded || !team_has_unread(team) {
311 return None;
312 }
313 let personal: u32 = team
314 .mentions
315 .iter()
316 .filter(|(channel_id, _)| {
317 team.channels
318 .iter()
319 .any(|channel| &channel.id == *channel_id)
320 })
321 .map(|(_, mentions)| mentions.personal)
322 .sum();
323 if personal > 0 {
324 return Some(MentionBadge::Count(personal));
325 }
326 let shown = || {
327 team.channels
328 .iter()
329 .filter(|channel| channel_shown(team, &channel.id))
330 .map(|channel| team.channel_mentions(&channel.id))
331 };
332 if shown().any(|mentions| mentions.channel > 0) {
333 Some(MentionBadge::Channel)
334 } else if shown().any(|mentions| mentions.team > 0) {
335 Some(MentionBadge::Team)
336 } else {
337 None
338 }
339}
340
341pub fn team_has_unread(team: &SidebarTeam) -> bool {
342 team.channels
343 .iter()
344 .any(|channel| channel.unread && channel_shown(team, &channel.id))
345}
346
347pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {
348 if expanded || !team_has_unread(team) {
349 return NameStyle::PLAIN;
350 }
351 NameStyle {
352 weight: NameWeight::Semibold,
353 highlighted: true,
354 }
355}
356
357pub fn channel_unread(sidebar: &Sidebar, channel_id: &str) -> bool {
358 sidebar
359 .teams
360 .iter()
361 .flat_map(|team| team.channels.iter())
362 .any(|channel| channel.id == channel_id && channel.unread)
363}
364
365pub fn any_unread_channel(sidebar: &Sidebar) -> bool {
366 sidebar
367 .teams
368 .iter()
369 .filter(|team| !team.hidden)
370 .any(team_has_unread)
371}
372
373pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
374 let by_id: HashMap<&str, &ChatRecord> = input
375 .chats
376 .iter()
377 .map(|chat| (chat.id.as_str(), chat))
378 .collect();
379 let mut placed: HashSet<&str> = HashSet::new();
380 let mut built: Vec<Option<Section>> = input
381 .directory
382 .folders
383 .iter()
384 .map(|folder| {
385 let (kind, name) = match folder.kind {
386 FolderKind::Favorites => (
387 SectionKind::Favorites,
388 if folder.name.trim().is_empty() {
389 FAVORITES_FALLBACK_NAME.to_owned()
390 } else {
391 folder.name.clone()
392 },
393 ),
394 FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()),
395 FolderKind::Recent | FolderKind::Meeting | FolderKind::Muted => return None,
396 };
397 let items: Vec<ChatItem> = folder
398 .conversation_ids
399 .iter()
400 .filter_map(|id| by_id.get(id.as_str()).copied())
401 .filter(|chat| placed.insert(chat.id.as_str()))
402 .map(|chat| chat_item(chat, input, Some(&folder.id)))
403 .collect();
404 Some(section(folder.id.clone(), name, kind, items, input))
405 })
406 .collect();
407 let settings = &input.directory.section_settings;
408 let mut muted = Vec::new();
409 let mut rest = Vec::new();
410 for chat in input
411 .chats
412 .iter()
413 .filter(|chat| !placed.contains(chat.id.as_str()))
414 {
415 let item = chat_item(chat, input, None);
416 if chat.muted && settings.enabled(ChatSection::Muted) {
417 muted.push(item);
418 } else {
419 rest.push(item);
420 }
421 }
422 let folder_id = |kind: FolderKind, fallback: &str| {
423 input
424 .directory
425 .folders
426 .iter()
427 .find(|folder| folder.kind == kind)
428 .map_or_else(|| fallback.to_owned(), |folder| folder.id.clone())
429 };
430 let mut others = Some(section(
431 folder_id(FolderKind::Recent, OTHERS_ID),
432 OTHERS_NAME.to_owned(),
433 SectionKind::Others,
434 rest,
435 input,
436 ));
437 let mut muted = (!muted.is_empty()).then(|| {
438 section(
439 folder_id(FolderKind::Muted, MUTED_ID),
440 MUTED_NAME.to_owned(),
441 SectionKind::Muted,
442 muted,
443 input,
444 )
445 });
446 let mut sections = Vec::new();
447 for (folder, section) in input.directory.folders.iter().zip(&mut built) {
448 match folder.kind {
449 FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()),
450 FolderKind::Recent => sections.extend(others.take()),
451 FolderKind::Meeting => {}
452 FolderKind::Muted => sections.extend(muted.take()),
453 }
454 }
455 sections.extend(others);
456 sections.extend(muted);
457 sections
458}
459
460pub fn wants_older_chats(
461 others_end: Option<f32>,
462 viewport_bottom: f32,
463 scroll_top: f32,
464 last_trigger_top: Option<f32>,
465 loading: bool,
466) -> bool {
467 !loading
468 && others_end.is_some_and(|end| end <= viewport_bottom)
469 && last_trigger_top != Some(scroll_top)
470}
471
472pub fn older_chats_trigger_resets(previous: (bool, bool), current: (bool, bool)) -> bool {
473 let ((had_more, was_loading), (has_more, is_loading)) = (previous, current);
474 (was_loading && !is_loading) || (!had_more && has_more)
475}
476
477pub fn visible_chat_ids(sections: &[Section]) -> Vec<&str> {
478 sections
479 .iter()
480 .filter(|section| !section.collapsed)
481 .flat_map(|section| section.items.iter().map(|item| item.id.as_str()))
482 .collect()
483}
484
485pub fn next_chat_id(sections: &[Section], removed_id: &str) -> Option<String> {
486 let visible = visible_chat_ids(sections);
487 let position = visible.iter().position(|id| *id == removed_id)?;
488 visible
489 .get(position + 1)
490 .or_else(|| {
491 position
492 .checked_sub(1)
493 .and_then(|previous| visible.get(previous))
494 })
495 .map(|id| (*id).to_owned())
496}
497
498#[derive(Debug, Clone, Copy, PartialEq, Eq)]
499pub enum Step {
500 Previous,
501 Next,
502}
503
504pub fn step_id(ids: &[&str], current: Option<&str>, step: Step) -> Option<String> {
505 let position = current.and_then(|current| ids.iter().position(|id| *id == current));
506 let target = match (position, step) {
507 (Some(position), Step::Next) => position + 1,
508 (Some(position), Step::Previous) => position.checked_sub(1)?,
509 (None, Step::Next) => 0,
510 (None, Step::Previous) => ids.len().checked_sub(1)?,
511 };
512 ids.get(target).map(|id| (*id).to_owned())
513}
514
515pub struct ChannelOrderInput<'a> {
516 pub teams: &'a [SidebarTeam],
517 pub pinned_ids: &'a [String],
518 pub collapsed_teams: &'a HashSet<String>,
519 pub revealed_channel_teams: &'a HashSet<String>,
520 pub hidden_teams_open: bool,
521 pub selected_channel: Option<&'a str>,
522}
523
524pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {
525 let mut ids: Vec<&str> = Vec::new();
526 let mut push = |id: &'a str| {
527 if !ids.contains(&id) {
528 ids.push(id);
529 }
530 };
531 for pinned_id in input.pinned_ids {
532 let known = input
533 .teams
534 .iter()
535 .flat_map(|entry| entry.channels.iter())
536 .find(|channel| &channel.id == pinned_id);
537 if let Some(channel) = known {
538 push(&channel.id);
539 }
540 }
541 let holds_selection = |entry: &SidebarTeam| {
542 entry
543 .channels
544 .iter()
545 .any(|channel| Some(channel.id.as_str()) == input.selected_channel)
546 };
547 let hidden_teams_shown = input.hidden_teams_open
548 || input
549 .teams
550 .iter()
551 .any(|entry| entry.hidden && holds_selection(entry));
552 let main_teams = input
553 .teams
554 .iter()
555 .filter(|entry| !entry.hidden || team_hoisted(entry))
556 .map(|entry| (entry, entry.hidden));
557 let hidden_teams = input
558 .teams
559 .iter()
560 .filter(|entry| entry.hidden && hidden_teams_shown)
561 .map(|entry| (entry, false));
562 for (entry, hoisted_only) in main_teams.chain(hidden_teams) {
563 if input.collapsed_teams.contains(&entry.team.id) {
564 continue;
565 }
566 for channel_id in team_channel_ids(entry, hoisted_only, input) {
567 push(channel_id);
568 }
569 }
570 ids
571}
572
573fn team_channel_ids<'a>(
574 entry: &'a SidebarTeam,
575 hoisted_only: bool,
576 input: &ChannelOrderInput<'_>,
577) -> Vec<&'a str> {
578 let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
579 let rows = team_channel_rows(
580 entry,
581 hoisted_only,
582 input.revealed_channel_teams.contains(&entry.team.id),
583 is_selected,
584 );
585 rows.shown
586 .into_iter()
587 .chain(rows.revealed)
588 .map(|channel| channel.id.as_str())
589 .collect()
590}
591
592pub struct TeamChannelRows<'a> {
593 pub shown: Vec<&'a ChannelRecord>,
594 pub hidden_count: usize,
595 pub revealed: Vec<&'a ChannelRecord>,
596}
597
598/// `hoisted_only` is a hidden team pulled into the main list: it shows only its hoisted channels.
599pub fn team_channel_rows<'a>(
600 entry: &'a SidebarTeam,
601 hoisted_only: bool,
602 revealed: bool,
603 is_selected: impl Fn(&ChannelRecord) -> bool,
604) -> TeamChannelRows<'a> {
605 let shown: Vec<&ChannelRecord> = entry
606 .channels
607 .iter()
608 .filter(|channel| {
609 if hoisted_only {
610 channel_hoisted(entry, &channel.id)
611 } else {
612 is_selected(channel) || channel_shown(entry, &channel.id)
613 }
614 })
615 .collect();
616 if hoisted_only {
617 return TeamChannelRows {
618 shown,
619 hidden_count: 0,
620 revealed: Vec::new(),
621 };
622 }
623 let hidden: Vec<&ChannelRecord> = entry
624 .channels
625 .iter()
626 .filter(|channel| !shown.iter().any(|row| row.id == channel.id))
627 .collect();
628 TeamChannelRows {
629 shown,
630 hidden_count: hidden.len(),
631 revealed: if revealed { hidden } else { Vec::new() },
632 }
633}
634
635fn section(
636 id: String,
637 name: String,
638 kind: SectionKind,
639 mut items: Vec<ChatItem>,
640 input: &SectionInput<'_>,
641) -> Section {
642 let collapsed = input.collapsed.contains(&id);
643 let count = items.len();
644 let unread_chats = items
645 .iter()
646 .filter(|item| item.unread.is_unread() && !item.muted)
647 .count() as u32;
648 let paged = kind == SectionKind::Muted;
649 let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id);
650 let hidden_count = if paged && !list_expanded {
651 count.saturating_sub(SECTION_PAGE_SIZE)
652 } else {
653 0
654 };
655 items.truncate(count - hidden_count);
656 for item in items.iter_mut().filter(|item| item.muted) {
657 if item.unread.is_unread() {
658 item.unread = Unread::Silent;
659 }
660 }
661 Section {
662 collapsed,
663 count,
664 unread_chats,
665 hidden_count,
666 list_expanded,
667 show_empty_hint: items.is_empty()
668 && !collapsed
669 && matches!(kind, SectionKind::Favorites | SectionKind::Folder),
670 id,
671 name,
672 kind,
673 items,
674 }
675}
676
677#[cfg(test)]
678mod tests {
679 use chrono::TimeZone;
680 use store::MemberRecord;
681
682 use super::*;
683 use crate::data::FolderInfo;
684
685 fn me() -> Person {
686 Person {
687 user_id: "me".into(),
688 display_name: "Me Myself".into(),
689 }
690 }
691
692 fn chat(id: &str, kind: &str, unread: bool) -> ChatRecord {
693 ChatRecord {
694 id: id.into(),
695 kind: kind.into(),
696 title: id.to_uppercase(),
697 unread,
698 last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 7, 9, 30, 0).unwrap()),
699 members: vec![
700 MemberRecord {
701 user_id: Some("me".into()),
702 display_name: "Me Myself".into(),
703 },
704 MemberRecord {
705 user_id: Some("ada".into()),
706 display_name: "Ada Example".into(),
707 },
708 MemberRecord {
709 user_id: Some("bob".into()),
710 display_name: "Bob Sample".into(),
711 },
712 ],
713 ..Default::default()
714 }
715 }
716
717 fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo {
718 FolderInfo {
719 id: id.into(),
720 name: format!("name-{id}"),
721 kind,
722 expanded: None,
723 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
724 }
725 }
726
727 fn muted_chat(id: &str) -> ChatRecord {
728 ChatRecord {
729 muted: true,
730 ..chat(id, "group", false)
731 }
732 }
733
734 fn meeting_chat(id: &str) -> ChatRecord {
735 chat(id, "meeting", false)
736 }
737
738 fn sectioned_directory(muted: bool, folders: Vec<FolderInfo>) -> Directory {
739 let mut directory = Directory {
740 folders,
741 ..Default::default()
742 };
743 directory.section_settings.set(ChatSection::Muted, muted);
744 directory
745 }
746
747 fn section_ids(sections: &[Section]) -> Vec<&str> {
748 sections.iter().map(|section| section.id.as_str()).collect()
749 }
750
751 fn item_ids(section: &Section) -> Vec<&str> {
752 section.items.iter().map(|item| item.id.as_str()).collect()
753 }
754
755 fn input<'a>(
756 chats: &'a [ChatRecord],
757 directory: &'a Directory,
758 collapsed: &'a HashSet<String>,
759 ) -> SectionInput<'a> {
760 typing_input(chats, directory, collapsed, &NO_TYPING)
761 }
762
763 static NO_EXPANDED: std::sync::LazyLock<HashSet<String>> =
764 std::sync::LazyLock::new(HashSet::new);
765
766 static NO_TYPING: std::sync::LazyLock<TypingState> =
767 std::sync::LazyLock::new(TypingState::default);
768
769 fn typing_input<'a>(
770 chats: &'a [ChatRecord],
771 directory: &'a Directory,
772 collapsed: &'a HashSet<String>,
773 typing: &'a TypingState,
774 ) -> SectionInput<'a> {
775 SectionInput {
776 chats,
777 directory,
778 collapsed,
779 expanded_lists: &NO_EXPANDED,
780 typing,
781 now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),
782 offset: FixedOffset::east_opt(0).unwrap(),
783 }
784 }
785
786 #[test]
787 fn next_chat_is_the_following_row_then_the_previous_one() {
788 let chats = [
789 chat("a", "group", false),
790 chat("b", "group", false),
791 chat("c", "group", false),
792 ];
793 let directory = Directory::default();
794 let collapsed = HashSet::new();
795 let sections = build_sections(&input(&chats, &directory, &collapsed));
796 assert_eq!(next_chat_id(&sections, "a"), Some("b".to_owned()));
797 assert_eq!(next_chat_id(&sections, "c"), Some("b".to_owned()));
798 assert_eq!(next_chat_id(&sections, "zzz"), None);
799 let single = [chat("a", "group", false)];
800 let sections = build_sections(&input(&single, &directory, &collapsed));
801 assert_eq!(next_chat_id(&sections, "a"), None);
802 }
803
804 #[test]
805 fn stepping_follows_the_visible_order_without_wrapping() {
806 let ids = ["a", "b", "c"];
807 assert_eq!(step_id(&ids, Some("a"), Step::Next), Some("b".to_owned()));
808 assert_eq!(
809 step_id(&ids, Some("b"), Step::Previous),
810 Some("a".to_owned())
811 );
812 assert_eq!(step_id(&ids, Some("c"), Step::Next), None);
813 assert_eq!(step_id(&ids, Some("a"), Step::Previous), None);
814 assert_eq!(step_id(&ids, None, Step::Next), Some("a".to_owned()));
815 assert_eq!(
816 step_id(&ids, Some("gone"), Step::Previous),
817 Some("c".to_owned())
818 );
819 assert_eq!(step_id(&[], None, Step::Next), None);
820 }
821
822 #[test]
823 fn visible_chats_skip_collapsed_sections_and_see_more_rows() {
824 let mut chats = vec![chat("fav", "group", false), chat("hid", "group", false)];
825 chats.extend((0..7).map(|index| muted_chat(&format!("m{index}"))));
826 chats.push(chat("other", "group", false));
827 let directory = sectioned_directory(
828 true,
829 vec![
830 folder("fav-folder", FolderKind::Favorites, &["fav"]),
831 folder("work", FolderKind::UserCreated, &["hid"]),
832 folder("recent", FolderKind::Recent, &[]),
833 folder("muted-folder", FolderKind::Muted, &[]),
834 ],
835 );
836 let mut collapsed = HashSet::new();
837 let sections = build_sections(&input(&chats, &directory, &collapsed));
838 assert_eq!(
839 visible_chat_ids(&sections),
840 vec!["fav", "hid", "other", "m0", "m1", "m2", "m3", "m4"]
841 );
842 collapsed.insert("work".to_owned());
843 collapsed.insert("muted-folder".to_owned());
844 let sections = build_sections(&input(&chats, &directory, &collapsed));
845 assert_eq!(visible_chat_ids(&sections), vec!["fav", "other"]);
846 }
847
848 fn team(
849 id: &str,
850 hidden: bool,
851 channel_ids: &[&str],
852 hidden_channel_ids: &[&str],
853 ) -> SidebarTeam {
854 SidebarTeam {
855 team: store::TeamRecord {
856 id: id.into(),
857 name: id.into(),
858 },
859 channels: channel_ids
860 .iter()
861 .map(|channel_id| ChannelRecord {
862 id: (*channel_id).into(),
863 team_id: id.into(),
864 name: (*channel_id).into(),
865 membership_type: None,
866 last_message_at: None,
867 unread: false,
868 })
869 .collect(),
870 hidden,
871 hidden_channel_ids: hidden_channel_ids
872 .iter()
873 .map(|id| (*id).to_owned())
874 .collect(),
875 notifications: HashMap::new(),
876 mentions: Default::default(),
877 }
878 }
879
880 fn with_unread(mut entry: SidebarTeam, unread_ids: &[&str]) -> SidebarTeam {
881 for channel in &mut entry.channels {
882 channel.unread = unread_ids.contains(&channel.id.as_str());
883 }
884 entry
885 }
886
887 #[test]
888 fn unread_shown_channel_is_bold_and_highlighted() {
889 let bold = NameStyle {
890 weight: NameWeight::Bold,
891 highlighted: true,
892 };
893 let plain = NameStyle {
894 weight: NameWeight::Regular,
895 highlighted: false,
896 };
897 assert_eq!(channel_name_style(true, true, false), bold);
898 assert_eq!(channel_name_style(false, true, false), plain);
899 assert_eq!(channel_name_style(true, false, false), plain);
900 assert_eq!(
901 channel_name_style(true, true, true),
902 NameStyle {
903 weight: NameWeight::Regular,
904 highlighted: true,
905 }
906 );
907 }
908
909 #[test]
910 fn collapsed_team_with_an_unread_shown_channel_is_semibold() {
911 let entry = with_unread(team("t1", false, &["a", "b"], &["b"]), &["a"]);
912 let semibold = NameStyle {
913 weight: NameWeight::Semibold,
914 highlighted: true,
915 };
916 assert_eq!(team_name_style(&entry, false), semibold);
917 assert_eq!(team_name_style(&entry, true), NameStyle::PLAIN);
918 let only_hidden = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]);
919 assert_eq!(team_name_style(&only_hidden, false), NameStyle::PLAIN);
920 }
921
922 #[test]
923 fn rail_dot_counts_shown_channels_of_shown_teams_only() {
924 let sidebar = |teams: Vec<SidebarTeam>| Sidebar {
925 teams,
926 ..Sidebar::default()
927 };
928 let hidden_channel = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]);
929 let hidden_team = with_unread(team("t2", true, &["c"], &[]), &["c"]);
930 assert!(!any_unread_channel(&sidebar(vec![
931 hidden_channel,
932 hidden_team
933 ])));
934 let shown = with_unread(team("t1", false, &["a"], &[]), &["a"]);
935 let both = sidebar(vec![shown]);
936 assert!(any_unread_channel(&both));
937 assert!(channel_unread(&both, "a"));
938 assert!(!channel_unread(&both, "missing"));
939 }
940
941 #[test]
942 fn visible_channels_list_pinned_first_then_open_teams() {
943 let teams = [
944 team("t1", false, &["a", "b", "c"], &["b"]),
945 team("t2", false, &["d", "e"], &[]),
946 team("t3", true, &["f"], &[]),
947 ];
948 let pinned = ["e".to_owned(), "missing".to_owned()];
949 let order = |selected: Option<&str>,
950 hidden_teams_open: bool,
951 collapsed: &[&str],
952 revealed: &[&str]| {
953 let to_set = |ids: &[&str]| {
954 ids.iter()
955 .map(|id| (*id).to_owned())
956 .collect::<HashSet<_>>()
957 };
958 let (collapsed, revealed) = (to_set(collapsed), to_set(revealed));
959 let input = ChannelOrderInput {
960 teams: &teams,
961 pinned_ids: &pinned,
962 collapsed_teams: &collapsed,
963 revealed_channel_teams: &revealed,
964 hidden_teams_open,
965 selected_channel: selected,
966 };
967 visible_channel_ids(&input)
968 .into_iter()
969 .map(str::to_owned)
970 .collect::<Vec<_>>()
971 };
972 assert_eq!(order(None, false, &[], &[]), vec!["e", "a", "c", "d"]);
973 assert_eq!(
974 order(Some("b"), false, &[], &[]),
975 vec!["e", "a", "b", "c", "d"]
976 );
977 assert_eq!(
978 order(Some("f"), false, &[], &[]),
979 vec!["e", "a", "c", "d", "f"]
980 );
981 assert_eq!(order(None, true, &[], &[]), vec!["e", "a", "c", "d", "f"]);
982 assert_eq!(
983 order(None, true, &["t2"], &["t1"]),
984 vec!["e", "a", "c", "b", "f"]
985 );
986 }
987
988 fn with_mentions(mut entry: SidebarTeam, mentions: &[(&str, u32, u32, u32)]) -> SidebarTeam {
989 for (channel_id, personal, channel, team) in mentions {
990 entry.mentions.insert(
991 (*channel_id).to_owned(),
992 store::ChannelMentions {
993 personal: *personal,
994 channel: *channel,
995 team: *team,
996 },
997 );
998 }
999 entry
1000 }
1001
1002 #[test]
1003 fn channel_badges_prefer_the_count_then_channel_then_team() {
1004 let entry = with_mentions(
1005 team("t", false, &["a", "b", "c", "d"], &[]),
1006 &[("a", 2, 1, 1), ("b", 0, 3, 1), ("c", 0, 0, 1)],
1007 );
1008 assert_eq!(channel_badge(&entry, "a"), Some(MentionBadge::Count(2)));
1009 assert_eq!(channel_badge(&entry, "b"), Some(MentionBadge::Channel));
1010 assert_eq!(channel_badge(&entry, "c"), Some(MentionBadge::Team));
1011 assert_eq!(channel_badge(&entry, "d"), None);
1012 }
1013
1014 #[test]
1015 fn the_collapsed_team_sums_counts_of_all_channels_and_icons_of_shown_ones() {
1016 let entry = with_unread(
1017 with_mentions(
1018 team("t", false, &["a", "b", "c"], &["b", "c"]),
1019 &[("a", 1, 0, 0), ("b", 2, 0, 0), ("c", 0, 1, 0)],
1020 ),
1021 &["a", "b", "c"],
1022 );
1023 assert_eq!(team_badge(&entry, false), Some(MentionBadge::Count(3)));
1024 assert_eq!(team_badge(&entry, true), None);
1025 let icons_only = with_unread(
1026 with_mentions(
1027 team("t", false, &["a", "c"], &["c"]),
1028 &[("a", 0, 0, 1), ("c", 0, 1, 0)],
1029 ),
1030 &["a", "c"],
1031 );
1032 assert_eq!(team_badge(&icons_only, false), Some(MentionBadge::Team));
1033 let read = with_mentions(team("t", false, &["a"], &[]), &[("a", 1, 0, 0)]);
1034 assert_eq!(team_badge(&read, false), None);
1035 }
1036
1037 #[test]
1038 fn a_hidden_channel_with_a_personal_mention_is_pulled_into_the_list() {
1039 let entry = with_unread(
1040 with_mentions(
1041 team("t", false, &["a", "b", "c"], &["b", "c"]),
1042 &[("b", 1, 0, 0), ("c", 0, 1, 0)],
1043 ),
1044 &["b", "c"],
1045 );
1046 assert!(channel_shown(&entry, "b"));
1047 assert!(!channel_shown(&entry, "c"));
1048 assert!(team_has_unread(&entry));
1049 let rows = team_channel_rows(&entry, false, false, |_| false);
1050 let shown: Vec<&str> = rows
1051 .shown
1052 .iter()
1053 .map(|channel| channel.id.as_str())
1054 .collect();
1055 assert_eq!(shown, ["a", "b"]);
1056 assert_eq!(rows.hidden_count, 1);
1057 assert!(rows.revealed.is_empty());
1058 }
1059
1060 #[test]
1061 fn a_hidden_team_with_a_hoisted_channel_shows_only_that_channel_in_the_main_list() {
1062 let teams = [
1063 team("t1", false, &["a"], &[]),
1064 with_mentions(team("t2", true, &["b", "c"], &["c"]), &[("c", 1, 0, 0)]),
1065 ];
1066 assert!(team_hoisted(&teams[1]));
1067 assert!(!team_hoisted(&teams[0]));
1068 let rows = team_channel_rows(&teams[1], true, true, |_| true);
1069 let shown: Vec<&str> = rows
1070 .shown
1071 .iter()
1072 .map(|channel| channel.id.as_str())
1073 .collect();
1074 assert_eq!(shown, ["c"]);
1075 assert_eq!(rows.hidden_count, 0);
1076 let empty = HashSet::new();
1077 let input = ChannelOrderInput {
1078 teams: &teams,
1079 pinned_ids: &[],
1080 collapsed_teams: &empty,
1081 revealed_channel_teams: &empty,
1082 hidden_teams_open: false,
1083 selected_channel: None,
1084 };
1085 assert_eq!(visible_channel_ids(&input), ["a", "c"]);
1086 let open = ChannelOrderInput {
1087 hidden_teams_open: true,
1088 ..input
1089 };
1090 assert_eq!(visible_channel_ids(&open), ["a", "c", "b"]);
1091 }
1092
1093 #[test]
1094 fn muted_chats_stay_out_of_unread_counts() {
1095 let mut quiet = chat("a", "group", true);
1096 quiet.muted = true;
1097 let chats = [quiet, chat("b", "group", true)];
1098 assert_eq!(unread_chat_count(&chats), 1);
1099 let directory = sectioned_directory(true, Vec::new());
1100 let collapsed = HashSet::new();
1101 let sections = build_sections(&input(&chats, &directory, &collapsed));
1102 assert_eq!(sections[0].unread_chats, 1);
1103 assert_eq!(sections[1].kind, SectionKind::Muted);
1104 assert!(sections[1].items[0].muted);
1105 assert!(sections[1].items[0].unread.is_unread());
1106 }
1107
1108 #[test]
1109 fn preview_prefix_is_you_for_own_and_first_name_for_groups() {
1110 let mut group = chat("g", "group", false);
1111 group.last_message_preview = Some("Hello".into());
1112 group.last_message_sender_id = Some("ada".into());
1113 group.last_message_sender_name = Some("Ada Example".into());
1114 assert_eq!(
1115 preview_for(&group, Some(&me())),
1116 Preview::Text {
1117 prefix: Some("Ada".into()),
1118 text: "Hello".into()
1119 }
1120 );
1121 group.last_message_sender_id = Some("me".into());
1122 assert_eq!(
1123 preview_for(&group, Some(&me())),
1124 Preview::Text {
1125 prefix: Some("You".into()),
1126 text: "Hello".into()
1127 }
1128 );
1129 let mut direct = chat("d", "oneOnOne", false);
1130 direct.last_message_preview = Some("Hi".into());
1131 direct.last_message_sender_id = Some("ada".into());
1132 direct.last_message_sender_name = Some("Ada Example".into());
1133 assert_eq!(
1134 preview_for(&direct, Some(&me())),
1135 Preview::Text {
1136 prefix: None,
1137 text: "Hi".into()
1138 }
1139 );
1140 }
1141
1142 #[test]
1143 fn deleted_and_blank_previews() {
1144 let mut deleted = chat("d", "group", false);
1145 deleted.last_message_deleted = true;
1146 deleted.last_message_preview = Some("secret".into());
1147 assert_eq!(preview_for(&deleted, None), Preview::Deleted);
1148 assert_eq!(
1149 preview_for(&chat("e", "group", false), None),
1150 Preview::Empty
1151 );
1152 }
1153
1154 #[test]
1155 fn sections_follow_folder_order_and_leave_the_rest_for_others() {
1156 let chats = vec![
1157 chat("a", "group", false),
1158 chat("b", "oneOnOne", true),
1159 chat("c", "group", false),
1160 chat("d", "group", false),
1161 ];
1162 let directory = Directory {
1163 me: Some(me()),
1164 folders: vec![
1165 folder("fav", FolderKind::Favorites, &["c"]),
1166 folder("work", FolderKind::UserCreated, &["b", "gone", "a"]),
1167 folder("todo", FolderKind::UserCreated, &[]),
1168 ],
1169 ..Default::default()
1170 };
1171 let collapsed = HashSet::new();
1172 let sections = build_sections(&input(&chats, &directory, &collapsed));
1173 let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect();
1174 assert_eq!(ids, vec!["fav", "work", "todo", OTHERS_ID]);
1175 let work: Vec<&str> = sections[1]
1176 .items
1177 .iter()
1178 .map(|item| item.id.as_str())
1179 .collect();
1180 assert_eq!(work, vec!["b", "a"]);
1181 assert_eq!(sections[1].count, 2);
1182 assert_eq!(sections[2].count, 0);
1183 assert!(sections[2].show_empty_hint);
1184 let others: Vec<&str> = sections[3]
1185 .items
1186 .iter()
1187 .map(|item| item.id.as_str())
1188 .collect();
1189 assert_eq!(others, vec!["d"]);
1190 assert!(!sections[3].show_empty_hint);
1191 }
1192
1193 #[test]
1194 fn collapsed_sections_keep_the_aggregated_unread() {
1195 let chats = vec![
1196 chat("a", "group", true),
1197 chat("b", "group", true),
1198 chat("c", "group", false),
1199 ];
1200 let directory = Directory {
1201 folders: vec![folder("work", FolderKind::UserCreated, &["a", "b", "c"])],
1202 ..Default::default()
1203 };
1204 let collapsed: HashSet<String> = ["work".to_owned()].into();
1205 let sections = build_sections(&input(&chats, &directory, &collapsed));
1206 assert!(sections[0].collapsed);
1207 assert_eq!(sections[0].unread_chats, 2);
1208 assert_eq!(sections[0].count, 3);
1209 assert!(!sections[0].show_empty_hint);
1210 }
1211
1212 #[test]
1213 fn collapsed_empty_folder_hides_the_hint() {
1214 let directory = Directory {
1215 folders: vec![folder("todo", FolderKind::UserCreated, &[])],
1216 ..Default::default()
1217 };
1218 let collapsed: HashSet<String> = ["todo".to_owned()].into();
1219 let sections = build_sections(&input(&[], &directory, &collapsed));
1220 assert!(!sections[0].show_empty_hint);
1221 }
1222
1223 #[test]
1224 fn favorites_without_a_server_name_say_angeheftet() {
1225 let mut favorites = folder("fav", FolderKind::Favorites, &[]);
1226 favorites.name = String::new();
1227 let directory = Directory {
1228 folders: vec![favorites],
1229 ..Default::default()
1230 };
1231 let sections = build_sections(&input(&[], &directory, &HashSet::new()));
1232 assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
1233 }
1234
1235 #[test]
1236 fn the_importance_marker_shows_only_while_the_chat_is_unread() {
1237 let chats = vec![chat("a", "group", true), chat("b", "group", false)];
1238 let mut directory = Directory::default();
1239 directory
1240 .unread_importance
1241 .insert("a".into(), MessageImportance::Urgent);
1242 directory
1243 .unread_importance
1244 .insert("b".into(), MessageImportance::High);
1245 let collapsed = HashSet::new();
1246 let context = input(&chats, &directory, &collapsed);
1247 assert_eq!(
1248 chat_item(&chats[0], &context, None).importance,
1249 MessageImportance::Urgent
1250 );
1251 assert_eq!(
1252 chat_item(&chats[1], &context, None).importance,
1253 MessageImportance::Normal
1254 );
1255 }
1256
1257 #[test]
1258 fn unread_is_a_count_when_known_else_a_dot() {
1259 let chats = vec![
1260 chat("a", "group", true),
1261 chat("b", "group", true),
1262 chat("c", "group", false),
1263 ];
1264 let mut directory = Directory::default();
1265 directory.unread_counts.insert("a".into(), 5);
1266 let collapsed = HashSet::new();
1267 let context = input(&chats, &directory, &collapsed);
1268 assert_eq!(
1269 chat_item(&chats[0], &context, None).unread,
1270 Unread::Count(5)
1271 );
1272 assert_eq!(chat_item(&chats[1], &context, None).unread, Unread::Dot);
1273 assert_eq!(chat_item(&chats[2], &context, None).unread, Unread::None);
1274 assert_eq!(unread_chat_count(&chats), 2);
1275 }
1276
1277 #[test]
1278 fn one_on_one_has_presence_and_a_single_face_groups_have_a_pair() {
1279 let directory = Directory {
1280 me: Some(me()),
1281 ..Default::default()
1282 };
1283 let collapsed = HashSet::new();
1284 let chats = vec![chat("d", "oneOnOne", false), chat("g", "group", false)];
1285 let context = input(&chats, &directory, &collapsed);
1286 let direct = chat_item(&chats[0], &context, None);
1287 assert_eq!(direct.presence_user.as_deref(), Some("ada"));
1288 assert!(
1289 matches!(direct.avatar, AvatarSpec::Single(ref face) if face.name == "Ada Example")
1290 );
1291 let group = chat_item(&chats[1], &context, None);
1292 assert_eq!(group.presence_user, None);
1293 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
1294 assert_eq!(
1295 avatar_for(&meeting_chat("meeting-1"), None),
1296 AvatarSpec::Meeting
1297 );
1298 }
1299
1300 #[test]
1301 fn the_notes_chat_shows_my_face_and_my_presence() {
1302 let directory = Directory {
1303 me: Some(me()),
1304 ..Default::default()
1305 };
1306 let collapsed = HashSet::new();
1307 let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);
1308 notes.title = "Me Myself (You)".into();
1309 notes
1310 .members
1311 .retain(|member| member.user_id.as_deref() == Some("me"));
1312 let chats = vec![notes];
1313 let context = input(&chats, &directory, &collapsed);
1314 let item = chat_item(&chats[0], &context, None);
1315 assert_eq!(item.title, "Me Myself (You)");
1316 assert_eq!(item.presence_user.as_deref(), Some("me"));
1317 assert!(
1318 matches!(item.avatar, AvatarSpec::Single(ref face) if face.user_id.as_deref() == Some("me"))
1319 );
1320 }
1321
1322 #[test]
1323 fn a_one_on_one_with_a_bot_shows_the_bot_tile_and_no_presence() {
1324 let directory = Directory {
1325 me: Some(me()),
1326 ..Default::default()
1327 };
1328 let collapsed = HashSet::new();
1329 let mut echo = chat("echo", "oneOnOne", false);
1330 echo.title = "Echo".into();
1331 echo.members.truncate(1);
1332 echo.members.push(MemberRecord {
1333 user_id: Some("28:bot-echo".into()),
1334 display_name: "Echo".into(),
1335 });
1336 echo.last_message_preview = Some("Recording is ready".into());
1337 let chats = vec![echo];
1338 let context = input(&chats, &directory, &collapsed);
1339 let item = chat_item(&chats[0], &context, None);
1340 assert_eq!(item.title, "Echo");
1341 assert_eq!(item.presence_user, None);
1342 assert!(
1343 matches!(item.avatar, AvatarSpec::Bot(ref face) if face.user_id.as_deref() == Some("28:bot-echo"))
1344 );
1345 assert_eq!(item.preview, Preview::Event("Recording is ready".into()));
1346 }
1347
1348 #[test]
1349 fn an_event_label_from_a_person_stays_plain_text() {
1350 let mut direct = chat("d", "oneOnOne", false);
1351 direct.last_message_preview = Some("Recording is ready".into());
1352 direct.last_message_sender_id = Some("ada".into());
1353 assert_eq!(
1354 preview_for(&direct, Some(&me())),
1355 Preview::Text {
1356 prefix: None,
1357 text: "Recording is ready".into()
1358 }
1359 );
1360 }
1361
1362 #[test]
1363 fn typing_replaces_the_preview_even_in_muted_chats() {
1364 let mut direct = chat("d", "oneOnOne", false);
1365 direct.last_message_preview = Some("Earlier".into());
1366 direct.muted = true;
1367 let group = chat("g", "group", false);
1368 let chats = vec![direct, group];
1369 let directory = Directory::default();
1370 let collapsed = HashSet::new();
1371 let now = std::time::Instant::now();
1372 let mut typing = TypingState::default();
1373 typing.start("d", "ada", "Ada Example", now, Utc::now());
1374 typing.start("g", "ada", "Ada Example", now, Utc::now());
1375 let context = typing_input(&chats, &directory, &collapsed, &typing);
1376 assert_eq!(
1377 chat_item(&chats[0], &context, None).preview,
1378 Preview::Typing("typing...".into())
1379 );
1380 assert_eq!(
1381 chat_item(&chats[1], &context, None).preview,
1382 Preview::Typing("Ada is typing...".into())
1383 );
1384 typing.clear("d", "ada");
1385 let context = typing_input(&chats, &directory, &collapsed, &typing);
1386 assert_eq!(
1387 chat_item(&chats[0], &context, None).preview,
1388 Preview::Text {
1389 prefix: None,
1390 text: "Earlier".into()
1391 }
1392 );
1393 }
1394
1395 #[test]
1396 fn time_label_uses_the_list_rules() {
1397 let chats = vec![chat("a", "group", false)];
1398 let directory = Directory::default();
1399 let collapsed = HashSet::new();
1400 let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None);
1401 assert_eq!(item.time_label, "09:30");
1402 }
1403
1404 #[test]
1405 fn muted_chats_leave_others_unless_pinned_or_in_a_custom_section_and_meeting_chats_stay() {
1406 let chats = vec![
1407 chat("plain", "group", false),
1408 muted_chat("quiet"),
1409 muted_chat("pinned-quiet"),
1410 meeting_chat("sync"),
1411 meeting_chat("custom-sync"),
1412 ChatRecord {
1413 muted: true,
1414 ..meeting_chat("quiet-sync")
1415 },
1416 ];
1417 let directory = sectioned_directory(
1418 true,
1419 vec![
1420 folder("fav", FolderKind::Favorites, &["pinned-quiet"]),
1421 folder("work", FolderKind::UserCreated, &["custom-sync"]),
1422 ],
1423 );
1424 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1425 assert_eq!(
1426 section_ids(&sections),
1427 vec!["fav", "work", OTHERS_ID, MUTED_ID]
1428 );
1429 assert_eq!(item_ids(&sections[0]), vec!["pinned-quiet"]);
1430 assert_eq!(item_ids(&sections[1]), vec!["custom-sync"]);
1431 assert_eq!(item_ids(&sections[2]), vec!["plain", "sync"]);
1432 assert_eq!(item_ids(&sections[3]), vec!["quiet", "quiet-sync"]);
1433 assert_eq!(sections[3].kind, SectionKind::Muted);
1434 assert_eq!(sections[3].count, 2);
1435 }
1436
1437 #[test]
1438 fn turning_the_muted_section_off_puts_its_chats_back_in_others() {
1439 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
1440 let directory = sectioned_directory(false, Vec::new());
1441 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1442 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1443 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
1444 }
1445
1446 #[test]
1447 fn muted_chats_stay_in_others_until_the_user_turns_the_section_on() {
1448 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
1449 let directory = Directory::default();
1450 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1451 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1452 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
1453 assert!(sections[0].items[0].muted);
1454 assert_eq!(sections[0].items[0].avatar, AvatarSpec::Muted);
1455 assert_eq!(sections[0].items[1].avatar, AvatarSpec::Meeting);
1456 }
1457
1458 #[test]
1459 fn a_muted_chat_in_others_stays_bold_without_a_count() {
1460 let mut quiet = muted_chat("quiet");
1461 quiet.unread = true;
1462 let chats = vec![quiet];
1463 let mut directory = Directory::default();
1464 directory.unread_counts.insert("quiet".into(), 4);
1465 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1466 assert_eq!(sections[0].kind, SectionKind::Others);
1467 assert_eq!(sections[0].items[0].unread, Unread::Silent);
1468 assert_eq!(sections[0].unread_chats, 0);
1469 }
1470
1471 #[test]
1472 fn older_chats_load_only_when_the_end_of_other_chats_is_on_screen_once_per_scroll_position() {
1473 assert!(wants_older_chats(Some(900.), 1000., 0., None, false));
1474 assert!(!wants_older_chats(Some(1500.), 1000., 0., None, false));
1475 assert!(!wants_older_chats(None, 1000., 0., None, false));
1476 assert!(!wants_older_chats(Some(900.), 1000., 0., Some(0.), false));
1477 assert!(wants_older_chats(Some(900.), 1000., 120., Some(0.), false));
1478 }
1479
1480 #[test]
1481 fn a_running_load_never_consumes_the_trigger() {
1482 assert!(!wants_older_chats(Some(900.), 1000., 0., None, true));
1483 }
1484
1485 #[test]
1486 fn the_trigger_resets_when_a_load_ends_or_more_chats_appear_but_not_while_idle() {
1487 assert!(older_chats_trigger_resets((true, true), (true, false)));
1488 assert!(older_chats_trigger_resets((true, true), (false, false)));
1489 assert!(older_chats_trigger_resets((false, false), (true, false)));
1490 assert!(!older_chats_trigger_resets((true, false), (true, false)));
1491 assert!(!older_chats_trigger_resets((true, false), (true, true)));
1492 assert!(!older_chats_trigger_resets((false, false), (false, false)));
1493 }
1494
1495 #[test]
1496 fn empty_system_sections_are_hidden() {
1497 let chats = vec![chat("a", "group", false)];
1498 let directory = sectioned_directory(true, Vec::new());
1499 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1500 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1501 }
1502
1503 #[test]
1504 fn sections_follow_the_server_folder_order_with_system_folders() {
1505 let chats = vec![
1506 chat("a", "group", false),
1507 muted_chat("quiet"),
1508 meeting_chat("sync"),
1509 ];
1510 let directory = sectioned_directory(
1511 true,
1512 vec![
1513 folder("muted-id", FolderKind::Muted, &[]),
1514 folder("fav", FolderKind::Favorites, &[]),
1515 folder("recent-id", FolderKind::Recent, &[]),
1516 folder("meeting-id", FolderKind::Meeting, &[]),
1517 ],
1518 );
1519 let collapsed: HashSet<String> = ["muted-id".to_owned()].into();
1520 let sections = build_sections(&input(&chats, &directory, &collapsed));
1521 assert_eq!(section_ids(&sections), vec!["muted-id", "fav", "recent-id"]);
1522 assert!(sections[0].collapsed);
1523 assert_eq!(sections[0].name, MUTED_NAME);
1524 assert_eq!(item_ids(&sections[2]), vec!["a", "sync"]);
1525 }
1526
1527 #[test]
1528 fn newest_five_show_then_see_more_expands_and_see_less_collapses() {
1529 let chats: Vec<ChatRecord> = (0..8)
1530 .map(|index| muted_chat(&format!("m{index}")))
1531 .collect();
1532 let directory = sectioned_directory(true, Vec::new());
1533 let collapsed = HashSet::new();
1534 let sections = build_sections(&input(&chats, &directory, &collapsed));
1535 let muted = &sections[1];
1536 assert_eq!(item_ids(muted), vec!["m0", "m1", "m2", "m3", "m4"]);
1537 assert_eq!(muted.count, 8);
1538 assert_eq!(muted.hidden_count, 3);
1539 assert!(!muted.list_expanded);
1540
1541 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
1542 let mut context = input(&chats, &directory, &collapsed);
1543 context.expanded_lists = &expanded;
1544 let sections = build_sections(&context);
1545 let muted = &sections[1];
1546 assert_eq!(muted.items.len(), 8);
1547 assert_eq!(muted.hidden_count, 0);
1548 assert!(muted.list_expanded);
1549 }
1550
1551 #[test]
1552 fn five_chats_need_no_see_more_even_when_marked_expanded() {
1553 let chats: Vec<ChatRecord> = (0..5)
1554 .map(|index| muted_chat(&format!("m{index}")))
1555 .collect();
1556 let directory = sectioned_directory(true, Vec::new());
1557 let collapsed = HashSet::new();
1558 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
1559 let mut context = input(&chats, &directory, &collapsed);
1560 context.expanded_lists = &expanded;
1561 let muted = &build_sections(&context)[1];
1562 assert_eq!(muted.hidden_count, 0);
1563 assert!(!muted.list_expanded);
1564 }
1565
1566 #[test]
1567 fn muted_section_keeps_unread_bold_without_a_badge_or_a_count() {
1568 let mut quiet = muted_chat("quiet");
1569 quiet.unread = true;
1570 let chats = vec![
1571 quiet,
1572 ChatRecord {
1573 muted: true,
1574 ..meeting_chat("x")
1575 },
1576 ];
1577 let mut directory = sectioned_directory(true, Vec::new());
1578 directory.unread_counts.insert("quiet".into(), 4);
1579 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1580 let muted = &sections[1];
1581 assert_eq!(muted.items[0].unread, Unread::Silent);
1582 assert!(muted.items[0].unread.is_unread());
1583 assert_eq!(muted.unread_chats, 0);
1584 assert_eq!(unread_chat_count(&chats), 0);
1585 }
1586
1587 #[test]
1588 fn meeting_chats_keep_their_unread_count_in_others() {
1589 let mut sync = meeting_chat("sync");
1590 sync.unread = true;
1591 let chats = vec![sync];
1592 let mut directory = sectioned_directory(true, Vec::new());
1593 directory.unread_counts.insert("sync".into(), 3);
1594 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1595 assert_eq!(sections[0].id, OTHERS_ID);
1596 assert_eq!(sections[0].items[0].unread, Unread::Count(3));
1597 assert_eq!(sections[0].unread_chats, 1);
1598 }
1599}