BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

sidebar_model.rs 29.6 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2
3use chrono::{DateTime, FixedOffset, Utc};
4use store::{ChatRecord, Sidebar};
5use teams_core::ChatSection;
6
7use crate::app_state::chat_title;
8use crate::data::{
9 Directory, FolderKind, Person, face_members, is_one_on_one, others, unread_count,
10};
11use crate::format;
12use crate::typing::{TypingState, preview_label};
13
14pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";
15pub const OTHERS_NAME: &str = "Other chats";
16pub const OTHERS_ID: &str = "others";
17pub const MEETING_NAME: &str = "Meeting chats";
18pub const MEETING_ID: &str = "meeting_chats";
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";
24const OWN_PREFIX: &str = "You";
25const GROUP_KIND: &str = "group";
26const MEETING_KIND: &str = "meeting";
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum Preview {
30 Empty,
31 Deleted,
32 Typing(String),
33 Text {
34 prefix: Option<String>,
35 text: String,
36 },
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum Unread {
41 None,
42 Silent,
43 Dot,
44 Count(u32),
45}
46
47impl Unread {
48 pub fn is_unread(self) -> bool {
49 self != Unread::None
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Face {
55 pub user_id: Option<String>,
56 pub name: String,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum AvatarSpec {
61 Single(Face),
62 Pair(Face, Face),
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct ChatItem {
67 pub id: String,
68 pub title: String,
69 pub time_label: String,
70 pub preview: Preview,
71 pub unread: Unread,
72 pub muted: bool,
73 pub is_group: bool,
74 pub member_count: usize,
75 pub avatar: AvatarSpec,
76 pub presence_user: Option<String>,
77 pub folder_id: Option<String>,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum SectionKind {
82 Favorites,
83 Folder,
84 Others,
85 Meeting,
86 Muted,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct Section {
91 pub id: String,
92 pub name: String,
93 pub kind: SectionKind,
94 pub collapsed: bool,
95 pub count: usize,
96 pub unread_chats: u32,
97 pub items: Vec<ChatItem>,
98 pub hidden_count: usize,
99 pub list_expanded: bool,
100 pub show_empty_hint: bool,
101}
102
103pub struct SectionInput<'a> {
104 pub chats: &'a [ChatRecord],
105 pub directory: &'a Directory,
106 pub collapsed: &'a HashSet<String>,
107 pub expanded_lists: &'a HashSet<String>,
108 pub typing: &'a TypingState,
109 pub now: DateTime<Utc>,
110 pub offset: FixedOffset,
111}
112
113pub fn preview_for(chat: &ChatRecord, me: Option<&Person>) -> Preview {
114 if chat.last_message_deleted {
115 return Preview::Deleted;
116 }
117 let Some(text) = chat
118 .last_message_preview
119 .as_deref()
120 .map(str::trim)
121 .filter(|text| !text.is_empty())
122 else {
123 return Preview::Empty;
124 };
125 let from_me = match (chat.last_message_sender_id.as_deref(), 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 let faces = face_members(chat, me);
147 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
148 if is_one_on_one(chat) || faces.len() < 2 {
149 return AvatarSpec::Single(match faces.into_iter().next() {
150 Some(first) => face(first),
151 None => Face {
152 user_id: None,
153 name: chat_title(chat),
154 },
155 });
156 }
157 let mut iterator = faces.into_iter();
158 let (first, second) = (iterator.next(), iterator.next());
159 match (first, second) {
160 (Some(first), Some(second)) => AvatarSpec::Pair(face(first), face(second)),
161 _ => AvatarSpec::Single(Face {
162 user_id: None,
163 name: chat_title(chat),
164 }),
165 }
166}
167
168pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<&str>) -> ChatItem {
169 let me = input.directory.me.as_ref();
170 let unread = if chat.unread {
171 unread_count(input.directory, chat)
172 .filter(|count| *count > 0)
173 .map_or(Unread::Dot, Unread::Count)
174 } else {
175 Unread::None
176 };
177 let presence_user = is_one_on_one(chat)
178 .then(|| {
179 others(chat, me)
180 .into_iter()
181 .find_map(|(user_id, _)| user_id)
182 })
183 .flatten();
184 let typing_names = input.typing.names(&chat.id);
185 let preview = if typing_names.is_empty() {
186 preview_for(chat, me)
187 } else {
188 Preview::Typing(preview_label(&typing_names, is_one_on_one(chat)))
189 };
190 ChatItem {
191 id: chat.id.clone(),
192 title: chat_title(chat),
193 time_label: chat
194 .last_message_at
195 .map(|time| {
196 format::list_time_label(
197 time,
198 input.now.with_timezone(&input.offset).date_naive(),
199 input.offset,
200 )
201 })
202 .unwrap_or_default(),
203 preview,
204 unread,
205 muted: chat.muted,
206 is_group: chat.kind == GROUP_KIND,
207 member_count: chat.members.len(),
208 avatar: avatar_for(chat, me),
209 presence_user,
210 folder_id: folder_id.map(str::to_owned),
211 }
212}
213
214pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 {
215 chats
216 .iter()
217 .filter(|chat| chat.unread && !chat.muted)
218 .count() as u32
219}
220
221pub fn any_unread_channel(sidebar: &Sidebar) -> bool {
222 sidebar
223 .teams
224 .iter()
225 .any(|team| team.channels.iter().any(|channel| channel.unread))
226}
227
228pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
229 let by_id: HashMap<&str, &ChatRecord> = input
230 .chats
231 .iter()
232 .map(|chat| (chat.id.as_str(), chat))
233 .collect();
234 let mut placed: HashSet<&str> = HashSet::new();
235 let mut built: Vec<Option<Section>> = input
236 .directory
237 .folders
238 .iter()
239 .map(|folder| {
240 let (kind, name) = match folder.kind {
241 FolderKind::Favorites => (
242 SectionKind::Favorites,
243 if folder.name.trim().is_empty() {
244 FAVORITES_FALLBACK_NAME.to_owned()
245 } else {
246 folder.name.clone()
247 },
248 ),
249 FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()),
250 FolderKind::Recent | FolderKind::Meeting | FolderKind::Muted => return None,
251 };
252 let items: Vec<ChatItem> = folder
253 .conversation_ids
254 .iter()
255 .filter_map(|id| by_id.get(id.as_str()).copied())
256 .filter(|chat| placed.insert(chat.id.as_str()))
257 .map(|chat| chat_item(chat, input, Some(&folder.id)))
258 .collect();
259 Some(section(folder.id.clone(), name, kind, items, input))
260 })
261 .collect();
262 let settings = &input.directory.section_settings;
263 let mut muted = Vec::new();
264 let mut meeting = Vec::new();
265 let mut rest = Vec::new();
266 for chat in input
267 .chats
268 .iter()
269 .filter(|chat| !placed.contains(chat.id.as_str()))
270 {
271 let item = chat_item(chat, input, None);
272 if chat.muted && settings.enabled(ChatSection::Muted) {
273 muted.push(item);
274 } else if !chat.muted && chat.kind == MEETING_KIND && settings.enabled(ChatSection::Meeting)
275 {
276 meeting.push(item);
277 } else {
278 rest.push(item);
279 }
280 }
281 let folder_id = |kind: FolderKind, fallback: &str| {
282 input
283 .directory
284 .folders
285 .iter()
286 .find(|folder| folder.kind == kind)
287 .map_or_else(|| fallback.to_owned(), |folder| folder.id.clone())
288 };
289 let mut others = Some(section(
290 folder_id(FolderKind::Recent, OTHERS_ID),
291 OTHERS_NAME.to_owned(),
292 SectionKind::Others,
293 rest,
294 input,
295 ));
296 let mut meeting = (!meeting.is_empty()).then(|| {
297 section(
298 folder_id(FolderKind::Meeting, MEETING_ID),
299 MEETING_NAME.to_owned(),
300 SectionKind::Meeting,
301 meeting,
302 input,
303 )
304 });
305 let mut muted = (!muted.is_empty()).then(|| {
306 section(
307 folder_id(FolderKind::Muted, MUTED_ID),
308 MUTED_NAME.to_owned(),
309 SectionKind::Muted,
310 muted,
311 input,
312 )
313 });
314 let mut sections = Vec::new();
315 for (folder, section) in input.directory.folders.iter().zip(&mut built) {
316 match folder.kind {
317 FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()),
318 FolderKind::Recent => sections.extend(others.take()),
319 FolderKind::Meeting => sections.extend(meeting.take()),
320 FolderKind::Muted => sections.extend(muted.take()),
321 }
322 }
323 sections.extend(meeting);
324 sections.extend(others);
325 sections.extend(muted);
326 sections
327}
328
329pub fn next_chat_id(sections: &[Section], removed_id: &str) -> Option<String> {
330 let visible: Vec<&str> = sections
331 .iter()
332 .filter(|section| !section.collapsed)
333 .flat_map(|section| section.items.iter().map(|item| item.id.as_str()))
334 .collect();
335 let position = visible.iter().position(|id| *id == removed_id)?;
336 visible
337 .get(position + 1)
338 .or_else(|| {
339 position
340 .checked_sub(1)
341 .and_then(|previous| visible.get(previous))
342 })
343 .map(|id| (*id).to_owned())
344}
345
346fn section(
347 id: String,
348 name: String,
349 kind: SectionKind,
350 mut items: Vec<ChatItem>,
351 input: &SectionInput<'_>,
352) -> Section {
353 let collapsed = input.collapsed.contains(&id);
354 let count = items.len();
355 let unread_chats = items
356 .iter()
357 .filter(|item| item.unread.is_unread() && !item.muted)
358 .count() as u32;
359 let paged = matches!(kind, SectionKind::Meeting | SectionKind::Muted);
360 let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id);
361 let hidden_count = if paged && !list_expanded {
362 count.saturating_sub(SECTION_PAGE_SIZE)
363 } else {
364 0
365 };
366 items.truncate(count - hidden_count);
367 if kind == SectionKind::Muted {
368 for item in &mut items {
369 if item.unread.is_unread() {
370 item.unread = Unread::Silent;
371 }
372 }
373 }
374 Section {
375 collapsed,
376 count,
377 unread_chats,
378 hidden_count,
379 list_expanded,
380 show_empty_hint: items.is_empty()
381 && !collapsed
382 && matches!(kind, SectionKind::Favorites | SectionKind::Folder),
383 id,
384 name,
385 kind,
386 items,
387 }
388}
389
390#[cfg(test)]
391mod tests {
392 use chrono::TimeZone;
393 use store::MemberRecord;
394
395 use super::*;
396 use crate::data::FolderInfo;
397
398 fn me() -> Person {
399 Person {
400 user_id: "me".into(),
401 display_name: "Me Myself".into(),
402 }
403 }
404
405 fn chat(id: &str, kind: &str, unread: bool) -> ChatRecord {
406 ChatRecord {
407 id: id.into(),
408 kind: kind.into(),
409 title: id.to_uppercase(),
410 unread,
411 last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 7, 9, 30, 0).unwrap()),
412 members: vec![
413 MemberRecord {
414 user_id: Some("me".into()),
415 display_name: "Me Myself".into(),
416 },
417 MemberRecord {
418 user_id: Some("ada".into()),
419 display_name: "Ada Example".into(),
420 },
421 MemberRecord {
422 user_id: Some("bob".into()),
423 display_name: "Bob Sample".into(),
424 },
425 ],
426 ..Default::default()
427 }
428 }
429
430 fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo {
431 FolderInfo {
432 id: id.into(),
433 name: format!("name-{id}"),
434 kind,
435 expanded: None,
436 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
437 }
438 }
439
440 fn muted_chat(id: &str) -> ChatRecord {
441 ChatRecord {
442 muted: true,
443 ..chat(id, "group", false)
444 }
445 }
446
447 fn meeting_chat(id: &str) -> ChatRecord {
448 chat(id, "meeting", false)
449 }
450
451 fn sectioned_directory(muted: bool, meeting: bool, folders: Vec<FolderInfo>) -> Directory {
452 let mut directory = Directory {
453 folders,
454 ..Default::default()
455 };
456 directory.section_settings.set(ChatSection::Muted, muted);
457 directory
458 .section_settings
459 .set(ChatSection::Meeting, meeting);
460 directory
461 }
462
463 fn section_ids(sections: &[Section]) -> Vec<&str> {
464 sections.iter().map(|section| section.id.as_str()).collect()
465 }
466
467 fn item_ids(section: &Section) -> Vec<&str> {
468 section.items.iter().map(|item| item.id.as_str()).collect()
469 }
470
471 fn input<'a>(
472 chats: &'a [ChatRecord],
473 directory: &'a Directory,
474 collapsed: &'a HashSet<String>,
475 ) -> SectionInput<'a> {
476 typing_input(chats, directory, collapsed, &NO_TYPING)
477 }
478
479 static NO_EXPANDED: std::sync::LazyLock<HashSet<String>> =
480 std::sync::LazyLock::new(HashSet::new);
481
482 static NO_TYPING: std::sync::LazyLock<TypingState> =
483 std::sync::LazyLock::new(TypingState::default);
484
485 fn typing_input<'a>(
486 chats: &'a [ChatRecord],
487 directory: &'a Directory,
488 collapsed: &'a HashSet<String>,
489 typing: &'a TypingState,
490 ) -> SectionInput<'a> {
491 SectionInput {
492 chats,
493 directory,
494 collapsed,
495 expanded_lists: &NO_EXPANDED,
496 typing,
497 now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),
498 offset: FixedOffset::east_opt(0).unwrap(),
499 }
500 }
501
502 #[test]
503 fn next_chat_is_the_following_row_then_the_previous_one() {
504 let chats = [
505 chat("a", "group", false),
506 chat("b", "group", false),
507 chat("c", "group", false),
508 ];
509 let directory = Directory::default();
510 let collapsed = HashSet::new();
511 let sections = build_sections(&input(&chats, &directory, &collapsed));
512 assert_eq!(next_chat_id(&sections, "a"), Some("b".to_owned()));
513 assert_eq!(next_chat_id(&sections, "c"), Some("b".to_owned()));
514 assert_eq!(next_chat_id(&sections, "zzz"), None);
515 let single = [chat("a", "group", false)];
516 let sections = build_sections(&input(&single, &directory, &collapsed));
517 assert_eq!(next_chat_id(&sections, "a"), None);
518 }
519
520 #[test]
521 fn muted_chats_stay_out_of_unread_counts() {
522 let mut quiet = chat("a", "group", true);
523 quiet.muted = true;
524 let chats = [quiet, chat("b", "group", true)];
525 assert_eq!(unread_chat_count(&chats), 1);
526 let directory = Directory::default();
527 let collapsed = HashSet::new();
528 let sections = build_sections(&input(&chats, &directory, &collapsed));
529 assert_eq!(sections[0].unread_chats, 1);
530 assert_eq!(sections[1].kind, SectionKind::Muted);
531 assert!(sections[1].items[0].muted);
532 assert!(sections[1].items[0].unread.is_unread());
533 }
534
535 #[test]
536 fn preview_prefix_is_you_for_own_and_first_name_for_groups() {
537 let mut group = chat("g", "group", false);
538 group.last_message_preview = Some("Hello".into());
539 group.last_message_sender_id = Some("ada".into());
540 group.last_message_sender_name = Some("Ada Example".into());
541 assert_eq!(
542 preview_for(&group, Some(&me())),
543 Preview::Text {
544 prefix: Some("Ada".into()),
545 text: "Hello".into()
546 }
547 );
548 group.last_message_sender_id = Some("me".into());
549 assert_eq!(
550 preview_for(&group, Some(&me())),
551 Preview::Text {
552 prefix: Some("You".into()),
553 text: "Hello".into()
554 }
555 );
556 let mut direct = chat("d", "oneOnOne", false);
557 direct.last_message_preview = Some("Hi".into());
558 direct.last_message_sender_id = Some("ada".into());
559 direct.last_message_sender_name = Some("Ada Example".into());
560 assert_eq!(
561 preview_for(&direct, Some(&me())),
562 Preview::Text {
563 prefix: None,
564 text: "Hi".into()
565 }
566 );
567 }
568
569 #[test]
570 fn deleted_and_blank_previews() {
571 let mut deleted = chat("d", "group", false);
572 deleted.last_message_deleted = true;
573 deleted.last_message_preview = Some("secret".into());
574 assert_eq!(preview_for(&deleted, None), Preview::Deleted);
575 assert_eq!(
576 preview_for(&chat("e", "group", false), None),
577 Preview::Empty
578 );
579 }
580
581 #[test]
582 fn sections_follow_folder_order_and_leave_the_rest_for_others() {
583 let chats = vec![
584 chat("a", "group", false),
585 chat("b", "oneOnOne", true),
586 chat("c", "group", false),
587 chat("d", "group", false),
588 ];
589 let directory = Directory {
590 me: Some(me()),
591 folders: vec![
592 folder("fav", FolderKind::Favorites, &["c"]),
593 folder("work", FolderKind::UserCreated, &["b", "gone", "a"]),
594 folder("todo", FolderKind::UserCreated, &[]),
595 ],
596 ..Default::default()
597 };
598 let collapsed = HashSet::new();
599 let sections = build_sections(&input(&chats, &directory, &collapsed));
600 let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect();
601 assert_eq!(ids, vec!["fav", "work", "todo", OTHERS_ID]);
602 let work: Vec<&str> = sections[1]
603 .items
604 .iter()
605 .map(|item| item.id.as_str())
606 .collect();
607 assert_eq!(work, vec!["b", "a"]);
608 assert_eq!(sections[1].count, 2);
609 assert_eq!(sections[2].count, 0);
610 assert!(sections[2].show_empty_hint);
611 let others: Vec<&str> = sections[3]
612 .items
613 .iter()
614 .map(|item| item.id.as_str())
615 .collect();
616 assert_eq!(others, vec!["d"]);
617 assert!(!sections[3].show_empty_hint);
618 }
619
620 #[test]
621 fn collapsed_sections_keep_the_aggregated_unread() {
622 let chats = vec![
623 chat("a", "group", true),
624 chat("b", "group", true),
625 chat("c", "group", false),
626 ];
627 let directory = Directory {
628 folders: vec![folder("work", FolderKind::UserCreated, &["a", "b", "c"])],
629 ..Default::default()
630 };
631 let collapsed: HashSet<String> = ["work".to_owned()].into();
632 let sections = build_sections(&input(&chats, &directory, &collapsed));
633 assert!(sections[0].collapsed);
634 assert_eq!(sections[0].unread_chats, 2);
635 assert_eq!(sections[0].count, 3);
636 assert!(!sections[0].show_empty_hint);
637 }
638
639 #[test]
640 fn collapsed_empty_folder_hides_the_hint() {
641 let directory = Directory {
642 folders: vec![folder("todo", FolderKind::UserCreated, &[])],
643 ..Default::default()
644 };
645 let collapsed: HashSet<String> = ["todo".to_owned()].into();
646 let sections = build_sections(&input(&[], &directory, &collapsed));
647 assert!(!sections[0].show_empty_hint);
648 }
649
650 #[test]
651 fn favorites_without_a_server_name_say_angeheftet() {
652 let mut favorites = folder("fav", FolderKind::Favorites, &[]);
653 favorites.name = String::new();
654 let directory = Directory {
655 folders: vec![favorites],
656 ..Default::default()
657 };
658 let sections = build_sections(&input(&[], &directory, &HashSet::new()));
659 assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
660 }
661
662 #[test]
663 fn unread_is_a_count_when_known_else_a_dot() {
664 let chats = vec![
665 chat("a", "group", true),
666 chat("b", "group", true),
667 chat("c", "group", false),
668 ];
669 let mut directory = Directory::default();
670 directory.unread_counts.insert("a".into(), 5);
671 let collapsed = HashSet::new();
672 let context = input(&chats, &directory, &collapsed);
673 assert_eq!(
674 chat_item(&chats[0], &context, None).unread,
675 Unread::Count(5)
676 );
677 assert_eq!(chat_item(&chats[1], &context, None).unread, Unread::Dot);
678 assert_eq!(chat_item(&chats[2], &context, None).unread, Unread::None);
679 assert_eq!(unread_chat_count(&chats), 2);
680 }
681
682 #[test]
683 fn one_on_one_has_presence_and_a_single_face_groups_have_a_pair() {
684 let directory = Directory {
685 me: Some(me()),
686 ..Default::default()
687 };
688 let collapsed = HashSet::new();
689 let chats = vec![chat("d", "oneOnOne", false), chat("g", "group", false)];
690 let context = input(&chats, &directory, &collapsed);
691 let direct = chat_item(&chats[0], &context, None);
692 assert_eq!(direct.presence_user.as_deref(), Some("ada"));
693 assert!(
694 matches!(direct.avatar, AvatarSpec::Single(ref face) if face.name == "Ada Example")
695 );
696 let group = chat_item(&chats[1], &context, None);
697 assert_eq!(group.presence_user, None);
698 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
699 }
700
701 #[test]
702 fn typing_replaces_the_preview_even_in_muted_chats() {
703 let mut direct = chat("d", "oneOnOne", false);
704 direct.last_message_preview = Some("Earlier".into());
705 direct.muted = true;
706 let group = chat("g", "group", false);
707 let chats = vec![direct, group];
708 let directory = Directory::default();
709 let collapsed = HashSet::new();
710 let now = std::time::Instant::now();
711 let mut typing = TypingState::default();
712 typing.start("d", "ada", "Ada Example", now, Utc::now());
713 typing.start("g", "ada", "Ada Example", now, Utc::now());
714 let context = typing_input(&chats, &directory, &collapsed, &typing);
715 assert_eq!(
716 chat_item(&chats[0], &context, None).preview,
717 Preview::Typing("typing...".into())
718 );
719 assert_eq!(
720 chat_item(&chats[1], &context, None).preview,
721 Preview::Typing("Ada is typing...".into())
722 );
723 typing.clear("d", "ada");
724 let context = typing_input(&chats, &directory, &collapsed, &typing);
725 assert_eq!(
726 chat_item(&chats[0], &context, None).preview,
727 Preview::Text {
728 prefix: None,
729 text: "Earlier".into()
730 }
731 );
732 }
733
734 #[test]
735 fn time_label_uses_the_list_rules() {
736 let chats = vec![chat("a", "group", false)];
737 let directory = Directory::default();
738 let collapsed = HashSet::new();
739 let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None);
740 assert_eq!(item.time_label, "09:30");
741 }
742
743 #[test]
744 fn muted_and_meeting_chats_leave_others_unless_pinned_or_in_a_custom_section() {
745 let chats = vec![
746 chat("plain", "group", false),
747 muted_chat("quiet"),
748 muted_chat("pinned-quiet"),
749 meeting_chat("sync"),
750 meeting_chat("custom-sync"),
751 ChatRecord {
752 muted: true,
753 ..meeting_chat("quiet-sync")
754 },
755 ];
756 let directory = sectioned_directory(
757 true,
758 true,
759 vec![
760 folder("fav", FolderKind::Favorites, &["pinned-quiet"]),
761 folder("work", FolderKind::UserCreated, &["custom-sync"]),
762 ],
763 );
764 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
765 assert_eq!(
766 section_ids(&sections),
767 vec!["fav", "work", MEETING_ID, OTHERS_ID, MUTED_ID]
768 );
769 assert_eq!(item_ids(&sections[0]), vec!["pinned-quiet"]);
770 assert_eq!(item_ids(&sections[1]), vec!["custom-sync"]);
771 assert_eq!(item_ids(&sections[2]), vec!["sync"]);
772 assert_eq!(item_ids(&sections[3]), vec!["plain"]);
773 assert_eq!(item_ids(&sections[4]), vec!["quiet", "quiet-sync"]);
774 assert_eq!(sections[4].kind, SectionKind::Muted);
775 assert_eq!(sections[4].count, 2);
776 }
777
778 #[test]
779 fn turning_a_section_off_puts_its_chats_back_in_others() {
780 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
781 let directory = sectioned_directory(false, false, Vec::new());
782 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
783 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
784 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
785 }
786
787 #[test]
788 fn muted_is_on_and_meeting_is_off_until_the_user_chooses() {
789 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
790 let directory = Directory::default();
791 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
792 assert_eq!(section_ids(&sections), vec![OTHERS_ID, MUTED_ID]);
793 assert_eq!(item_ids(&sections[0]), vec!["sync"]);
794 }
795
796 #[test]
797 fn empty_system_sections_are_hidden() {
798 let chats = vec![chat("a", "group", false)];
799 let directory = sectioned_directory(true, true, Vec::new());
800 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
801 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
802 }
803
804 #[test]
805 fn sections_follow_the_server_folder_order_with_system_folders() {
806 let chats = vec![
807 chat("a", "group", false),
808 muted_chat("quiet"),
809 meeting_chat("sync"),
810 ];
811 let directory = sectioned_directory(
812 true,
813 true,
814 vec![
815 folder("muted-id", FolderKind::Muted, &[]),
816 folder("fav", FolderKind::Favorites, &[]),
817 folder("recent-id", FolderKind::Recent, &[]),
818 folder("meeting-id", FolderKind::Meeting, &[]),
819 ],
820 );
821 let collapsed: HashSet<String> = ["muted-id".to_owned()].into();
822 let sections = build_sections(&input(&chats, &directory, &collapsed));
823 assert_eq!(
824 section_ids(&sections),
825 vec!["muted-id", "fav", "recent-id", "meeting-id"]
826 );
827 assert!(sections[0].collapsed);
828 assert_eq!(sections[0].name, MUTED_NAME);
829 assert_eq!(sections[3].name, MEETING_NAME);
830 }
831
832 #[test]
833 fn newest_five_show_then_see_more_expands_and_see_less_collapses() {
834 let chats: Vec<ChatRecord> = (0..8)
835 .map(|index| muted_chat(&format!("m{index}")))
836 .collect();
837 let directory = Directory::default();
838 let collapsed = HashSet::new();
839 let sections = build_sections(&input(&chats, &directory, &collapsed));
840 let muted = &sections[1];
841 assert_eq!(item_ids(muted), vec!["m0", "m1", "m2", "m3", "m4"]);
842 assert_eq!(muted.count, 8);
843 assert_eq!(muted.hidden_count, 3);
844 assert!(!muted.list_expanded);
845
846 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
847 let mut context = input(&chats, &directory, &collapsed);
848 context.expanded_lists = &expanded;
849 let sections = build_sections(&context);
850 let muted = &sections[1];
851 assert_eq!(muted.items.len(), 8);
852 assert_eq!(muted.hidden_count, 0);
853 assert!(muted.list_expanded);
854 }
855
856 #[test]
857 fn five_chats_need_no_see_more_even_when_marked_expanded() {
858 let chats: Vec<ChatRecord> = (0..5)
859 .map(|index| muted_chat(&format!("m{index}")))
860 .collect();
861 let directory = Directory::default();
862 let collapsed = HashSet::new();
863 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
864 let mut context = input(&chats, &directory, &collapsed);
865 context.expanded_lists = &expanded;
866 let muted = &build_sections(&context)[1];
867 assert_eq!(muted.hidden_count, 0);
868 assert!(!muted.list_expanded);
869 }
870
871 #[test]
872 fn muted_section_keeps_unread_bold_without_a_badge_or_a_count() {
873 let mut quiet = muted_chat("quiet");
874 quiet.unread = true;
875 let chats = vec![
876 quiet,
877 ChatRecord {
878 muted: true,
879 ..meeting_chat("x")
880 },
881 ];
882 let mut directory = Directory::default();
883 directory.unread_counts.insert("quiet".into(), 4);
884 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
885 let muted = &sections[1];
886 assert_eq!(muted.items[0].unread, Unread::Silent);
887 assert!(muted.items[0].unread.is_unread());
888 assert_eq!(muted.unread_chats, 0);
889 assert_eq!(unread_chat_count(&chats), 0);
890 }
891
892 #[test]
893 fn meeting_chats_keep_their_unread_count() {
894 let mut sync = meeting_chat("sync");
895 sync.unread = true;
896 let chats = vec![sync];
897 let mut directory = sectioned_directory(true, true, Vec::new());
898 directory.unread_counts.insert("sync".into(), 3);
899 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
900 assert_eq!(sections[0].id, MEETING_ID);
901 assert_eq!(sections[0].items[0].unread, Unread::Count(3));
902 assert_eq!(sections[0].unread_chats, 1);
903 }
904}