BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

sidebar_model.rs 37.9 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2
3use chrono::{DateTime, FixedOffset, Utc};
4use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam};
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 = "Favorites";
15pub const OTHERS_NAME: &str = "Other chats";
16pub const OTHERS_ID: &str = "others";
17pub const MUTED_NAME: &str = "Muted";
18pub const MUTED_ID: &str = "muted_chats";
19pub const SECTION_PAGE_SIZE: usize = 5;
20pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
21pub const DELETED_PREVIEW: &str = "Message deleted";
22const OWN_PREFIX: &str = "You";
23const GROUP_KIND: &str = "group";
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum Preview {
27 Empty,
28 Deleted,
29 Typing(String),
30 Text {
31 prefix: Option<String>,
32 text: String,
33 },
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Unread {
38 None,
39 Silent,
40 Dot,
41 Count(u32),
42}
43
44impl Unread {
45 pub fn is_unread(self) -> bool {
46 self != Unread::None
47 }
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct Face {
52 pub user_id: Option<String>,
53 pub name: String,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum AvatarSpec {
58 Single(Face),
59 Pair(Face, Face),
60 Meeting,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct ChatItem {
65 pub id: String,
66 pub title: String,
67 pub time_label: String,
68 pub preview: Preview,
69 pub unread: Unread,
70 pub muted: bool,
71 pub is_group: bool,
72 pub member_count: usize,
73 pub avatar: AvatarSpec,
74 pub presence_user: Option<String>,
75 pub folder_id: Option<String>,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum SectionKind {
80 Favorites,
81 Folder,
82 Others,
83 Muted,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct Section {
88 pub id: String,
89 pub name: String,
90 pub kind: SectionKind,
91 pub collapsed: bool,
92 pub count: usize,
93 pub unread_chats: u32,
94 pub items: Vec<ChatItem>,
95 pub hidden_count: usize,
96 pub list_expanded: bool,
97 pub show_empty_hint: bool,
98}
99
100pub struct SectionInput<'a> {
101 pub chats: &'a [ChatRecord],
102 pub directory: &'a Directory,
103 pub collapsed: &'a HashSet<String>,
104 pub expanded_lists: &'a HashSet<String>,
105 pub typing: &'a TypingState,
106 pub now: DateTime<Utc>,
107 pub offset: FixedOffset,
108}
109
110pub fn preview_for(chat: &ChatRecord, me: Option<&Person>) -> Preview {
111 if chat.last_message_deleted {
112 return Preview::Deleted;
113 }
114 let Some(text) = chat
115 .last_message_preview
116 .as_deref()
117 .map(str::trim)
118 .filter(|text| !text.is_empty())
119 else {
120 return Preview::Empty;
121 };
122 let from_me = match (chat.last_message_sender_id.as_deref(), me) {
123 (Some(sender), Some(me)) => sender == me.user_id,
124 _ => false,
125 };
126 let prefix = if from_me {
127 Some(OWN_PREFIX.to_owned())
128 } else if is_one_on_one(chat) {
129 None
130 } else {
131 chat.last_message_sender_name
132 .as_deref()
133 .map(|name| format::first_name(name).to_owned())
134 .filter(|name| !name.is_empty())
135 };
136 Preview::Text {
137 prefix,
138 text: text.to_owned(),
139 }
140}
141
142pub fn avatar_for(chat: &ChatRecord, me: Option<&Person>) -> AvatarSpec {
143 if chat.kind.eq_ignore_ascii_case("meeting") {
144 return AvatarSpec::Meeting;
145 }
146 let faces = face_members(chat, me);
147 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
148 if 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 rest = Vec::new();
265 for chat in input
266 .chats
267 .iter()
268 .filter(|chat| !placed.contains(chat.id.as_str()))
269 {
270 let item = chat_item(chat, input, None);
271 if chat.muted && settings.enabled(ChatSection::Muted) {
272 muted.push(item);
273 } else {
274 rest.push(item);
275 }
276 }
277 let folder_id = |kind: FolderKind, fallback: &str| {
278 input
279 .directory
280 .folders
281 .iter()
282 .find(|folder| folder.kind == kind)
283 .map_or_else(|| fallback.to_owned(), |folder| folder.id.clone())
284 };
285 let mut others = Some(section(
286 folder_id(FolderKind::Recent, OTHERS_ID),
287 OTHERS_NAME.to_owned(),
288 SectionKind::Others,
289 rest,
290 input,
291 ));
292 let mut muted = (!muted.is_empty()).then(|| {
293 section(
294 folder_id(FolderKind::Muted, MUTED_ID),
295 MUTED_NAME.to_owned(),
296 SectionKind::Muted,
297 muted,
298 input,
299 )
300 });
301 let mut sections = Vec::new();
302 for (folder, section) in input.directory.folders.iter().zip(&mut built) {
303 match folder.kind {
304 FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()),
305 FolderKind::Recent => sections.extend(others.take()),
306 FolderKind::Meeting => {}
307 FolderKind::Muted => sections.extend(muted.take()),
308 }
309 }
310 sections.extend(others);
311 sections.extend(muted);
312 sections
313}
314
315pub fn wants_older_chats(
316 others_end: Option<f32>,
317 viewport_bottom: f32,
318 scroll_top: f32,
319 last_trigger_top: Option<f32>,
320 loading: bool,
321) -> bool {
322 !loading
323 && others_end.is_some_and(|end| end <= viewport_bottom)
324 && last_trigger_top != Some(scroll_top)
325}
326
327pub fn older_chats_trigger_resets(previous: (bool, bool), current: (bool, bool)) -> bool {
328 let ((had_more, was_loading), (has_more, is_loading)) = (previous, current);
329 (was_loading && !is_loading) || (!had_more && has_more)
330}
331
332pub fn visible_chat_ids(sections: &[Section]) -> Vec<&str> {
333 sections
334 .iter()
335 .filter(|section| !section.collapsed)
336 .flat_map(|section| section.items.iter().map(|item| item.id.as_str()))
337 .collect()
338}
339
340pub fn next_chat_id(sections: &[Section], removed_id: &str) -> Option<String> {
341 let visible = visible_chat_ids(sections);
342 let position = visible.iter().position(|id| *id == removed_id)?;
343 visible
344 .get(position + 1)
345 .or_else(|| {
346 position
347 .checked_sub(1)
348 .and_then(|previous| visible.get(previous))
349 })
350 .map(|id| (*id).to_owned())
351}
352
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354pub enum Step {
355 Previous,
356 Next,
357}
358
359pub fn step_id(ids: &[&str], current: Option<&str>, step: Step) -> Option<String> {
360 let position = current.and_then(|current| ids.iter().position(|id| *id == current));
361 let target = match (position, step) {
362 (Some(position), Step::Next) => position + 1,
363 (Some(position), Step::Previous) => position.checked_sub(1)?,
364 (None, Step::Next) => 0,
365 (None, Step::Previous) => ids.len().checked_sub(1)?,
366 };
367 ids.get(target).map(|id| (*id).to_owned())
368}
369
370pub struct ChannelOrderInput<'a> {
371 pub teams: &'a [SidebarTeam],
372 pub pinned_ids: &'a [String],
373 pub collapsed_teams: &'a HashSet<String>,
374 pub revealed_channel_teams: &'a HashSet<String>,
375 pub hidden_teams_open: bool,
376 pub selected_channel: Option<&'a str>,
377}
378
379pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {
380 let mut ids: Vec<&str> = Vec::new();
381 let mut push = |id: &'a str| {
382 if !ids.contains(&id) {
383 ids.push(id);
384 }
385 };
386 for pinned_id in input.pinned_ids {
387 let known = input
388 .teams
389 .iter()
390 .flat_map(|entry| entry.channels.iter())
391 .find(|channel| &channel.id == pinned_id);
392 if let Some(channel) = known {
393 push(&channel.id);
394 }
395 }
396 let holds_selection = |entry: &SidebarTeam| {
397 entry
398 .channels
399 .iter()
400 .any(|channel| Some(channel.id.as_str()) == input.selected_channel)
401 };
402 let hidden_teams_shown = input.hidden_teams_open
403 || input
404 .teams
405 .iter()
406 .any(|entry| entry.hidden && holds_selection(entry));
407 let teams = input.teams.iter().filter(|entry| !entry.hidden).chain(
408 input
409 .teams
410 .iter()
411 .filter(|entry| entry.hidden && hidden_teams_shown),
412 );
413 for entry in teams {
414 if input.collapsed_teams.contains(&entry.team.id) {
415 continue;
416 }
417 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
418 let is_selected =
419 |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
420 let revealed = input.revealed_channel_teams.contains(&entry.team.id);
421 for channel in entry
422 .channels
423 .iter()
424 .filter(|channel| !is_hidden(channel) || is_selected(channel))
425 {
426 push(&channel.id);
427 }
428 if revealed {
429 for channel in entry
430 .channels
431 .iter()
432 .filter(|channel| is_hidden(channel) && !is_selected(channel))
433 {
434 push(&channel.id);
435 }
436 }
437 }
438 ids
439}
440
441fn section(
442 id: String,
443 name: String,
444 kind: SectionKind,
445 mut items: Vec<ChatItem>,
446 input: &SectionInput<'_>,
447) -> Section {
448 let collapsed = input.collapsed.contains(&id);
449 let count = items.len();
450 let unread_chats = items
451 .iter()
452 .filter(|item| item.unread.is_unread() && !item.muted)
453 .count() as u32;
454 let paged = kind == SectionKind::Muted;
455 let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id);
456 let hidden_count = if paged && !list_expanded {
457 count.saturating_sub(SECTION_PAGE_SIZE)
458 } else {
459 0
460 };
461 items.truncate(count - hidden_count);
462 if kind == SectionKind::Muted {
463 for item in &mut items {
464 if item.unread.is_unread() {
465 item.unread = Unread::Silent;
466 }
467 }
468 }
469 Section {
470 collapsed,
471 count,
472 unread_chats,
473 hidden_count,
474 list_expanded,
475 show_empty_hint: items.is_empty()
476 && !collapsed
477 && matches!(kind, SectionKind::Favorites | SectionKind::Folder),
478 id,
479 name,
480 kind,
481 items,
482 }
483}
484
485#[cfg(test)]
486mod tests {
487 use chrono::TimeZone;
488 use store::MemberRecord;
489
490 use super::*;
491 use crate::data::FolderInfo;
492
493 fn me() -> Person {
494 Person {
495 user_id: "me".into(),
496 display_name: "Me Myself".into(),
497 }
498 }
499
500 fn chat(id: &str, kind: &str, unread: bool) -> ChatRecord {
501 ChatRecord {
502 id: id.into(),
503 kind: kind.into(),
504 title: id.to_uppercase(),
505 unread,
506 last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 7, 9, 30, 0).unwrap()),
507 members: vec![
508 MemberRecord {
509 user_id: Some("me".into()),
510 display_name: "Me Myself".into(),
511 },
512 MemberRecord {
513 user_id: Some("ada".into()),
514 display_name: "Ada Example".into(),
515 },
516 MemberRecord {
517 user_id: Some("bob".into()),
518 display_name: "Bob Sample".into(),
519 },
520 ],
521 ..Default::default()
522 }
523 }
524
525 fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo {
526 FolderInfo {
527 id: id.into(),
528 name: format!("name-{id}"),
529 kind,
530 expanded: None,
531 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
532 }
533 }
534
535 fn muted_chat(id: &str) -> ChatRecord {
536 ChatRecord {
537 muted: true,
538 ..chat(id, "group", false)
539 }
540 }
541
542 fn meeting_chat(id: &str) -> ChatRecord {
543 chat(id, "meeting", false)
544 }
545
546 fn sectioned_directory(muted: bool, folders: Vec<FolderInfo>) -> Directory {
547 let mut directory = Directory {
548 folders,
549 ..Default::default()
550 };
551 directory.section_settings.set(ChatSection::Muted, muted);
552 directory
553 }
554
555 fn section_ids(sections: &[Section]) -> Vec<&str> {
556 sections.iter().map(|section| section.id.as_str()).collect()
557 }
558
559 fn item_ids(section: &Section) -> Vec<&str> {
560 section.items.iter().map(|item| item.id.as_str()).collect()
561 }
562
563 fn input<'a>(
564 chats: &'a [ChatRecord],
565 directory: &'a Directory,
566 collapsed: &'a HashSet<String>,
567 ) -> SectionInput<'a> {
568 typing_input(chats, directory, collapsed, &NO_TYPING)
569 }
570
571 static NO_EXPANDED: std::sync::LazyLock<HashSet<String>> =
572 std::sync::LazyLock::new(HashSet::new);
573
574 static NO_TYPING: std::sync::LazyLock<TypingState> =
575 std::sync::LazyLock::new(TypingState::default);
576
577 fn typing_input<'a>(
578 chats: &'a [ChatRecord],
579 directory: &'a Directory,
580 collapsed: &'a HashSet<String>,
581 typing: &'a TypingState,
582 ) -> SectionInput<'a> {
583 SectionInput {
584 chats,
585 directory,
586 collapsed,
587 expanded_lists: &NO_EXPANDED,
588 typing,
589 now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),
590 offset: FixedOffset::east_opt(0).unwrap(),
591 }
592 }
593
594 #[test]
595 fn next_chat_is_the_following_row_then_the_previous_one() {
596 let chats = [
597 chat("a", "group", false),
598 chat("b", "group", false),
599 chat("c", "group", false),
600 ];
601 let directory = Directory::default();
602 let collapsed = HashSet::new();
603 let sections = build_sections(&input(&chats, &directory, &collapsed));
604 assert_eq!(next_chat_id(&sections, "a"), Some("b".to_owned()));
605 assert_eq!(next_chat_id(&sections, "c"), Some("b".to_owned()));
606 assert_eq!(next_chat_id(&sections, "zzz"), None);
607 let single = [chat("a", "group", false)];
608 let sections = build_sections(&input(&single, &directory, &collapsed));
609 assert_eq!(next_chat_id(&sections, "a"), None);
610 }
611
612 #[test]
613 fn stepping_follows_the_visible_order_without_wrapping() {
614 let ids = ["a", "b", "c"];
615 assert_eq!(step_id(&ids, Some("a"), Step::Next), Some("b".to_owned()));
616 assert_eq!(
617 step_id(&ids, Some("b"), Step::Previous),
618 Some("a".to_owned())
619 );
620 assert_eq!(step_id(&ids, Some("c"), Step::Next), None);
621 assert_eq!(step_id(&ids, Some("a"), Step::Previous), None);
622 assert_eq!(step_id(&ids, None, Step::Next), Some("a".to_owned()));
623 assert_eq!(
624 step_id(&ids, Some("gone"), Step::Previous),
625 Some("c".to_owned())
626 );
627 assert_eq!(step_id(&[], None, Step::Next), None);
628 }
629
630 #[test]
631 fn visible_chats_skip_collapsed_sections_and_see_more_rows() {
632 let mut chats = vec![chat("fav", "group", false), chat("hid", "group", false)];
633 chats.extend((0..7).map(|index| muted_chat(&format!("m{index}"))));
634 chats.push(chat("other", "group", false));
635 let directory = sectioned_directory(
636 true,
637 vec![
638 folder("fav-folder", FolderKind::Favorites, &["fav"]),
639 folder("work", FolderKind::UserCreated, &["hid"]),
640 folder("recent", FolderKind::Recent, &[]),
641 folder("muted-folder", FolderKind::Muted, &[]),
642 ],
643 );
644 let mut collapsed = HashSet::new();
645 let sections = build_sections(&input(&chats, &directory, &collapsed));
646 assert_eq!(
647 visible_chat_ids(&sections),
648 vec!["fav", "hid", "other", "m0", "m1", "m2", "m3", "m4"]
649 );
650 collapsed.insert("work".to_owned());
651 collapsed.insert("muted-folder".to_owned());
652 let sections = build_sections(&input(&chats, &directory, &collapsed));
653 assert_eq!(visible_chat_ids(&sections), vec!["fav", "other"]);
654 }
655
656 fn team(
657 id: &str,
658 hidden: bool,
659 channel_ids: &[&str],
660 hidden_channel_ids: &[&str],
661 ) -> SidebarTeam {
662 SidebarTeam {
663 team: store::TeamRecord {
664 id: id.into(),
665 name: id.into(),
666 },
667 channels: channel_ids
668 .iter()
669 .map(|channel_id| ChannelRecord {
670 id: (*channel_id).into(),
671 team_id: id.into(),
672 name: (*channel_id).into(),
673 membership_type: None,
674 last_message_at: None,
675 unread: false,
676 })
677 .collect(),
678 hidden,
679 hidden_channel_ids: hidden_channel_ids
680 .iter()
681 .map(|id| (*id).to_owned())
682 .collect(),
683 notifications: HashMap::new(),
684 }
685 }
686
687 #[test]
688 fn visible_channels_list_pinned_first_then_open_teams() {
689 let teams = [
690 team("t1", false, &["a", "b", "c"], &["b"]),
691 team("t2", false, &["d", "e"], &[]),
692 team("t3", true, &["f"], &[]),
693 ];
694 let pinned = ["e".to_owned(), "missing".to_owned()];
695 let order = |selected: Option<&str>,
696 hidden_teams_open: bool,
697 collapsed: &[&str],
698 revealed: &[&str]| {
699 let to_set = |ids: &[&str]| {
700 ids.iter()
701 .map(|id| (*id).to_owned())
702 .collect::<HashSet<_>>()
703 };
704 let (collapsed, revealed) = (to_set(collapsed), to_set(revealed));
705 let input = ChannelOrderInput {
706 teams: &teams,
707 pinned_ids: &pinned,
708 collapsed_teams: &collapsed,
709 revealed_channel_teams: &revealed,
710 hidden_teams_open,
711 selected_channel: selected,
712 };
713 visible_channel_ids(&input)
714 .into_iter()
715 .map(str::to_owned)
716 .collect::<Vec<_>>()
717 };
718 assert_eq!(order(None, false, &[], &[]), vec!["e", "a", "c", "d"]);
719 assert_eq!(
720 order(Some("b"), false, &[], &[]),
721 vec!["e", "a", "b", "c", "d"]
722 );
723 assert_eq!(
724 order(Some("f"), false, &[], &[]),
725 vec!["e", "a", "c", "d", "f"]
726 );
727 assert_eq!(order(None, true, &[], &[]), vec!["e", "a", "c", "d", "f"]);
728 assert_eq!(
729 order(None, true, &["t2"], &["t1"]),
730 vec!["e", "a", "c", "b", "f"]
731 );
732 }
733
734 #[test]
735 fn muted_chats_stay_out_of_unread_counts() {
736 let mut quiet = chat("a", "group", true);
737 quiet.muted = true;
738 let chats = [quiet, chat("b", "group", true)];
739 assert_eq!(unread_chat_count(&chats), 1);
740 let directory = Directory::default();
741 let collapsed = HashSet::new();
742 let sections = build_sections(&input(&chats, &directory, &collapsed));
743 assert_eq!(sections[0].unread_chats, 1);
744 assert_eq!(sections[1].kind, SectionKind::Muted);
745 assert!(sections[1].items[0].muted);
746 assert!(sections[1].items[0].unread.is_unread());
747 }
748
749 #[test]
750 fn preview_prefix_is_you_for_own_and_first_name_for_groups() {
751 let mut group = chat("g", "group", false);
752 group.last_message_preview = Some("Hello".into());
753 group.last_message_sender_id = Some("ada".into());
754 group.last_message_sender_name = Some("Ada Example".into());
755 assert_eq!(
756 preview_for(&group, Some(&me())),
757 Preview::Text {
758 prefix: Some("Ada".into()),
759 text: "Hello".into()
760 }
761 );
762 group.last_message_sender_id = Some("me".into());
763 assert_eq!(
764 preview_for(&group, Some(&me())),
765 Preview::Text {
766 prefix: Some("You".into()),
767 text: "Hello".into()
768 }
769 );
770 let mut direct = chat("d", "oneOnOne", false);
771 direct.last_message_preview = Some("Hi".into());
772 direct.last_message_sender_id = Some("ada".into());
773 direct.last_message_sender_name = Some("Ada Example".into());
774 assert_eq!(
775 preview_for(&direct, Some(&me())),
776 Preview::Text {
777 prefix: None,
778 text: "Hi".into()
779 }
780 );
781 }
782
783 #[test]
784 fn deleted_and_blank_previews() {
785 let mut deleted = chat("d", "group", false);
786 deleted.last_message_deleted = true;
787 deleted.last_message_preview = Some("secret".into());
788 assert_eq!(preview_for(&deleted, None), Preview::Deleted);
789 assert_eq!(
790 preview_for(&chat("e", "group", false), None),
791 Preview::Empty
792 );
793 }
794
795 #[test]
796 fn sections_follow_folder_order_and_leave_the_rest_for_others() {
797 let chats = vec![
798 chat("a", "group", false),
799 chat("b", "oneOnOne", true),
800 chat("c", "group", false),
801 chat("d", "group", false),
802 ];
803 let directory = Directory {
804 me: Some(me()),
805 folders: vec![
806 folder("fav", FolderKind::Favorites, &["c"]),
807 folder("work", FolderKind::UserCreated, &["b", "gone", "a"]),
808 folder("todo", FolderKind::UserCreated, &[]),
809 ],
810 ..Default::default()
811 };
812 let collapsed = HashSet::new();
813 let sections = build_sections(&input(&chats, &directory, &collapsed));
814 let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect();
815 assert_eq!(ids, vec!["fav", "work", "todo", OTHERS_ID]);
816 let work: Vec<&str> = sections[1]
817 .items
818 .iter()
819 .map(|item| item.id.as_str())
820 .collect();
821 assert_eq!(work, vec!["b", "a"]);
822 assert_eq!(sections[1].count, 2);
823 assert_eq!(sections[2].count, 0);
824 assert!(sections[2].show_empty_hint);
825 let others: Vec<&str> = sections[3]
826 .items
827 .iter()
828 .map(|item| item.id.as_str())
829 .collect();
830 assert_eq!(others, vec!["d"]);
831 assert!(!sections[3].show_empty_hint);
832 }
833
834 #[test]
835 fn collapsed_sections_keep_the_aggregated_unread() {
836 let chats = vec![
837 chat("a", "group", true),
838 chat("b", "group", true),
839 chat("c", "group", false),
840 ];
841 let directory = Directory {
842 folders: vec![folder("work", FolderKind::UserCreated, &["a", "b", "c"])],
843 ..Default::default()
844 };
845 let collapsed: HashSet<String> = ["work".to_owned()].into();
846 let sections = build_sections(&input(&chats, &directory, &collapsed));
847 assert!(sections[0].collapsed);
848 assert_eq!(sections[0].unread_chats, 2);
849 assert_eq!(sections[0].count, 3);
850 assert!(!sections[0].show_empty_hint);
851 }
852
853 #[test]
854 fn collapsed_empty_folder_hides_the_hint() {
855 let directory = Directory {
856 folders: vec![folder("todo", FolderKind::UserCreated, &[])],
857 ..Default::default()
858 };
859 let collapsed: HashSet<String> = ["todo".to_owned()].into();
860 let sections = build_sections(&input(&[], &directory, &collapsed));
861 assert!(!sections[0].show_empty_hint);
862 }
863
864 #[test]
865 fn favorites_without_a_server_name_say_angeheftet() {
866 let mut favorites = folder("fav", FolderKind::Favorites, &[]);
867 favorites.name = String::new();
868 let directory = Directory {
869 folders: vec![favorites],
870 ..Default::default()
871 };
872 let sections = build_sections(&input(&[], &directory, &HashSet::new()));
873 assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
874 }
875
876 #[test]
877 fn unread_is_a_count_when_known_else_a_dot() {
878 let chats = vec![
879 chat("a", "group", true),
880 chat("b", "group", true),
881 chat("c", "group", false),
882 ];
883 let mut directory = Directory::default();
884 directory.unread_counts.insert("a".into(), 5);
885 let collapsed = HashSet::new();
886 let context = input(&chats, &directory, &collapsed);
887 assert_eq!(
888 chat_item(&chats[0], &context, None).unread,
889 Unread::Count(5)
890 );
891 assert_eq!(chat_item(&chats[1], &context, None).unread, Unread::Dot);
892 assert_eq!(chat_item(&chats[2], &context, None).unread, Unread::None);
893 assert_eq!(unread_chat_count(&chats), 2);
894 }
895
896 #[test]
897 fn one_on_one_has_presence_and_a_single_face_groups_have_a_pair() {
898 let directory = Directory {
899 me: Some(me()),
900 ..Default::default()
901 };
902 let collapsed = HashSet::new();
903 let chats = vec![chat("d", "oneOnOne", false), chat("g", "group", false)];
904 let context = input(&chats, &directory, &collapsed);
905 let direct = chat_item(&chats[0], &context, None);
906 assert_eq!(direct.presence_user.as_deref(), Some("ada"));
907 assert!(
908 matches!(direct.avatar, AvatarSpec::Single(ref face) if face.name == "Ada Example")
909 );
910 let group = chat_item(&chats[1], &context, None);
911 assert_eq!(group.presence_user, None);
912 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
913 assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);
914 }
915
916 #[test]
917 fn typing_replaces_the_preview_even_in_muted_chats() {
918 let mut direct = chat("d", "oneOnOne", false);
919 direct.last_message_preview = Some("Earlier".into());
920 direct.muted = true;
921 let group = chat("g", "group", false);
922 let chats = vec![direct, group];
923 let directory = Directory::default();
924 let collapsed = HashSet::new();
925 let now = std::time::Instant::now();
926 let mut typing = TypingState::default();
927 typing.start("d", "ada", "Ada Example", now, Utc::now());
928 typing.start("g", "ada", "Ada Example", now, Utc::now());
929 let context = typing_input(&chats, &directory, &collapsed, &typing);
930 assert_eq!(
931 chat_item(&chats[0], &context, None).preview,
932 Preview::Typing("typing...".into())
933 );
934 assert_eq!(
935 chat_item(&chats[1], &context, None).preview,
936 Preview::Typing("Ada is typing...".into())
937 );
938 typing.clear("d", "ada");
939 let context = typing_input(&chats, &directory, &collapsed, &typing);
940 assert_eq!(
941 chat_item(&chats[0], &context, None).preview,
942 Preview::Text {
943 prefix: None,
944 text: "Earlier".into()
945 }
946 );
947 }
948
949 #[test]
950 fn time_label_uses_the_list_rules() {
951 let chats = vec![chat("a", "group", false)];
952 let directory = Directory::default();
953 let collapsed = HashSet::new();
954 let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None);
955 assert_eq!(item.time_label, "09:30");
956 }
957
958 #[test]
959 fn muted_chats_leave_others_unless_pinned_or_in_a_custom_section_and_meeting_chats_stay() {
960 let chats = vec![
961 chat("plain", "group", false),
962 muted_chat("quiet"),
963 muted_chat("pinned-quiet"),
964 meeting_chat("sync"),
965 meeting_chat("custom-sync"),
966 ChatRecord {
967 muted: true,
968 ..meeting_chat("quiet-sync")
969 },
970 ];
971 let directory = sectioned_directory(
972 true,
973 vec![
974 folder("fav", FolderKind::Favorites, &["pinned-quiet"]),
975 folder("work", FolderKind::UserCreated, &["custom-sync"]),
976 ],
977 );
978 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
979 assert_eq!(
980 section_ids(&sections),
981 vec!["fav", "work", OTHERS_ID, MUTED_ID]
982 );
983 assert_eq!(item_ids(&sections[0]), vec!["pinned-quiet"]);
984 assert_eq!(item_ids(&sections[1]), vec!["custom-sync"]);
985 assert_eq!(item_ids(&sections[2]), vec!["plain", "sync"]);
986 assert_eq!(item_ids(&sections[3]), vec!["quiet", "quiet-sync"]);
987 assert_eq!(sections[3].kind, SectionKind::Muted);
988 assert_eq!(sections[3].count, 2);
989 }
990
991 #[test]
992 fn turning_the_muted_section_off_puts_its_chats_back_in_others() {
993 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
994 let directory = sectioned_directory(false, Vec::new());
995 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
996 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
997 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
998 }
999
1000 #[test]
1001 fn muted_is_on_until_the_user_chooses_and_meeting_chats_stay_in_others() {
1002 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
1003 let directory = Directory::default();
1004 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1005 assert_eq!(section_ids(&sections), vec![OTHERS_ID, MUTED_ID]);
1006 assert_eq!(item_ids(&sections[0]), vec!["sync"]);
1007 }
1008
1009 #[test]
1010 fn older_chats_load_only_when_the_end_of_other_chats_is_on_screen_once_per_scroll_position() {
1011 assert!(wants_older_chats(Some(900.), 1000., 0., None, false));
1012 assert!(!wants_older_chats(Some(1500.), 1000., 0., None, false));
1013 assert!(!wants_older_chats(None, 1000., 0., None, false));
1014 assert!(!wants_older_chats(Some(900.), 1000., 0., Some(0.), false));
1015 assert!(wants_older_chats(Some(900.), 1000., 120., Some(0.), false));
1016 }
1017
1018 #[test]
1019 fn a_running_load_never_consumes_the_trigger() {
1020 assert!(!wants_older_chats(Some(900.), 1000., 0., None, true));
1021 }
1022
1023 #[test]
1024 fn the_trigger_resets_when_a_load_ends_or_more_chats_appear_but_not_while_idle() {
1025 assert!(older_chats_trigger_resets((true, true), (true, false)));
1026 assert!(older_chats_trigger_resets((true, true), (false, false)));
1027 assert!(older_chats_trigger_resets((false, false), (true, false)));
1028 assert!(!older_chats_trigger_resets((true, false), (true, false)));
1029 assert!(!older_chats_trigger_resets((true, false), (true, true)));
1030 assert!(!older_chats_trigger_resets((false, false), (false, false)));
1031 }
1032
1033 #[test]
1034 fn empty_system_sections_are_hidden() {
1035 let chats = vec![chat("a", "group", false)];
1036 let directory = sectioned_directory(true, Vec::new());
1037 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1038 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1039 }
1040
1041 #[test]
1042 fn sections_follow_the_server_folder_order_with_system_folders() {
1043 let chats = vec![
1044 chat("a", "group", false),
1045 muted_chat("quiet"),
1046 meeting_chat("sync"),
1047 ];
1048 let directory = sectioned_directory(
1049 true,
1050 vec![
1051 folder("muted-id", FolderKind::Muted, &[]),
1052 folder("fav", FolderKind::Favorites, &[]),
1053 folder("recent-id", FolderKind::Recent, &[]),
1054 folder("meeting-id", FolderKind::Meeting, &[]),
1055 ],
1056 );
1057 let collapsed: HashSet<String> = ["muted-id".to_owned()].into();
1058 let sections = build_sections(&input(&chats, &directory, &collapsed));
1059 assert_eq!(section_ids(&sections), vec!["muted-id", "fav", "recent-id"]);
1060 assert!(sections[0].collapsed);
1061 assert_eq!(sections[0].name, MUTED_NAME);
1062 assert_eq!(item_ids(&sections[2]), vec!["a", "sync"]);
1063 }
1064
1065 #[test]
1066 fn newest_five_show_then_see_more_expands_and_see_less_collapses() {
1067 let chats: Vec<ChatRecord> = (0..8)
1068 .map(|index| muted_chat(&format!("m{index}")))
1069 .collect();
1070 let directory = Directory::default();
1071 let collapsed = HashSet::new();
1072 let sections = build_sections(&input(&chats, &directory, &collapsed));
1073 let muted = &sections[1];
1074 assert_eq!(item_ids(muted), vec!["m0", "m1", "m2", "m3", "m4"]);
1075 assert_eq!(muted.count, 8);
1076 assert_eq!(muted.hidden_count, 3);
1077 assert!(!muted.list_expanded);
1078
1079 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
1080 let mut context = input(&chats, &directory, &collapsed);
1081 context.expanded_lists = &expanded;
1082 let sections = build_sections(&context);
1083 let muted = &sections[1];
1084 assert_eq!(muted.items.len(), 8);
1085 assert_eq!(muted.hidden_count, 0);
1086 assert!(muted.list_expanded);
1087 }
1088
1089 #[test]
1090 fn five_chats_need_no_see_more_even_when_marked_expanded() {
1091 let chats: Vec<ChatRecord> = (0..5)
1092 .map(|index| muted_chat(&format!("m{index}")))
1093 .collect();
1094 let directory = Directory::default();
1095 let collapsed = HashSet::new();
1096 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
1097 let mut context = input(&chats, &directory, &collapsed);
1098 context.expanded_lists = &expanded;
1099 let muted = &build_sections(&context)[1];
1100 assert_eq!(muted.hidden_count, 0);
1101 assert!(!muted.list_expanded);
1102 }
1103
1104 #[test]
1105 fn muted_section_keeps_unread_bold_without_a_badge_or_a_count() {
1106 let mut quiet = muted_chat("quiet");
1107 quiet.unread = true;
1108 let chats = vec![
1109 quiet,
1110 ChatRecord {
1111 muted: true,
1112 ..meeting_chat("x")
1113 },
1114 ];
1115 let mut directory = Directory::default();
1116 directory.unread_counts.insert("quiet".into(), 4);
1117 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1118 let muted = &sections[1];
1119 assert_eq!(muted.items[0].unread, Unread::Silent);
1120 assert!(muted.items[0].unread.is_unread());
1121 assert_eq!(muted.unread_chats, 0);
1122 assert_eq!(unread_chat_count(&chats), 0);
1123 }
1124
1125 #[test]
1126 fn meeting_chats_keep_their_unread_count_in_others() {
1127 let mut sync = meeting_chat("sync");
1128 sync.unread = true;
1129 let chats = vec![sync];
1130 let mut directory = sectioned_directory(true, Vec::new());
1131 directory.unread_counts.insert("sync".into(), 3);
1132 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1133 assert_eq!(sections[0].id, OTHERS_ID);
1134 assert_eq!(sections[0].items[0].unread, Unread::Count(3));
1135 assert_eq!(sections[0].unread_chats, 1);
1136 }
1137}