BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

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