BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

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