BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

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