BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

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