BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

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