BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

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