BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

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